From 68b60ccb8b235ea312c5131f75fb90a2abf1bdc2 Mon Sep 17 00:00:00 2001 From: apathy Date: Fri, 3 Jun 2016 21:30:08 -0700 Subject: [PATCH] Initial project commit Added udplibrary - consider making this an external dependency Add basic application loop and a ServiceContainer class. Added basic registrar service Clang format Rename RegistrarService to RegistrarNode Add serialization helpers Process GetChatServer message Add tools for streaming binary data to output Move Connection management into NodeClient Refactored NodeClient to be the layer between the application and the udp library that handles tasks specific to translating from one system to the other Abstracted common bits of the node class out to a reusable base for the gateway as well. Added stub classes for gateway node and clients Add missing OnTick call Added SetApiVersion handler and related messages Use :: to prevent the overload selected by argument dependent lookup from being used Enable C++14 building on gcc/clang Add missing header Iterator returned by remove_if should not be a ref Added start of ChatAvatarService Add serialization support directly for strongly typed enums Make sending message calls more concise Add stubs for getting avatars from the online list and from persistent storage Add SQLite3 dependency Fixed variable name regression in last commit Make param for SendMessage const Tweak network message logging Removed ServiceContainer, each Node instance serves as its own "service container" Remove unused file Open database connection in GatewayNode to pass to services that might need it. GetPersistedAvatarByNameAndAddress implemented Refactored class to return boost::optional from "Find" member functions. Move result codes enum to its own header as it will be included in other locations. Handle LoginAvatar messages Added missing include Fixed compile error on gcc Use optional avatar arguments for network messages where an avatar might not exist due to an error Added simple sql script for creating the necessary table structure. Move init_database.sql to extras Add a travis-ci file Added newline to end of file Changed min required cmake version Modern C++ compiler support on travis-ci Disable clang for now (issue on travis-ci end) Missed disabling the llvm toolchain Add the travis-ci build badge to the README, which also serves as the project landing page Added a notes on the dependencies for swgchat and simple build instructions. Added ChatRoom and related service class for managing rooms. Added GetRoomSummaries request/response messages and related handler. Added create table statement for room data Load chat room data from persistent storage Support room creation and persistence Minor tweaks to room address handling Added GetRoom request/response messages and handler Added EnterRoom request/response and handler Build the application configuration from command line, config file or both. Command line settings take precidence over those in the config file. Adds dependency on boost::program_options Use trusty Reset state when servers reconnect Added logger support via easyloggingpp, a header-only logger. Updated places that were using cout for logging to use the logger. Moved all external code to an "externals" directory. Renamed SendMessage to prevent pita clashes when windows headers get included. Create verbose logs with unique filenames on each run. Moved the logger_config option to a commandline only option Added LOGOUTAVATAR request/response messages and handler Added SETAVATARATTRIBUTES request/response messages and handler Added stub classes for persistent message handling Added GETPERSISTENTHEADERS request message and handler stub Add a table for persistent message storage Add handler for GetPersistentHeaders Add messages and handlers for sending/getting/updating persistent messages Fix isset check for avatar Adding initial Contact management Added support for friend/ignore list management Add a response callback message to notify recipients of mail they have a new message Remove the ContactService, manage friends/ignore list within the related avatar Send FRIENDLOGIN update messages Removed contact.hpp header, fixed cyclic dependency with ChatAvatar Send updates on avatar logout Only send non-deleted message headers. Send update messages to the appropriately connected server. fix compile issue in currently unused template Added instant message support Testing travis-ci with clang once more as the llvm apt repo is now back online Uncommented clang-3.7 package Adding libc++ and libc++abi packages Disabling clang building for now, will need to devise a solution for building the boost dependency with clang as well before enabling again Added implementations for a number of room related messages. Handle add/remove banned - will add persistence for the banned/admin/moderator lists shortly Handle room chat. Initial work on room moderation/attribute management Added support for destroying rooms Message sending tweaks Prevent sending redundant messages to a game server that has already received the update. Implement the leave room handler Added add/remove moderator handlers Added descriptive comment for this member func Specified unique columns and foreign keys Handle storing moderator/banned lists Cleanup of the EnterRoom handler Avatar that creates a room is also a moderator Restructure projects for testing Moved all code not relating to the app lifetime to a library so it can be easily linked to for testing In addition, the initial setup for tests using the Catch library was created Add a general handler to orchestrate the request/response process. This pulls all the duplicate code for setup/teardown/message handling leaving the message handlers to be simpler and easier to take in. Moving each request/response/handler set to its own compilation unit to make it easier to find and read them. Moved LogoutAvatar to its own compilation unit Moved CreateRoom to its own compilation unit Moved DestroyRoom to its own compilation unit Moved SendInstantMessage to own compilation unit Also added a basic info log for each incoming request received. Moved SendRoomMessage to its own compilation unit Moved AddFriend handling to its own compilation unit Moved RemoveFriend handling to its own compilation unit Moved FriendStatus handling to its own compilation unit Moved AddIgnore handling to its own compilation unit Moved RemoveIgnore to its own compilation unit Moved EnterRoom handling to its own compilation unit Moved LeaveRoom handling to its own compilation unit Move AddModerator to its own compilation unit Moved RemoveModerator to its own compilation unit Moved add/remove banned handlers to own compilation unit Move Add/Remove invite handlers to own compilation unit Move GetRoom handler to own compilation unit Moved GetRoomSummaries handler to own compilation unit Moved persistent message handlers to own compilation unit Moved IgnoreStatus to own compilation unit Move SetApiVersion handler to own compilation unit Moved GetAnyAvatar and SetAvatarAttributes handlers to own compilation units Moving remaining messages to own compilation units Moved request/response enums to the ChatEnum header Fix typename issue Fixed source grouping helper Load up a galaxies rooms when system user logs in Use stringstreams vs static array As more rooms and more players are added, the buffer holding the serialized data needs to be able to expand accordingly, this fix addresses that throw appropriate exceptions from the message service ChatAvatar tracks rooms they are in now LogoutAvatar now removes avatar from all rooms they are joined to currently. Add appropriate checks for managing the room String version of error codes are now logged instead of just integer codes Implement kick avatar Fixes potential crash when the vector of rooms is resized (could invalidate pointers into the container) fix for persistent message oob storage Support for destroying avatars Fixed unsigned/signed mismatch Support failoverreloginavatar Replace wstring usage (which has a base type of wchar_t that is OS specific) with u16string which has a base type of uchar16_t that is guaranteed to be 16bit, exactly the size needed by the SOE protocol. Fix issue with streaming u16string types Remove udplibrary source from codebase Ignore the udplibrary dir if it exists --- .gitignore | 1 + .travis.yml | 29 + CMakeLists.txt | 40 + README.md | 37 + cmake/FindSQLite3.cmake | 25 + cmake/GroupSourceByFilesystem.cmake | 16 + cmake/ModernCpp.cmake | 9 + externals/CMakeLists.txt | 4 + externals/catch/catch.hpp | 10593 +++++++++++++++++++++ externals/easyloggingpp/LICENCE | 24 + externals/easyloggingpp/easylogging++.h | 6663 +++++++++++++ extras/init_database.sql | 73 + extras/logger.cfg.dist | 18 + extras/swgchat.cfg.dist | 14 + src/CMakeLists.txt | 132 + src/ChatAvatar.cpp | 107 + src/ChatAvatar.hpp | 135 + src/ChatAvatarService.cpp | 488 + src/ChatAvatarService.hpp | 65 + src/ChatEnums.cpp | 152 + src/ChatEnums.hpp | 252 + src/ChatRoom.cpp | 307 + src/ChatRoom.hpp | 169 + src/ChatRoomService.cpp | 407 + src/ChatRoomService.hpp | 57 + src/Contact.hpp | 38 + src/GatewayClient.cpp | 245 + src/GatewayClient.hpp | 69 + src/GatewayNode.cpp | 39 + src/GatewayNode.hpp | 45 + src/Message.hpp | 298 + src/Node.hpp | 52 + src/NodeClient.cpp | 30 + src/NodeClient.hpp | 35 + src/PersistentMessage.hpp | 51 + src/PersistentMessageService.cpp | 210 + src/PersistentMessageService.hpp | 30 + src/RegistrarClient.cpp | 45 + src/RegistrarClient.hpp | 22 + src/RegistrarNode.cpp | 17 + src/RegistrarNode.hpp | 20 + src/SQLite3.hpp | 14 + src/Serialization.hpp | 119 + src/StationChatApp.cpp | 17 + src/StationChatApp.hpp | 25 + src/StationChatConfig.hpp | 24 + src/StreamUtils.cpp | 75 + src/StreamUtils.hpp | 28 + src/StringUtils.cpp | 10 + src/StringUtils.hpp | 8 + src/main.cpp | 91 + src/protocol/AddBan.cpp | 38 + src/protocol/AddBan.hpp | 63 + src/protocol/AddFriend.cpp | 30 + src/protocol/AddFriend.hpp | 62 + src/protocol/AddIgnore.cpp | 26 + src/protocol/AddIgnore.hpp | 58 + src/protocol/AddInvite.cpp | 38 + src/protocol/AddInvite.hpp | 63 + src/protocol/AddModerator.cpp | 39 + src/protocol/AddModerator.hpp | 63 + src/protocol/CreateRoom.cpp | 21 + src/protocol/CreateRoom.hpp | 83 + src/protocol/DestroyAvatar.cpp | 29 + src/protocol/DestroyAvatar.hpp | 55 + src/protocol/DestroyRoom.cpp | 42 + src/protocol/DestroyRoom.hpp | 59 + src/protocol/EnterRoom.cpp | 33 + src/protocol/EnterRoom.hpp | 89 + src/protocol/FailoverReLoginAvatar.cpp | 38 + src/protocol/FailoverReLoginAvatar.hpp | 64 + src/protocol/FriendStatus.cpp | 22 + src/protocol/FriendStatus.hpp | 70 + src/protocol/GetAnyAvatar.cpp | 24 + src/protocol/GetAnyAvatar.hpp | 68 + src/protocol/GetPersistentHeaders.cpp | 17 + src/protocol/GetPersistentHeaders.hpp | 62 + src/protocol/GetPersistentMessage.cpp | 17 + src/protocol/GetPersistentMessage.hpp | 60 + src/protocol/GetRoom.cpp | 20 + src/protocol/GetRoom.hpp | 65 + src/protocol/GetRoomSummaries.cpp | 18 + src/protocol/GetRoomSummaries.hpp | 67 + src/protocol/IgnoreStatus.cpp | 22 + src/protocol/IgnoreStatus.hpp | 67 + src/protocol/KickAvatar.cpp | 39 + src/protocol/KickAvatar.hpp | 63 + src/protocol/LeaveRoom.cpp | 31 + src/protocol/LeaveRoom.hpp | 59 + src/protocol/LoginAvatar.cpp | 36 + src/protocol/LoginAvatar.hpp | 69 + src/protocol/LogoutAvatar.cpp | 28 + src/protocol/LogoutAvatar.hpp | 54 + src/protocol/RegistrarGetChatServer.cpp | 18 + src/protocol/RegistrarGetChatServer.hpp | 54 + src/protocol/RemoveBan.cpp | 38 + src/protocol/RemoveBan.hpp | 63 + src/protocol/RemoveFriend.cpp | 28 + src/protocol/RemoveFriend.hpp | 58 + src/protocol/RemoveIgnore.cpp | 27 + src/protocol/RemoveIgnore.hpp | 58 + src/protocol/RemoveInvite.cpp | 39 + src/protocol/RemoveInvite.hpp | 63 + src/protocol/RemoveModerator.cpp | 35 + src/protocol/RemoveModerator.hpp | 63 + src/protocol/SendInstantMessage.cpp | 28 + src/protocol/SendInstantMessage.hpp | 62 + src/protocol/SendPersistentMessage.cpp | 48 + src/protocol/SendPersistentMessage.hpp | 83 + src/protocol/SendRoomMessage.cpp | 33 + src/protocol/SendRoomMessage.hpp | 68 + src/protocol/SetApiVersion.cpp | 16 + src/protocol/SetApiVersion.hpp | 55 + src/protocol/SetAvatarAttributes.cpp | 27 + src/protocol/SetAvatarAttributes.hpp | 63 + src/protocol/UpdatePersistentMessage.cpp | 14 + src/protocol/UpdatePersistentMessage.hpp | 56 + tests/CMakeLists.txt | 8 + tests/main.cpp | 2 + 119 files changed, 24552 insertions(+) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 CMakeLists.txt create mode 100644 README.md create mode 100644 cmake/FindSQLite3.cmake create mode 100644 cmake/GroupSourceByFilesystem.cmake create mode 100644 cmake/ModernCpp.cmake create mode 100644 externals/CMakeLists.txt create mode 100644 externals/catch/catch.hpp create mode 100644 externals/easyloggingpp/LICENCE create mode 100644 externals/easyloggingpp/easylogging++.h create mode 100644 extras/init_database.sql create mode 100644 extras/logger.cfg.dist create mode 100644 extras/swgchat.cfg.dist create mode 100644 src/CMakeLists.txt create mode 100644 src/ChatAvatar.cpp create mode 100644 src/ChatAvatar.hpp create mode 100644 src/ChatAvatarService.cpp create mode 100644 src/ChatAvatarService.hpp create mode 100644 src/ChatEnums.cpp create mode 100644 src/ChatEnums.hpp create mode 100644 src/ChatRoom.cpp create mode 100644 src/ChatRoom.hpp create mode 100644 src/ChatRoomService.cpp create mode 100644 src/ChatRoomService.hpp create mode 100644 src/Contact.hpp create mode 100644 src/GatewayClient.cpp create mode 100644 src/GatewayClient.hpp create mode 100644 src/GatewayNode.cpp create mode 100644 src/GatewayNode.hpp create mode 100644 src/Message.hpp create mode 100644 src/Node.hpp create mode 100644 src/NodeClient.cpp create mode 100644 src/NodeClient.hpp create mode 100644 src/PersistentMessage.hpp create mode 100644 src/PersistentMessageService.cpp create mode 100644 src/PersistentMessageService.hpp create mode 100644 src/RegistrarClient.cpp create mode 100644 src/RegistrarClient.hpp create mode 100644 src/RegistrarNode.cpp create mode 100644 src/RegistrarNode.hpp create mode 100644 src/SQLite3.hpp create mode 100644 src/Serialization.hpp create mode 100644 src/StationChatApp.cpp create mode 100644 src/StationChatApp.hpp create mode 100644 src/StationChatConfig.hpp create mode 100644 src/StreamUtils.cpp create mode 100644 src/StreamUtils.hpp create mode 100644 src/StringUtils.cpp create mode 100644 src/StringUtils.hpp create mode 100644 src/main.cpp create mode 100644 src/protocol/AddBan.cpp create mode 100644 src/protocol/AddBan.hpp create mode 100644 src/protocol/AddFriend.cpp create mode 100644 src/protocol/AddFriend.hpp create mode 100644 src/protocol/AddIgnore.cpp create mode 100644 src/protocol/AddIgnore.hpp create mode 100644 src/protocol/AddInvite.cpp create mode 100644 src/protocol/AddInvite.hpp create mode 100644 src/protocol/AddModerator.cpp create mode 100644 src/protocol/AddModerator.hpp create mode 100644 src/protocol/CreateRoom.cpp create mode 100644 src/protocol/CreateRoom.hpp create mode 100644 src/protocol/DestroyAvatar.cpp create mode 100644 src/protocol/DestroyAvatar.hpp create mode 100644 src/protocol/DestroyRoom.cpp create mode 100644 src/protocol/DestroyRoom.hpp create mode 100644 src/protocol/EnterRoom.cpp create mode 100644 src/protocol/EnterRoom.hpp create mode 100644 src/protocol/FailoverReLoginAvatar.cpp create mode 100644 src/protocol/FailoverReLoginAvatar.hpp create mode 100644 src/protocol/FriendStatus.cpp create mode 100644 src/protocol/FriendStatus.hpp create mode 100644 src/protocol/GetAnyAvatar.cpp create mode 100644 src/protocol/GetAnyAvatar.hpp create mode 100644 src/protocol/GetPersistentHeaders.cpp create mode 100644 src/protocol/GetPersistentHeaders.hpp create mode 100644 src/protocol/GetPersistentMessage.cpp create mode 100644 src/protocol/GetPersistentMessage.hpp create mode 100644 src/protocol/GetRoom.cpp create mode 100644 src/protocol/GetRoom.hpp create mode 100644 src/protocol/GetRoomSummaries.cpp create mode 100644 src/protocol/GetRoomSummaries.hpp create mode 100644 src/protocol/IgnoreStatus.cpp create mode 100644 src/protocol/IgnoreStatus.hpp create mode 100644 src/protocol/KickAvatar.cpp create mode 100644 src/protocol/KickAvatar.hpp create mode 100644 src/protocol/LeaveRoom.cpp create mode 100644 src/protocol/LeaveRoom.hpp create mode 100644 src/protocol/LoginAvatar.cpp create mode 100644 src/protocol/LoginAvatar.hpp create mode 100644 src/protocol/LogoutAvatar.cpp create mode 100644 src/protocol/LogoutAvatar.hpp create mode 100644 src/protocol/RegistrarGetChatServer.cpp create mode 100644 src/protocol/RegistrarGetChatServer.hpp create mode 100644 src/protocol/RemoveBan.cpp create mode 100644 src/protocol/RemoveBan.hpp create mode 100644 src/protocol/RemoveFriend.cpp create mode 100644 src/protocol/RemoveFriend.hpp create mode 100644 src/protocol/RemoveIgnore.cpp create mode 100644 src/protocol/RemoveIgnore.hpp create mode 100644 src/protocol/RemoveInvite.cpp create mode 100644 src/protocol/RemoveInvite.hpp create mode 100644 src/protocol/RemoveModerator.cpp create mode 100644 src/protocol/RemoveModerator.hpp create mode 100644 src/protocol/SendInstantMessage.cpp create mode 100644 src/protocol/SendInstantMessage.hpp create mode 100644 src/protocol/SendPersistentMessage.cpp create mode 100644 src/protocol/SendPersistentMessage.hpp create mode 100644 src/protocol/SendRoomMessage.cpp create mode 100644 src/protocol/SendRoomMessage.hpp create mode 100644 src/protocol/SetApiVersion.cpp create mode 100644 src/protocol/SetApiVersion.hpp create mode 100644 src/protocol/SetAvatarAttributes.cpp create mode 100644 src/protocol/SetAvatarAttributes.hpp create mode 100644 src/protocol/UpdatePersistentMessage.cpp create mode 100644 src/protocol/UpdatePersistentMessage.hpp create mode 100644 tests/CMakeLists.txt create mode 100644 tests/main.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3ac8df7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +externals/udplibrary \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..394343a --- /dev/null +++ b/.travis.yml @@ -0,0 +1,29 @@ +sudo: required +dist: trusty +language: cpp +compiler: + - gcc +script: + - mkdir build + - cd build + - cmake .. && make + +notifications: + email: + recipients: builds@eb2.co + on_success: change + on_failure: always + +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-5 + - gcc-5 + - libboost-dev + - libboost-program-options-dev + - libsqlite3-dev + +install: + - if [ "$CXX" = "g++" ]; then export CXX="g++-5" CC="gcc-5"; fi diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..082f94a --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,40 @@ +# don't allow in-source project generation +if (${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) + message(WARNING "\n\nCMake generation is not allowed within the source directory!\n") + message(STATUS "Cancelling CMake and cleaning up source tree...") + execute_process(COMMAND ${CMAKE_COMMAND} -E remove_directory "${CMAKE_BINARY_DIR}/CMakeFiles") + math(EXPR Crash 0/0) + message(FATAL_ERROR "CMake should have crashed - this is a failsafe in case the call used to trigger the crash gets fixed.") +endif() + +cmake_minimum_required(VERSION 2.8) + +project(stationapi CXX) + +set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") + +include(GroupSourceByFilesystem) +include(ModernCpp) +set_property(GLOBAL PROPERTY USE_FOLDERS ON) + +if (EXISTS "externals/udplibrary/CMakeLists.txt") + set(HAVE_UDPLIBRARY 1) +endif() + +add_definitions(-DBOOST_ALL_NO_LIB) +set(Boost_USE_STATIC_LIBS ON) +set(Boost_USE_MULTITHREADED ON) + +find_package(Boost COMPONENTS program_options REQUIRED) +find_package(SQLite3 REQUIRED) + +if (${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-write-strings") +endif () + +add_subdirectory(externals) +add_subdirectory(src) +add_subdirectory(tests) + +configure_file(extras/logger.cfg.dist src/logger.cfg COPYONLY) +configure_file(extras/swgchat.cfg.dist src/swgchat.cfg COPYONLY) diff --git a/README.md b/README.md new file mode 100644 index 0000000..b175cac --- /dev/null +++ b/README.md @@ -0,0 +1,37 @@ +# swgchat [![Build Status](https://travis-ci.com/apathyboy/swgchat.svg?token=FbjsTwsn9ctKssvZJqCa&branch=master)](https://travis-ci.com/apathyboy/swgchat) # + +An open implementation of the chat gateway that SOE based games used to provide various social communication features such as mail, custom chat rooms, friend management, etc. + +Like my work and want to support my free and open-source contributions? + +[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=8KCAU8HB9J7YU) + +## Implementation ## + +Uses the SOE libraries to implement chat features in a standalone utility. Ideally, the completed implementation would allow for multiple galaxies to connect and allow players to communicate across them. + +## External Dependencies ## + +c++14 compatible compiler +boost::iostreams (header only) +boost::optional (header only) +boost::program_options +sqlite3 +udplibrary - bundled in the Star Wars Galaxies official source + +## Building ## + +Copy the udplibrary directory from the Star Wars Galaxies offical source to the top level swgchat directory, then run the following: + + mkdir build; cd build + cmake .. + cmake --build . + +## Database Initialization ## + +Create the database with the following commands: + + sqlite3 chat.db + sqlite> .read /path/to/init_database.sql + +Then update the **database_path** config option with the full path to the database. diff --git a/cmake/FindSQLite3.cmake b/cmake/FindSQLite3.cmake new file mode 100644 index 0000000..fdd93f4 --- /dev/null +++ b/cmake/FindSQLite3.cmake @@ -0,0 +1,25 @@ + +find_path(SQLite3_INCLUDE_DIR sqlite3.h + HINTS + $ENV{SQLite3_ROOT} + PATH_SUFFIXES include + PATHS + ${SQLite3_ROOT} + ${SQLite3_INCLUDEDIR} +) + +find_library(SQLite3_LIBRARY + NAMES sqlite3 + PATH_SUFFIXES lib + HINTS + $ENV{SQLite3_ROOT} + ${SQLite3_ROOT} + ${SQLite3_LIBRARYDIR} +) + +# handle the QUIETLY and REQUIRED arguments and set OPENAL_FOUND to TRUE if +# all listed variables are TRUE +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(SQLite3 DEFAULT_MSG SQLite3_LIBRARY SQLite3_INCLUDE_DIR) + +mark_as_advanced(SQLite3_ROOT SQLite3_INCLUDE_DIR SQLite3_LIBRARY) diff --git a/cmake/GroupSourceByFilesystem.cmake b/cmake/GroupSourceByFilesystem.cmake new file mode 100644 index 0000000..5fb0d75 --- /dev/null +++ b/cmake/GroupSourceByFilesystem.cmake @@ -0,0 +1,16 @@ +function(GroupSourceByFilesystem SOURCES) + foreach(FILE ${SOURCES}) + get_filename_component(PARENT_DIR "${FILE}" DIRECTORY) + string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}" "" GROUP "${PARENT_DIR}") + string(REPLACE "/" "\\" GROUP "${GROUP}") + + # Group into "Source Files" and "Header Files" + if ("${FILE}" MATCHES ".*\\.cpp") + set(GROUP "Source Files\\${GROUP}") + elseif("${FILE}" MATCHES ".*\\.h") + set(GROUP "Header Files\\${GROUP}") + endif() + + source_group("${GROUP}" FILES "${FILE}") + endforeach() +endfunction(GroupSourceByFilesystem) \ No newline at end of file diff --git a/cmake/ModernCpp.cmake b/cmake/ModernCpp.cmake new file mode 100644 index 0000000..cd1da3b --- /dev/null +++ b/cmake/ModernCpp.cmake @@ -0,0 +1,9 @@ + +if (${CMAKE_CXX_COMPILER_ID} MATCHES "Clang") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -stdlib=libc++") + if (NOT APPLE) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -lc++abi") + endif () +elseif (${CMAKE_CXX_COMPILER_ID} STREQUAL "GNU") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") +endif () diff --git a/externals/CMakeLists.txt b/externals/CMakeLists.txt new file mode 100644 index 0000000..a4477d6 --- /dev/null +++ b/externals/CMakeLists.txt @@ -0,0 +1,4 @@ + +if (HAVE_UDPLIBRARY) + add_subdirectory(udplibrary) +endif() diff --git a/externals/catch/catch.hpp b/externals/catch/catch.hpp new file mode 100644 index 0000000..c8df33d --- /dev/null +++ b/externals/catch/catch.hpp @@ -0,0 +1,10593 @@ +/* + * Catch v1.5.6 + * Generated: 2016-06-09 19:20:41.460328 + * ---------------------------------------------------------- + * This file has been merged from multiple headers. Please don't edit it directly + * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED + +#define TWOBLUECUBES_CATCH_HPP_INCLUDED + +#ifdef __clang__ +#pragma clang system_header +#elif defined __GNUC__ +#pragma GCC system_header +#endif + +// #included from: internal/catch_suppress_warnings.h + +#ifdef __clang__ +#ifdef __ICC // icpc defines the __clang__ macro +#pragma warning(push) +#pragma warning(disable : 161 1682) +#else // __ICC +#pragma clang diagnostic ignored "-Wglobal-constructors" +#pragma clang diagnostic ignored "-Wvariadic-macros" +#pragma clang diagnostic ignored "-Wc99-extensions" +#pragma clang diagnostic ignored "-Wunused-variable" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#pragma clang diagnostic ignored "-Wc++98-compat" +#pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#pragma clang diagnostic ignored "-Wswitch-enum" +#pragma clang diagnostic ignored "-Wcovered-switch-default" +#endif +#elif defined __GNUC__ +#pragma GCC diagnostic ignored "-Wvariadic-macros" +#pragma GCC diagnostic ignored "-Wunused-variable" +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpadded" +#endif +#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) +#define CATCH_IMPL +#endif + +#ifdef CATCH_IMPL +#ifndef CLARA_CONFIG_MAIN +#define CLARA_CONFIG_MAIN_NOT_DEFINED +#define CLARA_CONFIG_MAIN +#endif +#endif + +// #included from: internal/catch_notimplemented_exception.h +#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED + +// #included from: catch_common.h +#define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED + +#define INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) name##line +#define INTERNAL_CATCH_UNIQUE_NAME_LINE(name, line) INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) +#ifdef CATCH_CONFIG_COUNTER +#define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __COUNTER__) +#else +#define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __LINE__) +#endif + +#define INTERNAL_CATCH_STRINGIFY2(expr) #expr +#define INTERNAL_CATCH_STRINGIFY(expr) INTERNAL_CATCH_STRINGIFY2(expr) + +#include +#include +#include + +// #included from: catch_compiler_capabilities.h +#define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED + +// Detect a number of compiler features - mostly C++11/14 conformance - by compiler +// The following features are defined: +// +// CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported? +// CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported? +// CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods +// CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported? +// CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported +// CATCH_CONFIG_CPP11_LONG_LONG : is long long supported? +// CATCH_CONFIG_CPP11_OVERRIDE : is override supported? +// CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) + +// CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? + +// CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? +// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? +// **************** +// Note to maintainers: if new toggles are added please document them +// in configuration.md, too +// **************** + +// In general each macro has a _NO_ form +// (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +// All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11 + +#ifdef __cplusplus + +#if __cplusplus >= 201103L +#define CATCH_CPP11_OR_GREATER +#endif + +#if __cplusplus >= 201402L +#define CATCH_CPP14_OR_GREATER +#endif + +#endif + +#ifdef __clang__ + +#if __has_feature(cxx_nullptr) +#define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +#if __has_feature(cxx_noexcept) +#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT +#endif + +#if defined(CATCH_CPP11_OR_GREATER) +#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma("clang diagnostic ignored \"-Wparentheses\"") +#endif + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// Borland +#ifdef __BORLANDC__ + +#endif // __BORLANDC__ + +//////////////////////////////////////////////////////////////////////////////// +// EDG +#ifdef __EDG_VERSION__ + +#endif // __EDG_VERSION__ + +//////////////////////////////////////////////////////////////////////////////// +// Digital Mars +#ifdef __DMC__ + +#endif // __DMC__ + +//////////////////////////////////////////////////////////////////////////////// +// GCC +#ifdef __GNUC__ + +#if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) +#define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) && defined(CATCH_CPP11_OR_GREATER) +#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma("GCC diagnostic ignored \"-Wparentheses\"") +#endif + +// - otherwise more recent versions define __cplusplus >= 201103L +// and will get picked up below + +#endif // __GNUC__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#ifdef _MSC_VER + +#if (_MSC_VER >= 1600) +#define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR +#define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR +#endif + +#if (_MSC_VER >= 1900) // (VC++ 13 (VS2015)) +#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT +#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#endif + +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// + +// Use variadic macros if the compiler supports them +#if (defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || (defined __WAVE__ && __WAVE_HAS_VARIADICS) || (defined __GNUC__ && __GNUC__ >= 3) || (!defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L) + +#define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS + +#endif + +// Use __COUNTER__ if the compiler supports it +#if (defined _MSC_VER && _MSC_VER >= 1300) || (defined __GNUC__ && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3) || (defined __clang__ && __clang_major__ >= 3) + +#define CATCH_INTERNAL_CONFIG_COUNTER + +#endif + +//////////////////////////////////////////////////////////////////////////////// +// C++ language feature support + +// catch all support for C++11 +#if defined(CATCH_CPP11_OR_GREATER) + +#if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) +#define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +#ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT +#define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT +#endif + +#ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#endif + +#ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM +#define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM +#endif + +#ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE +#define CATCH_INTERNAL_CONFIG_CPP11_TUPLE +#endif + +#ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS +#define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) +#define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) +#define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE +#endif +#if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) +#define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR +#endif + +#endif // __cplusplus >= 201103L + +// Now set the actual defines based on the above + anything the user has configured +#if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11) +#define CATCH_CONFIG_CPP11_NULLPTR +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11) +#define CATCH_CONFIG_CPP11_NOEXCEPT +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11) +#define CATCH_CONFIG_CPP11_GENERATED_METHODS +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11) +#define CATCH_CONFIG_CPP11_IS_ENUM +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11) +#define CATCH_CONFIG_CPP11_TUPLE +#endif +#if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS) +#define CATCH_CONFIG_VARIADIC_MACROS +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11) +#define CATCH_CONFIG_CPP11_LONG_LONG +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11) +#define CATCH_CONFIG_CPP11_OVERRIDE +#endif +#if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11) +#define CATCH_CONFIG_CPP11_UNIQUE_PTR +#endif +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) +#define CATCH_CONFIG_COUNTER +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) +#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +#endif + +// noexcept support: +#if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT) +#define CATCH_NOEXCEPT noexcept +#define CATCH_NOEXCEPT_IS(x) noexcept(x) +#else +#define CATCH_NOEXCEPT throw() +#define CATCH_NOEXCEPT_IS(x) +#endif + +// nullptr support +#ifdef CATCH_CONFIG_CPP11_NULLPTR +#define CATCH_NULL nullptr +#else +#define CATCH_NULL NULL +#endif + +// override support +#ifdef CATCH_CONFIG_CPP11_OVERRIDE +#define CATCH_OVERRIDE override +#else +#define CATCH_OVERRIDE +#endif + +// unique_ptr support +#ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR +#define CATCH_AUTO_PTR(T) std::unique_ptr +#else +#define CATCH_AUTO_PTR(T) std::auto_ptr +#endif + +namespace Catch { + +struct IConfig; + +struct CaseSensitive { + enum Choice { + Yes, + No + }; +}; + +class NonCopyable { +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + NonCopyable(NonCopyable const&) = delete; + NonCopyable(NonCopyable&&) = delete; + NonCopyable& operator=(NonCopyable const&) = delete; + NonCopyable& operator=(NonCopyable&&) = delete; +#else + NonCopyable(NonCopyable const& info); + NonCopyable& operator=(NonCopyable const&); +#endif + +protected: + NonCopyable() {} + virtual ~NonCopyable(); +}; + +class SafeBool { +public: + typedef void (SafeBool::*type)() const; + + static type makeSafe(bool value) { + return value ? &SafeBool::trueValue : 0; + } + +private: + void trueValue() const {} +}; + +template +inline void deleteAll(ContainerT& container) { + typename ContainerT::const_iterator it = container.begin(); + typename ContainerT::const_iterator itEnd = container.end(); + for (; it != itEnd; ++it) + delete *it; +} +template +inline void deleteAllValues(AssociativeContainerT& container) { + typename AssociativeContainerT::const_iterator it = container.begin(); + typename AssociativeContainerT::const_iterator itEnd = container.end(); + for (; it != itEnd; ++it) + delete it->second; +} + +bool startsWith(std::string const& s, std::string const& prefix); +bool endsWith(std::string const& s, std::string const& suffix); +bool contains(std::string const& s, std::string const& infix); +void toLowerInPlace(std::string& s); +std::string toLower(std::string const& s); +std::string trim(std::string const& str); +bool replaceInPlace(std::string& str, std::string const& replaceThis, std::string const& withThis); + +struct pluralise { + pluralise(std::size_t count, std::string const& label); + + friend std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser); + + std::size_t m_count; + std::string m_label; +}; + +struct SourceLineInfo { + + SourceLineInfo(); + SourceLineInfo(char const* _file, std::size_t _line); + SourceLineInfo(SourceLineInfo const& other); +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + SourceLineInfo(SourceLineInfo&&) = default; + SourceLineInfo& operator=(SourceLineInfo const&) = default; + SourceLineInfo& operator=(SourceLineInfo&&) = default; +#endif + bool empty() const; + bool operator==(SourceLineInfo const& other) const; + bool operator<(SourceLineInfo const& other) const; + + std::string file; + std::size_t line; +}; + +std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info); + +// This is just here to avoid compiler warnings with macro constants and boolean literals +inline bool isTrue(bool value) { return value; } +inline bool alwaysTrue() { return true; } +inline bool alwaysFalse() { return false; } + +void throwLogicError(std::string const& message, SourceLineInfo const& locationInfo); + +void seedRng(IConfig const& config); +unsigned int rngSeed(); + +// Use this in variadic streaming macros to allow +// >> +StreamEndStop +// as well as +// >> stuff +StreamEndStop +struct StreamEndStop { + std::string operator+() { + return std::string(); + } +}; +template +T const& operator+(T const& value, StreamEndStop) { + return value; +} +} + +#define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo(__FILE__, static_cast(__LINE__)) +#define CATCH_INTERNAL_ERROR(msg) ::Catch::throwLogicError(msg, CATCH_INTERNAL_LINEINFO); + +#include + +namespace Catch { + +class NotImplementedException : public std::exception { +public: + NotImplementedException(SourceLineInfo const& lineInfo); + NotImplementedException(NotImplementedException const&) {} + + virtual ~NotImplementedException() CATCH_NOEXCEPT {} + + virtual const char* what() const CATCH_NOEXCEPT; + +private: + std::string m_what; + SourceLineInfo m_lineInfo; +}; + +} // end namespace Catch + +/////////////////////////////////////////////////////////////////////////////// +#define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException(CATCH_INTERNAL_LINEINFO) + +// #included from: internal/catch_context.h +#define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED + +// #included from: catch_interfaces_generators.h +#define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED + +#include + +namespace Catch { + +struct IGeneratorInfo { + virtual ~IGeneratorInfo(); + virtual bool moveNext() = 0; + virtual std::size_t getCurrentIndex() const = 0; +}; + +struct IGeneratorsForTest { + virtual ~IGeneratorsForTest(); + + virtual IGeneratorInfo& getGeneratorInfo(std::string const& fileInfo, std::size_t size) = 0; + virtual bool moveNext() = 0; +}; + +IGeneratorsForTest* createGeneratorsForTest(); + +} // end namespace Catch + +// #included from: catch_ptr.hpp +#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +namespace Catch { + +// An intrusive reference counting smart pointer. +// T must implement addRef() and release() methods +// typically implementing the IShared interface +template +class Ptr { +public: + Ptr() + : m_p(CATCH_NULL) {} + Ptr(T* p) + : m_p(p) { + if (m_p) + m_p->addRef(); + } + Ptr(Ptr const& other) + : m_p(other.m_p) { + if (m_p) + m_p->addRef(); + } + ~Ptr() { + if (m_p) + m_p->release(); + } + void reset() { + if (m_p) + m_p->release(); + m_p = CATCH_NULL; + } + Ptr& operator=(T* p) { + Ptr temp(p); + swap(temp); + return *this; + } + Ptr& operator=(Ptr const& other) { + Ptr temp(other); + swap(temp); + return *this; + } + void swap(Ptr& other) { std::swap(m_p, other.m_p); } + T* get() const { return m_p; } + T& operator*() const { return *m_p; } + T* operator->() const { return m_p; } + bool operator!() const { return m_p == CATCH_NULL; } + operator SafeBool::type() const { return SafeBool::makeSafe(m_p != CATCH_NULL); } + +private: + T* m_p; +}; + +struct IShared : NonCopyable { + virtual ~IShared(); + virtual void addRef() const = 0; + virtual void release() const = 0; +}; + +template +struct SharedImpl : T { + + SharedImpl() + : m_rc(0) {} + + virtual void addRef() const { + ++m_rc; + } + virtual void release() const { + if (--m_rc == 0) + delete this; + } + + mutable unsigned int m_rc; +}; + +} // end namespace Catch + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#include +#include +#include + +namespace Catch { + +class TestCase; +class Stream; +struct IResultCapture; +struct IRunner; +struct IGeneratorsForTest; +struct IConfig; + +struct IContext { + virtual ~IContext(); + + virtual IResultCapture* getResultCapture() = 0; + virtual IRunner* getRunner() = 0; + virtual size_t getGeneratorIndex(std::string const& fileInfo, size_t totalSize) = 0; + virtual bool advanceGeneratorsForCurrentTest() = 0; + virtual Ptr getConfig() const = 0; +}; + +struct IMutableContext : IContext { + virtual ~IMutableContext(); + virtual void setResultCapture(IResultCapture* resultCapture) = 0; + virtual void setRunner(IRunner* runner) = 0; + virtual void setConfig(Ptr const& config) = 0; +}; + +IContext& getCurrentContext(); +IMutableContext& getCurrentMutableContext(); +void cleanUpContext(); +Stream createStream(std::string const& streamName); +} + +// #included from: internal/catch_test_registry.hpp +#define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED + +// #included from: catch_interfaces_testcase.h +#define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED + +#include + +namespace Catch { + +class TestSpec; + +struct ITestCase : IShared { + virtual void invoke() const = 0; + +protected: + virtual ~ITestCase(); +}; + +class TestCase; +struct IConfig; + +struct ITestCaseRegistry { + virtual ~ITestCaseRegistry(); + virtual std::vector const& getAllTests() const = 0; + virtual std::vector const& getAllTestsSorted(IConfig const& config) const = 0; +}; + +bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config); +std::vector filterTests(std::vector const& testCases, TestSpec const& testSpec, IConfig const& config); +std::vector const& getAllTestCasesSorted(IConfig const& config); +} + +namespace Catch { + +template +class MethodTestCase : public SharedImpl { + +public: + MethodTestCase(void (C::*method)()) + : m_method(method) {} + + virtual void invoke() const { + C obj; + (obj.*m_method)(); + } + +private: + virtual ~MethodTestCase() {} + + void (C::*m_method)(); +}; + +typedef void (*TestFunction)(); + +struct NameAndDesc { + NameAndDesc(const char* _name = "", const char* _description = "") + : name(_name) + , description(_description) {} + + const char* name; + const char* description; +}; + +void registerTestCase(ITestCase* testCase, + char const* className, + NameAndDesc const& nameAndDesc, + SourceLineInfo const& lineInfo); + +struct AutoReg { + + AutoReg(TestFunction function, + SourceLineInfo const& lineInfo, + NameAndDesc const& nameAndDesc); + + template + AutoReg(void (C::*method)(), + char const* className, + NameAndDesc const& nameAndDesc, + SourceLineInfo const& lineInfo) { + + registerTestCase(new MethodTestCase(method), + className, + nameAndDesc, + lineInfo); + } + + ~AutoReg(); + +private: + AutoReg(AutoReg const&); + void operator=(AutoReg const&); +}; + +void registerTestCaseFunction(TestFunction function, + SourceLineInfo const& lineInfo, + NameAndDesc const& nameAndDesc); + +} // end namespace Catch + +#ifdef CATCH_CONFIG_VARIADIC_MACROS +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TESTCASE2(TestName, ...) \ + static void TestName(); \ + namespace { \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(&TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc(__VA_ARGS__)); \ + } \ + static void TestName() +#define INTERNAL_CATCH_TESTCASE(...) \ + INTERNAL_CATCH_TESTCASE2(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), __VA_ARGS__) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...) \ + namespace { \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(&QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc(__VA_ARGS__), CATCH_INTERNAL_LINEINFO); \ + } + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...) \ + namespace { \ + struct TestName : ClassName { \ + void test(); \ + }; \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(&TestName::test, #ClassName, Catch::NameAndDesc(__VA_ARGS__), CATCH_INTERNAL_LINEINFO); \ + } \ + void TestName::test() +#define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...) \ + INTERNAL_CATCH_TEST_CASE_METHOD2(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), ClassName, __VA_ARGS__) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...) \ + Catch::AutoReg(Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc(__VA_ARGS__)); + +#else +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TESTCASE2(TestName, Name, Desc) \ + static void TestName(); \ + namespace { \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(&TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc(Name, Desc)); \ + } \ + static void TestName() +#define INTERNAL_CATCH_TESTCASE(Name, Desc) \ + INTERNAL_CATCH_TESTCASE2(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), Name, Desc) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, Name, Desc) \ + namespace { \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(&QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc(Name, Desc), CATCH_INTERNAL_LINEINFO); \ + } + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TEST_CASE_METHOD2(TestCaseName, ClassName, TestName, Desc) \ + namespace { \ + struct TestCaseName : ClassName { \ + void test(); \ + }; \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(&TestCaseName::test, #ClassName, Catch::NameAndDesc(TestName, Desc), CATCH_INTERNAL_LINEINFO); \ + } \ + void TestCaseName::test() +#define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, TestName, Desc) \ + INTERNAL_CATCH_TEST_CASE_METHOD2(INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_S_T____), ClassName, TestName, Desc) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_REGISTER_TESTCASE(Function, Name, Desc) \ + Catch::AutoReg(Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc(Name, Desc)); +#endif + +// #included from: internal/catch_capture.hpp +#define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED + +// #included from: catch_result_builder.h +#define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED + +// #included from: catch_result_type.h +#define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED + +namespace Catch { + +// ResultWas::OfType enum +struct ResultWas { + enum OfType { + Unknown = -1, + Ok = 0, + Info = 1, + Warning = 2, + + FailureBit = 0x10, + + ExpressionFailed = FailureBit | 1, + ExplicitFailure = FailureBit | 2, + + Exception = 0x100 | FailureBit, + + ThrewException = Exception | 1, + DidntThrowException = Exception | 2, + + FatalErrorCondition = 0x200 | FailureBit + + }; +}; + +inline bool isOk(ResultWas::OfType resultType) { + return (resultType & ResultWas::FailureBit) == 0; +} +inline bool isJustInfo(int flags) { + return flags == ResultWas::Info; +} + +// ResultDisposition::Flags enum +struct ResultDisposition { + enum Flags { + Normal = 0x01, + + ContinueOnFailure = 0x02, // Failures fail test, but execution continues + FalseTest = 0x04, // Prefix expression with ! + SuppressFail = 0x08 // Failures are reported but do not fail the test + }; +}; + +inline ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs) { + return static_cast(static_cast(lhs) | static_cast(rhs)); +} + +inline bool shouldContinueOnFailure(int flags) { return (flags & ResultDisposition::ContinueOnFailure) != 0; } +inline bool isFalseTest(int flags) { return (flags & ResultDisposition::FalseTest) != 0; } +inline bool shouldSuppressFailure(int flags) { return (flags & ResultDisposition::SuppressFail) != 0; } + +} // end namespace Catch + +// #included from: catch_assertionresult.h +#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED + +#include + +namespace Catch { + +struct AssertionInfo { + AssertionInfo() {} + AssertionInfo(std::string const& _macroName, + SourceLineInfo const& _lineInfo, + std::string const& _capturedExpression, + ResultDisposition::Flags _resultDisposition); + + std::string macroName; + SourceLineInfo lineInfo; + std::string capturedExpression; + ResultDisposition::Flags resultDisposition; +}; + +struct AssertionResultData { + AssertionResultData() + : resultType(ResultWas::Unknown) {} + + std::string reconstructedExpression; + std::string message; + ResultWas::OfType resultType; +}; + +class AssertionResult { +public: + AssertionResult(); + AssertionResult(AssertionInfo const& info, AssertionResultData const& data); + ~AssertionResult(); +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + AssertionResult(AssertionResult const&) = default; + AssertionResult(AssertionResult&&) = default; + AssertionResult& operator=(AssertionResult const&) = default; + AssertionResult& operator=(AssertionResult&&) = default; +#endif + + bool isOk() const; + bool succeeded() const; + ResultWas::OfType getResultType() const; + bool hasExpression() const; + bool hasMessage() const; + std::string getExpression() const; + std::string getExpressionInMacro() const; + bool hasExpandedExpression() const; + std::string getExpandedExpression() const; + std::string getMessage() const; + SourceLineInfo getSourceInfo() const; + std::string getTestMacroName() const; + +protected: + AssertionInfo m_info; + AssertionResultData m_resultData; +}; + +} // end namespace Catch + +// #included from: catch_matchers.hpp +#define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED + +namespace Catch { +namespace Matchers { + namespace Impl { + + namespace Generic { + template + class AllOf; + template + class AnyOf; + template + class Not; + } + + template + struct Matcher : SharedImpl { + typedef ExpressionT ExpressionType; + + virtual ~Matcher() {} + virtual Ptr clone() const = 0; + virtual bool match(ExpressionT const& expr) const = 0; + virtual std::string toString() const = 0; + + Generic::AllOf operator&&(Matcher const& other) const; + Generic::AnyOf operator||(Matcher const& other) const; + Generic::Not operator!() const; + }; + + template + struct MatcherImpl : Matcher { + + virtual Ptr> clone() const { + return Ptr>(new DerivedT(static_cast(*this))); + } + }; + + namespace Generic { + template + class Not : public MatcherImpl, ExpressionT> { + public: + explicit Not(Matcher const& matcher) + : m_matcher(matcher.clone()) {} + Not(Not const& other) + : m_matcher(other.m_matcher) {} + + virtual bool match(ExpressionT const& expr) const CATCH_OVERRIDE { + return !m_matcher->match(expr); + } + + virtual std::string toString() const CATCH_OVERRIDE { + return "not " + m_matcher->toString(); + } + + private: + Ptr> m_matcher; + }; + + template + class AllOf : public MatcherImpl, ExpressionT> { + public: + AllOf() {} + AllOf(AllOf const& other) + : m_matchers(other.m_matchers) {} + + AllOf& add(Matcher const& matcher) { + m_matchers.push_back(matcher.clone()); + return *this; + } + virtual bool match(ExpressionT const& expr) const { + for (std::size_t i = 0; i < m_matchers.size(); ++i) + if (!m_matchers[i]->match(expr)) + return false; + return true; + } + virtual std::string toString() const { + std::ostringstream oss; + oss << "( "; + for (std::size_t i = 0; i < m_matchers.size(); ++i) { + if (i != 0) + oss << " and "; + oss << m_matchers[i]->toString(); + } + oss << " )"; + return oss.str(); + } + + AllOf operator&&(Matcher const& other) const { + AllOf allOfExpr(*this); + allOfExpr.add(other); + return allOfExpr; + } + + private: + std::vector>> m_matchers; + }; + + template + class AnyOf : public MatcherImpl, ExpressionT> { + public: + AnyOf() {} + AnyOf(AnyOf const& other) + : m_matchers(other.m_matchers) {} + + AnyOf& add(Matcher const& matcher) { + m_matchers.push_back(matcher.clone()); + return *this; + } + virtual bool match(ExpressionT const& expr) const { + for (std::size_t i = 0; i < m_matchers.size(); ++i) + if (m_matchers[i]->match(expr)) + return true; + return false; + } + virtual std::string toString() const { + std::ostringstream oss; + oss << "( "; + for (std::size_t i = 0; i < m_matchers.size(); ++i) { + if (i != 0) + oss << " or "; + oss << m_matchers[i]->toString(); + } + oss << " )"; + return oss.str(); + } + + AnyOf operator||(Matcher const& other) const { + AnyOf anyOfExpr(*this); + anyOfExpr.add(other); + return anyOfExpr; + } + + private: + std::vector>> m_matchers; + }; + + } // namespace Generic + + template + Generic::AllOf Matcher::operator&&(Matcher const& other) const { + Generic::AllOf allOfExpr; + allOfExpr.add(*this); + allOfExpr.add(other); + return allOfExpr; + } + + template + Generic::AnyOf Matcher::operator||(Matcher const& other) const { + Generic::AnyOf anyOfExpr; + anyOfExpr.add(*this); + anyOfExpr.add(other); + return anyOfExpr; + } + + template + Generic::Not Matcher::operator!() const { + return Generic::Not(*this); + } + + namespace StdString { + + inline std::string makeString(std::string const& str) { return str; } + inline std::string makeString(const char* str) { return str ? std::string(str) : std::string(); } + + struct CasedString { + CasedString(std::string const& str, CaseSensitive::Choice caseSensitivity) + : m_caseSensitivity(caseSensitivity) + , m_str(adjustString(str)) {} + std::string adjustString(std::string const& str) const { + return m_caseSensitivity == CaseSensitive::No + ? toLower(str) + : str; + } + std::string toStringSuffix() const { + return m_caseSensitivity == CaseSensitive::No + ? " (case insensitive)" + : ""; + } + CaseSensitive::Choice m_caseSensitivity; + std::string m_str; + }; + + struct Equals : MatcherImpl { + Equals(std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes) + : m_data(str, caseSensitivity) {} + Equals(Equals const& other) + : m_data(other.m_data) {} + + virtual ~Equals(); + + virtual bool match(std::string const& expr) const { + return m_data.m_str == m_data.adjustString(expr); + ; + } + virtual std::string toString() const { + return "equals: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); + } + + CasedString m_data; + }; + + struct Contains : MatcherImpl { + Contains(std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes) + : m_data(substr, caseSensitivity) {} + Contains(Contains const& other) + : m_data(other.m_data) {} + + virtual ~Contains(); + + virtual bool match(std::string const& expr) const { + return m_data.adjustString(expr).find(m_data.m_str) != std::string::npos; + } + virtual std::string toString() const { + return "contains: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); + } + + CasedString m_data; + }; + + struct StartsWith : MatcherImpl { + StartsWith(std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes) + : m_data(substr, caseSensitivity) {} + + StartsWith(StartsWith const& other) + : m_data(other.m_data) {} + + virtual ~StartsWith(); + + virtual bool match(std::string const& expr) const { + return startsWith(m_data.adjustString(expr), m_data.m_str); + } + virtual std::string toString() const { + return "starts with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); + } + + CasedString m_data; + }; + + struct EndsWith : MatcherImpl { + EndsWith(std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes) + : m_data(substr, caseSensitivity) {} + EndsWith(EndsWith const& other) + : m_data(other.m_data) {} + + virtual ~EndsWith(); + + virtual bool match(std::string const& expr) const { + return endsWith(m_data.adjustString(expr), m_data.m_str); + } + virtual std::string toString() const { + return "ends with: \"" + m_data.m_str + "\"" + m_data.toStringSuffix(); + } + + CasedString m_data; + }; + } // namespace StdString + } // namespace Impl + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + template + inline Impl::Generic::Not Not(Impl::Matcher const& m) { + return Impl::Generic::Not(m); + } + + template + inline Impl::Generic::AllOf AllOf(Impl::Matcher const& m1, + Impl::Matcher const& m2) { + return Impl::Generic::AllOf().add(m1).add(m2); + } + template + inline Impl::Generic::AllOf AllOf(Impl::Matcher const& m1, + Impl::Matcher const& m2, + Impl::Matcher const& m3) { + return Impl::Generic::AllOf().add(m1).add(m2).add(m3); + } + template + inline Impl::Generic::AnyOf AnyOf(Impl::Matcher const& m1, + Impl::Matcher const& m2) { + return Impl::Generic::AnyOf().add(m1).add(m2); + } + template + inline Impl::Generic::AnyOf AnyOf(Impl::Matcher const& m1, + Impl::Matcher const& m2, + Impl::Matcher const& m3) { + return Impl::Generic::AnyOf().add(m1).add(m2).add(m3); + } + + inline Impl::StdString::Equals Equals(std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes) { + return Impl::StdString::Equals(str, caseSensitivity); + } + inline Impl::StdString::Equals Equals(const char* str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes) { + return Impl::StdString::Equals(Impl::StdString::makeString(str), caseSensitivity); + } + inline Impl::StdString::Contains Contains(std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes) { + return Impl::StdString::Contains(substr, caseSensitivity); + } + inline Impl::StdString::Contains Contains(const char* substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes) { + return Impl::StdString::Contains(Impl::StdString::makeString(substr), caseSensitivity); + } + inline Impl::StdString::StartsWith StartsWith(std::string const& substr) { + return Impl::StdString::StartsWith(substr); + } + inline Impl::StdString::StartsWith StartsWith(const char* substr) { + return Impl::StdString::StartsWith(Impl::StdString::makeString(substr)); + } + inline Impl::StdString::EndsWith EndsWith(std::string const& substr) { + return Impl::StdString::EndsWith(substr); + } + inline Impl::StdString::EndsWith EndsWith(const char* substr) { + return Impl::StdString::EndsWith(Impl::StdString::makeString(substr)); + } + +} // namespace Matchers + +using namespace Matchers; + +} // namespace Catch + +namespace Catch { + +struct TestFailureException {}; + +template +class ExpressionLhs; + +struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison; + +struct CopyableStream { + CopyableStream() {} + CopyableStream(CopyableStream const& other) { + oss << other.oss.str(); + } + CopyableStream& operator=(CopyableStream const& other) { + oss.str(""); + oss << other.oss.str(); + return *this; + } + std::ostringstream oss; +}; + +class ResultBuilder { +public: + ResultBuilder(char const* macroName, + SourceLineInfo const& lineInfo, + char const* capturedExpression, + ResultDisposition::Flags resultDisposition, + char const* secondArg = ""); + + template + ExpressionLhs operator<=(T const& operand); + ExpressionLhs operator<=(bool value); + + template + ResultBuilder& operator<<(T const& value) { + m_stream.oss << value; + return *this; + } + + template + STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator&&(RhsT const&); + template + STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator||(RhsT const&); + + ResultBuilder& setResultType(ResultWas::OfType result); + ResultBuilder& setResultType(bool result); + ResultBuilder& setLhs(std::string const& lhs); + ResultBuilder& setRhs(std::string const& rhs); + ResultBuilder& setOp(std::string const& op); + + void endExpression(); + + std::string reconstructExpression() const; + AssertionResult build() const; + + void useActiveException(ResultDisposition::Flags resultDisposition = ResultDisposition::Normal); + void captureResult(ResultWas::OfType resultType); + void captureExpression(); + void captureExpectedException(std::string const& expectedMessage); + void captureExpectedException(Matchers::Impl::Matcher const& matcher); + void handleResult(AssertionResult const& result); + void react(); + bool shouldDebugBreak() const; + bool allowThrows() const; + +private: + AssertionInfo m_assertionInfo; + AssertionResultData m_data; + struct ExprComponents { + ExprComponents() + : testFalse(false) {} + bool testFalse; + std::string lhs, rhs, op; + } m_exprComponents; + CopyableStream m_stream; + + bool m_shouldDebugBreak; + bool m_shouldThrow; +}; + +} // namespace Catch + +// Include after due to circular dependency: +// #included from: catch_expression_lhs.hpp +#define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED + +// #included from: catch_evaluate.hpp +#define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4389) // '==' : signed/unsigned mismatch +#endif + +#include + +namespace Catch { +namespace Internal { + + enum Operator { + IsEqualTo, + IsNotEqualTo, + IsLessThan, + IsGreaterThan, + IsLessThanOrEqualTo, + IsGreaterThanOrEqualTo + }; + + template + struct OperatorTraits { + static const char* getName() { return "*error*"; } + }; + template <> + struct OperatorTraits { + static const char* getName() { return "=="; } + }; + template <> + struct OperatorTraits { + static const char* getName() { return "!="; } + }; + template <> + struct OperatorTraits { + static const char* getName() { return "<"; } + }; + template <> + struct OperatorTraits { + static const char* getName() { return ">"; } + }; + template <> + struct OperatorTraits { + static const char* getName() { return "<="; } + }; + template <> + struct OperatorTraits { + static const char* getName() { return ">="; } + }; + + template + inline T& opCast(T const& t) { return const_cast(t); } + +// nullptr_t support based on pull request #154 from Konstantin Baumann +#ifdef CATCH_CONFIG_CPP11_NULLPTR + inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } +#endif // CATCH_CONFIG_CPP11_NULLPTR + + // So the compare overloads can be operator agnostic we convey the operator as a template + // enum, which is used to specialise an Evaluator for doing the comparison. + template + class Evaluator {}; + + template + struct Evaluator { + static bool evaluate(T1 const& lhs, T2 const& rhs) { + return bool(opCast(lhs) == opCast(rhs)); + } + }; + template + struct Evaluator { + static bool evaluate(T1 const& lhs, T2 const& rhs) { + return bool(opCast(lhs) != opCast(rhs)); + } + }; + template + struct Evaluator { + static bool evaluate(T1 const& lhs, T2 const& rhs) { + return bool(opCast(lhs) < opCast(rhs)); + } + }; + template + struct Evaluator { + static bool evaluate(T1 const& lhs, T2 const& rhs) { + return bool(opCast(lhs) > opCast(rhs)); + } + }; + template + struct Evaluator { + static bool evaluate(T1 const& lhs, T2 const& rhs) { + return bool(opCast(lhs) >= opCast(rhs)); + } + }; + template + struct Evaluator { + static bool evaluate(T1 const& lhs, T2 const& rhs) { + return bool(opCast(lhs) <= opCast(rhs)); + } + }; + + template + bool applyEvaluator(T1 const& lhs, T2 const& rhs) { + return Evaluator::evaluate(lhs, rhs); + } + + // This level of indirection allows us to specialise for integer types + // to avoid signed/ unsigned warnings + + // "base" overload + template + bool compare(T1 const& lhs, T2 const& rhs) { + return Evaluator::evaluate(lhs, rhs); + } + + // unsigned X to int + template + bool compare(unsigned int lhs, int rhs) { + return applyEvaluator(lhs, static_cast(rhs)); + } + template + bool compare(unsigned long lhs, int rhs) { + return applyEvaluator(lhs, static_cast(rhs)); + } + template + bool compare(unsigned char lhs, int rhs) { + return applyEvaluator(lhs, static_cast(rhs)); + } + + // unsigned X to long + template + bool compare(unsigned int lhs, long rhs) { + return applyEvaluator(lhs, static_cast(rhs)); + } + template + bool compare(unsigned long lhs, long rhs) { + return applyEvaluator(lhs, static_cast(rhs)); + } + template + bool compare(unsigned char lhs, long rhs) { + return applyEvaluator(lhs, static_cast(rhs)); + } + + // int to unsigned X + template + bool compare(int lhs, unsigned int rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(int lhs, unsigned long rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(int lhs, unsigned char rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + + // long to unsigned X + template + bool compare(long lhs, unsigned int rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(long lhs, unsigned long rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(long lhs, unsigned char rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + + // pointer to long (when comparing against NULL) + template + bool compare(long lhs, T* rhs) { + return Evaluator::evaluate(reinterpret_cast(lhs), rhs); + } + template + bool compare(T* lhs, long rhs) { + return Evaluator::evaluate(lhs, reinterpret_cast(rhs)); + } + + // pointer to int (when comparing against NULL) + template + bool compare(int lhs, T* rhs) { + return Evaluator::evaluate(reinterpret_cast(lhs), rhs); + } + template + bool compare(T* lhs, int rhs) { + return Evaluator::evaluate(lhs, reinterpret_cast(rhs)); + } + +#ifdef CATCH_CONFIG_CPP11_LONG_LONG + // long long to unsigned X + template + bool compare(long long lhs, unsigned int rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(long long lhs, unsigned long rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(long long lhs, unsigned long long rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(long long lhs, unsigned char rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + + // unsigned long long to X + template + bool compare(unsigned long long lhs, int rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(unsigned long long lhs, long rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(unsigned long long lhs, long long rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + template + bool compare(unsigned long long lhs, char rhs) { + return applyEvaluator(static_cast(lhs), rhs); + } + + // pointer to long long (when comparing against NULL) + template + bool compare(long long lhs, T* rhs) { + return Evaluator::evaluate(reinterpret_cast(lhs), rhs); + } + template + bool compare(T* lhs, long long rhs) { + return Evaluator::evaluate(lhs, reinterpret_cast(rhs)); + } +#endif // CATCH_CONFIG_CPP11_LONG_LONG + +#ifdef CATCH_CONFIG_CPP11_NULLPTR + // pointer to nullptr_t (when comparing against nullptr) + template + bool compare(std::nullptr_t, T* rhs) { + return Evaluator::evaluate(nullptr, rhs); + } + template + bool compare(T* lhs, std::nullptr_t) { + return Evaluator::evaluate(lhs, nullptr); + } +#endif // CATCH_CONFIG_CPP11_NULLPTR + +} // end of namespace Internal +} // end of namespace Catch + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +// #included from: catch_tostring.h +#define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED + +#include +#include +#include +#include +#include + +#ifdef __OBJC__ +// #included from: catch_objc_arc.hpp +#define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED + +#import + +#ifdef __has_feature +#define CATCH_ARC_ENABLED __has_feature(objc_arc) +#else +#define CATCH_ARC_ENABLED 0 +#endif + +void arcSafeRelease(NSObject* obj); +id performOptionalSelector(id obj, SEL sel); + +#if !CATCH_ARC_ENABLED +inline void arcSafeRelease(NSObject* obj) { + [obj release]; +} +inline id performOptionalSelector(id obj, SEL sel) { + if ([obj respondsToSelector:sel]) + return [obj performSelector:sel]; + return nil; +} +#define CATCH_UNSAFE_UNRETAINED +#define CATCH_ARC_STRONG +#else +inline void arcSafeRelease(NSObject*) {} +inline id performOptionalSelector(id obj, SEL sel) { +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" +#endif + if ([obj respondsToSelector:sel]) + return [obj performSelector:sel]; +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + return nil; +} +#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained +#define CATCH_ARC_STRONG __strong +#endif + +#endif + +#ifdef CATCH_CONFIG_CPP11_TUPLE +#include +#endif + +#ifdef CATCH_CONFIG_CPP11_IS_ENUM +#include +#endif + +namespace Catch { + +// Why we're here. +template +std::string toString(T const& value); + +// Built in overloads + +std::string toString(std::string const& value); +std::string toString(std::wstring const& value); +std::string toString(const char* const value); +std::string toString(char* const value); +std::string toString(const wchar_t* const value); +std::string toString(wchar_t* const value); +std::string toString(int value); +std::string toString(unsigned long value); +std::string toString(unsigned int value); +std::string toString(const double value); +std::string toString(const float value); +std::string toString(bool value); +std::string toString(char value); +std::string toString(signed char value); +std::string toString(unsigned char value); + +#ifdef CATCH_CONFIG_CPP11_LONG_LONG +std::string toString(long long value); +std::string toString(unsigned long long value); +#endif + +#ifdef CATCH_CONFIG_CPP11_NULLPTR +std::string toString(std::nullptr_t); +#endif + +#ifdef __OBJC__ +std::string toString(NSString const* const& nsstring); +std::string toString(NSString* CATCH_ARC_STRONG const& nsstring); +std::string toString(NSObject* const& nsObject); +#endif + +namespace Detail { + + extern const std::string unprintableString; + + struct BorgType { + template + BorgType(T const&); + }; + + struct TrueType { + char sizer[1]; + }; + struct FalseType { + char sizer[2]; + }; + + TrueType& testStreamable(std::ostream&); + FalseType testStreamable(FalseType); + + FalseType operator<<(std::ostream const&, BorgType const&); + + template + struct IsStreamInsertable { + static std::ostream& s; + static T const& t; + enum { value = sizeof(testStreamable(s << t)) == sizeof(TrueType) }; + }; + +#if defined(CATCH_CONFIG_CPP11_IS_ENUM) + template ::value> + struct EnumStringMaker { + static std::string convert(T const&) { return unprintableString; } + }; + + template + struct EnumStringMaker { + static std::string convert(T const& v) { + return ::Catch::toString( + static_cast::type>(v)); + } + }; +#endif + template + struct StringMakerBase { +#if defined(CATCH_CONFIG_CPP11_IS_ENUM) + template + static std::string convert(T const& v) { + return EnumStringMaker::convert(v); + } +#else + template + static std::string convert(T const&) { return unprintableString; } +#endif + }; + + template <> + struct StringMakerBase { + template + static std::string convert(T const& _value) { + std::ostringstream oss; + oss << _value; + return oss.str(); + } + }; + + std::string rawMemoryToString(const void* object, std::size_t size); + + template + inline std::string rawMemoryToString(const T& object) { + return rawMemoryToString(&object, sizeof(object)); + } + +} // end namespace Detail + +template +struct StringMaker : Detail::StringMakerBase::value> {}; + +template +struct StringMaker { + template + static std::string convert(U* p) { + if (!p) + return "NULL"; + else + return Detail::rawMemoryToString(p); + } +}; + +template +struct StringMaker { + static std::string convert(R C::*p) { + if (!p) + return "NULL"; + else + return Detail::rawMemoryToString(p); + } +}; + +namespace Detail { + template + std::string rangeToString(InputIterator first, InputIterator last); +} + +//template +//struct StringMaker > { +// static std::string convert( std::vector const& v ) { +// return Detail::rangeToString( v.begin(), v.end() ); +// } +//}; + +template +std::string toString(std::vector const& v) { + return Detail::rangeToString(v.begin(), v.end()); +} + +#ifdef CATCH_CONFIG_CPP11_TUPLE + +// toString for tuples +namespace TupleDetail { + template < + typename Tuple, + std::size_t N = 0, + bool = (N < std::tuple_size::value)> + struct ElementPrinter { + static void print(const Tuple& tuple, std::ostream& os) { + os << (N ? ", " : " ") + << Catch::toString(std::get(tuple)); + ElementPrinter::print(tuple, os); + } + }; + + template < + typename Tuple, + std::size_t N> + struct ElementPrinter { + static void print(const Tuple&, std::ostream&) {} + }; +} + +template +struct StringMaker> { + + static std::string convert(const std::tuple& tuple) { + std::ostringstream os; + os << '{'; + TupleDetail::ElementPrinter>::print(tuple, os); + os << " }"; + return os.str(); + } +}; +#endif // CATCH_CONFIG_CPP11_TUPLE + +namespace Detail { + template + std::string makeString(T const& value) { + return StringMaker::convert(value); + } +} // end namespace Detail + +/// \brief converts any type to a string +/// +/// The default template forwards on to ostringstream - except when an +/// ostringstream overload does not exist - in which case it attempts to detect +/// that and writes {?}. +/// Overload (not specialise) this template for custom typs that you don't want +/// to provide an ostream overload for. +template +std::string toString(T const& value) { + return StringMaker::convert(value); +} + +namespace Detail { + template + std::string rangeToString(InputIterator first, InputIterator last) { + std::ostringstream oss; + oss << "{ "; + if (first != last) { + oss << Catch::toString(*first); + for (++first; first != last; ++first) + oss << ", " << Catch::toString(*first); + } + oss << " }"; + return oss.str(); + } +} + +} // end namespace Catch + +namespace Catch { + +// Wraps the LHS of an expression and captures the operator and RHS (if any) - +// wrapping them all in a ResultBuilder object +template +class ExpressionLhs { + ExpressionLhs& operator=(ExpressionLhs const&); +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + ExpressionLhs& operator=(ExpressionLhs&&) = delete; +#endif + +public: + ExpressionLhs(ResultBuilder& rb, T lhs) + : m_rb(rb) + , m_lhs(lhs) {} +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + ExpressionLhs(ExpressionLhs const&) = default; + ExpressionLhs(ExpressionLhs&&) = default; +#endif + + template + ResultBuilder& operator==(RhsT const& rhs) { + return captureExpression(rhs); + } + + template + ResultBuilder& operator!=(RhsT const& rhs) { + return captureExpression(rhs); + } + + template + ResultBuilder& operator<(RhsT const& rhs) { + return captureExpression(rhs); + } + + template + ResultBuilder& operator>(RhsT const& rhs) { + return captureExpression(rhs); + } + + template + ResultBuilder& operator<=(RhsT const& rhs) { + return captureExpression(rhs); + } + + template + ResultBuilder& operator>=(RhsT const& rhs) { + return captureExpression(rhs); + } + + ResultBuilder& operator==(bool rhs) { + return captureExpression(rhs); + } + + ResultBuilder& operator!=(bool rhs) { + return captureExpression(rhs); + } + + void endExpression() { + bool value = m_lhs ? true : false; + m_rb + .setLhs(Catch::toString(value)) + .setResultType(value) + .endExpression(); + } + + // Only simple binary expressions are allowed on the LHS. + // If more complex compositions are required then place the sub expression in parentheses + template + STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator+(RhsT const&); + template + STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator-(RhsT const&); + template + STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator/(RhsT const&); + template + STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator*(RhsT const&); + template + STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator&&(RhsT const&); + template + STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator||(RhsT const&); + +private: + template + ResultBuilder& captureExpression(RhsT const& rhs) { + return m_rb + .setResultType(Internal::compare(m_lhs, rhs)) + .setLhs(Catch::toString(m_lhs)) + .setRhs(Catch::toString(rhs)) + .setOp(Internal::OperatorTraits::getName()); + } + +private: + ResultBuilder& m_rb; + T m_lhs; +}; + +} // end namespace Catch + +namespace Catch { + +template +inline ExpressionLhs ResultBuilder::operator<=(T const& operand) { + return ExpressionLhs(*this, operand); +} + +inline ExpressionLhs ResultBuilder::operator<=(bool value) { + return ExpressionLhs(*this, value); +} + +} // namespace Catch + +// #included from: catch_message.h +#define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED + +#include + +namespace Catch { + +struct MessageInfo { + MessageInfo(std::string const& _macroName, + SourceLineInfo const& _lineInfo, + ResultWas::OfType _type); + + std::string macroName; + SourceLineInfo lineInfo; + ResultWas::OfType type; + std::string message; + unsigned int sequence; + + bool operator==(MessageInfo const& other) const { + return sequence == other.sequence; + } + bool operator<(MessageInfo const& other) const { + return sequence < other.sequence; + } + +private: + static unsigned int globalCount; +}; + +struct MessageBuilder { + MessageBuilder(std::string const& macroName, + SourceLineInfo const& lineInfo, + ResultWas::OfType type) + : m_info(macroName, lineInfo, type) {} + + template + MessageBuilder& operator<<(T const& value) { + m_stream << value; + return *this; + } + + MessageInfo m_info; + std::ostringstream m_stream; +}; + +class ScopedMessage { +public: + ScopedMessage(MessageBuilder const& builder); + ScopedMessage(ScopedMessage const& other); + ~ScopedMessage(); + + MessageInfo m_info; +}; + +} // end namespace Catch + +// #included from: catch_interfaces_capture.h +#define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED + +#include + +namespace Catch { + +class TestCase; +class AssertionResult; +struct AssertionInfo; +struct SectionInfo; +struct SectionEndInfo; +struct MessageInfo; +class ScopedMessageBuilder; +struct Counts; + +struct IResultCapture { + + virtual ~IResultCapture(); + + virtual void assertionEnded(AssertionResult const& result) = 0; + virtual bool sectionStarted(SectionInfo const& sectionInfo, + Counts& assertions) + = 0; + virtual void sectionEnded(SectionEndInfo const& endInfo) = 0; + virtual void sectionEndedEarly(SectionEndInfo const& endInfo) = 0; + virtual void pushScopedMessage(MessageInfo const& message) = 0; + virtual void popScopedMessage(MessageInfo const& message) = 0; + + virtual std::string getCurrentTestName() const = 0; + virtual const AssertionResult* getLastResult() const = 0; + + virtual void handleFatalErrorCondition(std::string const& message) = 0; +}; + +IResultCapture& getResultCapture(); +} + +// #included from: catch_debugger.h +#define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED + +// #included from: catch_platform.h +#define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED + +#if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#define CATCH_PLATFORM_MAC +#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#define CATCH_PLATFORM_IPHONE +#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) +#define CATCH_PLATFORM_WINDOWS +#endif + +#include + +namespace Catch { + +bool isDebuggerActive(); +void writeToDebugConsole(std::string const& text); +} + +#ifdef CATCH_PLATFORM_MAC + +// The following code snippet based on: +// http://cocoawithlove.com/2008/03/break-into-debugger.html +#ifdef DEBUG +#if defined(__ppc64__) || defined(__ppc__) +#define CATCH_BREAK_INTO_DEBUGGER() \ + if (Catch::isDebuggerActive()) { \ + __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \ + : \ + : \ + : "memory", "r0", "r3", "r4"); \ + } +#else +#define CATCH_BREAK_INTO_DEBUGGER() \ + if (Catch::isDebuggerActive()) { \ + __asm__("int $3\n" \ + : \ + :); \ + } +#endif +#endif + +#elif defined(_MSC_VER) +#define CATCH_BREAK_INTO_DEBUGGER() \ + if (Catch::isDebuggerActive()) { \ + __debugbreak(); \ + } +#elif defined(__MINGW32__) +extern "C" __declspec(dllimport) void __stdcall DebugBreak(); +#define CATCH_BREAK_INTO_DEBUGGER() \ + if (Catch::isDebuggerActive()) { \ + DebugBreak(); \ + } +#endif + +#ifndef CATCH_BREAK_INTO_DEBUGGER +#define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); +#endif + +// #included from: catch_interfaces_runner.h +#define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED + +namespace Catch { +class TestCase; + +struct IRunner { + virtual ~IRunner(); + virtual bool aborting() const = 0; +}; +} + +/////////////////////////////////////////////////////////////////////////////// +// In the event of a failure works out if the debugger needs to be invoked +// and/or an exception thrown and takes appropriate action. +// This needs to be done as a macro so the debugger will stop in the user +// source code rather than in Catch library code +#define INTERNAL_CATCH_REACT(resultBuilder) \ + if (resultBuilder.shouldDebugBreak()) \ + CATCH_BREAK_INTO_DEBUGGER(); \ + resultBuilder.react(); + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TEST(expr, resultDisposition, macroName) \ + do { \ + Catch::ResultBuilder __catchResult(macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition); \ + try { \ + CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS(__catchResult <= expr) \ + .endExpression(); \ + } catch (...) { \ + __catchResult.useActiveException(Catch::ResultDisposition::Normal); \ + } \ + INTERNAL_CATCH_REACT(__catchResult) \ + } while (Catch::isTrue(false && !!(expr))) // expr here is never evaluated at runtime but it forces the compiler to give it a look + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_IF(expr, resultDisposition, macroName) \ + INTERNAL_CATCH_TEST(expr, resultDisposition, macroName); \ + if (Catch::getResultCapture().getLastResult()->succeeded()) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_ELSE(expr, resultDisposition, macroName) \ + INTERNAL_CATCH_TEST(expr, resultDisposition, macroName); \ + if (!Catch::getResultCapture().getLastResult()->succeeded()) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_NO_THROW(expr, resultDisposition, macroName) \ + do { \ + Catch::ResultBuilder __catchResult(macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition); \ + try { \ + expr; \ + __catchResult.captureResult(Catch::ResultWas::Ok); \ + } catch (...) { \ + __catchResult.useActiveException(resultDisposition); \ + } \ + INTERNAL_CATCH_REACT(__catchResult) \ + } while (Catch::alwaysFalse()) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_THROWS(expr, resultDisposition, matcher, macroName) \ + do { \ + Catch::ResultBuilder __catchResult(macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher); \ + if (__catchResult.allowThrows()) \ + try { \ + expr; \ + __catchResult.captureResult(Catch::ResultWas::DidntThrowException); \ + } catch (...) { \ + __catchResult.captureExpectedException(matcher); \ + } \ + else \ + __catchResult.captureResult(Catch::ResultWas::Ok); \ + INTERNAL_CATCH_REACT(__catchResult) \ + } while (Catch::alwaysFalse()) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_THROWS_AS(expr, exceptionType, resultDisposition, macroName) \ + do { \ + Catch::ResultBuilder __catchResult(macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition); \ + if (__catchResult.allowThrows()) \ + try { \ + expr; \ + __catchResult.captureResult(Catch::ResultWas::DidntThrowException); \ + } catch (exceptionType) { \ + __catchResult.captureResult(Catch::ResultWas::Ok); \ + } catch (...) { \ + __catchResult.useActiveException(resultDisposition); \ + } \ + else \ + __catchResult.captureResult(Catch::ResultWas::Ok); \ + INTERNAL_CATCH_REACT(__catchResult) \ + } while (Catch::alwaysFalse()) + +/////////////////////////////////////////////////////////////////////////////// +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define INTERNAL_CATCH_MSG(messageType, resultDisposition, macroName, ...) \ + do { \ + Catch::ResultBuilder __catchResult(macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition); \ + __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ + __catchResult.captureResult(messageType); \ + INTERNAL_CATCH_REACT(__catchResult) \ + } while (Catch::alwaysFalse()) +#else +#define INTERNAL_CATCH_MSG(messageType, resultDisposition, macroName, log) \ + do { \ + Catch::ResultBuilder __catchResult(macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition); \ + __catchResult << log + ::Catch::StreamEndStop(); \ + __catchResult.captureResult(messageType); \ + INTERNAL_CATCH_REACT(__catchResult) \ + } while (Catch::alwaysFalse()) +#endif + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_INFO(log, macroName) \ + Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME(scopedMessage) = Catch::MessageBuilder(macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info) << log; + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CHECK_THAT(arg, matcher, resultDisposition, macroName) \ + do { \ + Catch::ResultBuilder __catchResult(macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition); \ + try { \ + std::string matcherAsString = (matcher).toString(); \ + __catchResult \ + .setLhs(Catch::toString(arg)) \ + .setRhs(matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString) \ + .setOp("matches") \ + .setResultType((matcher).match(arg)); \ + __catchResult.captureExpression(); \ + } catch (...) { \ + __catchResult.useActiveException(resultDisposition | Catch::ResultDisposition::ContinueOnFailure); \ + } \ + INTERNAL_CATCH_REACT(__catchResult) \ + } while (Catch::alwaysFalse()) + +// #included from: internal/catch_section.h +#define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED + +// #included from: catch_section_info.h +#define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED + +// #included from: catch_totals.hpp +#define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED + +#include + +namespace Catch { + +struct Counts { + Counts() + : passed(0) + , failed(0) + , failedButOk(0) {} + + Counts operator-(Counts const& other) const { + Counts diff; + diff.passed = passed - other.passed; + diff.failed = failed - other.failed; + diff.failedButOk = failedButOk - other.failedButOk; + return diff; + } + Counts& operator+=(Counts const& other) { + passed += other.passed; + failed += other.failed; + failedButOk += other.failedButOk; + return *this; + } + + std::size_t total() const { + return passed + failed + failedButOk; + } + bool allPassed() const { + return failed == 0 && failedButOk == 0; + } + bool allOk() const { + return failed == 0; + } + + std::size_t passed; + std::size_t failed; + std::size_t failedButOk; +}; + +struct Totals { + + Totals operator-(Totals const& other) const { + Totals diff; + diff.assertions = assertions - other.assertions; + diff.testCases = testCases - other.testCases; + return diff; + } + + Totals delta(Totals const& prevTotals) const { + Totals diff = *this - prevTotals; + if (diff.assertions.failed > 0) + ++diff.testCases.failed; + else if (diff.assertions.failedButOk > 0) + ++diff.testCases.failedButOk; + else + ++diff.testCases.passed; + return diff; + } + + Totals& operator+=(Totals const& other) { + assertions += other.assertions; + testCases += other.testCases; + return *this; + } + + Counts assertions; + Counts testCases; +}; +} + +namespace Catch { + +struct SectionInfo { + SectionInfo(SourceLineInfo const& _lineInfo, + std::string const& _name, + std::string const& _description = std::string()); + + std::string name; + std::string description; + SourceLineInfo lineInfo; +}; + +struct SectionEndInfo { + SectionEndInfo(SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds) + : sectionInfo(_sectionInfo) + , prevAssertions(_prevAssertions) + , durationInSeconds(_durationInSeconds) {} + + SectionInfo sectionInfo; + Counts prevAssertions; + double durationInSeconds; +}; + +} // end namespace Catch + +// #included from: catch_timer.h +#define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED + +#ifdef CATCH_PLATFORM_WINDOWS +typedef unsigned long long uint64_t; +#else +#include +#endif + +namespace Catch { + +class Timer { +public: + Timer() + : m_ticks(0) {} + void start(); + unsigned int getElapsedMicroseconds() const; + unsigned int getElapsedMilliseconds() const; + double getElapsedSeconds() const; + +private: + uint64_t m_ticks; +}; + +} // namespace Catch + +#include + +namespace Catch { + +class Section : NonCopyable { +public: + Section(SectionInfo const& info); + ~Section(); + + // This indicates whether the section should be executed or not + operator bool() const; + +private: + SectionInfo m_info; + + std::string m_name; + Counts m_assertions; + bool m_sectionIncluded; + Timer m_timer; +}; + +} // end namespace Catch + +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define INTERNAL_CATCH_SECTION(...) \ + if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, __VA_ARGS__)) +#else +#define INTERNAL_CATCH_SECTION(name, desc) \ + if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, name, desc)) +#endif + +// #included from: internal/catch_generators.hpp +#define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED + +#include +#include +#include +#include + +namespace Catch { + +template +struct IGenerator { + virtual ~IGenerator() {} + virtual T getValue(std::size_t index) const = 0; + virtual std::size_t size() const = 0; +}; + +template +class BetweenGenerator : public IGenerator { +public: + BetweenGenerator(T from, T to) + : m_from(from) + , m_to(to) {} + + virtual T getValue(std::size_t index) const { + return m_from + static_cast(index); + } + + virtual std::size_t size() const { + return static_cast(1 + m_to - m_from); + } + +private: + T m_from; + T m_to; +}; + +template +class ValuesGenerator : public IGenerator { +public: + ValuesGenerator() {} + + void add(T value) { + m_values.push_back(value); + } + + virtual T getValue(std::size_t index) const { + return m_values[index]; + } + + virtual std::size_t size() const { + return m_values.size(); + } + +private: + std::vector m_values; +}; + +template +class CompositeGenerator { +public: + CompositeGenerator() + : m_totalSize(0) {} + + // *** Move semantics, similar to auto_ptr *** + CompositeGenerator(CompositeGenerator& other) + : m_fileInfo(other.m_fileInfo) + , m_totalSize(0) { + move(other); + } + + CompositeGenerator& setFileInfo(const char* fileInfo) { + m_fileInfo = fileInfo; + return *this; + } + + ~CompositeGenerator() { + deleteAll(m_composed); + } + + operator T() const { + size_t overallIndex = getCurrentContext().getGeneratorIndex(m_fileInfo, m_totalSize); + + typename std::vector*>::const_iterator it = m_composed.begin(); + typename std::vector*>::const_iterator itEnd = m_composed.end(); + for (size_t index = 0; it != itEnd; ++it) { + const IGenerator* generator = *it; + if (overallIndex >= index && overallIndex < index + generator->size()) { + return generator->getValue(overallIndex - index); + } + index += generator->size(); + } + CATCH_INTERNAL_ERROR("Indexed past end of generated range"); + return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so + } + + void add(const IGenerator* generator) { + m_totalSize += generator->size(); + m_composed.push_back(generator); + } + + CompositeGenerator& then(CompositeGenerator& other) { + move(other); + return *this; + } + + CompositeGenerator& then(T value) { + ValuesGenerator* valuesGen = new ValuesGenerator(); + valuesGen->add(value); + add(valuesGen); + return *this; + } + +private: + void move(CompositeGenerator& other) { + std::copy(other.m_composed.begin(), other.m_composed.end(), std::back_inserter(m_composed)); + m_totalSize += other.m_totalSize; + other.m_composed.clear(); + } + + std::vector*> m_composed; + std::string m_fileInfo; + size_t m_totalSize; +}; + +namespace Generators { + template + CompositeGenerator between(T from, T to) { + CompositeGenerator generators; + generators.add(new BetweenGenerator(from, to)); + return generators; + } + + template + CompositeGenerator values(T val1, T val2) { + CompositeGenerator generators; + ValuesGenerator* valuesGen = new ValuesGenerator(); + valuesGen->add(val1); + valuesGen->add(val2); + generators.add(valuesGen); + return generators; + } + + template + CompositeGenerator values(T val1, T val2, T val3) { + CompositeGenerator generators; + ValuesGenerator* valuesGen = new ValuesGenerator(); + valuesGen->add(val1); + valuesGen->add(val2); + valuesGen->add(val3); + generators.add(valuesGen); + return generators; + } + + template + CompositeGenerator values(T val1, T val2, T val3, T val4) { + CompositeGenerator generators; + ValuesGenerator* valuesGen = new ValuesGenerator(); + valuesGen->add(val1); + valuesGen->add(val2); + valuesGen->add(val3); + valuesGen->add(val4); + generators.add(valuesGen); + return generators; + } + +} // end namespace Generators + +using namespace Generators; + +} // end namespace Catch + +#define INTERNAL_CATCH_LINESTR2(line) #line +#define INTERNAL_CATCH_LINESTR(line) INTERNAL_CATCH_LINESTR2(line) + +#define INTERNAL_CATCH_GENERATE(expr) expr.setFileInfo(__FILE__ "(" INTERNAL_CATCH_LINESTR(__LINE__) ")") + +// #included from: internal/catch_interfaces_exception.h +#define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED + +#include +#include + +// #included from: catch_interfaces_registry_hub.h +#define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED + +#include + +namespace Catch { + +class TestCase; +struct ITestCaseRegistry; +struct IExceptionTranslatorRegistry; +struct IExceptionTranslator; +struct IReporterRegistry; +struct IReporterFactory; + +struct IRegistryHub { + virtual ~IRegistryHub(); + + virtual IReporterRegistry const& getReporterRegistry() const = 0; + virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; + virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; +}; + +struct IMutableRegistryHub { + virtual ~IMutableRegistryHub(); + virtual void registerReporter(std::string const& name, Ptr const& factory) = 0; + virtual void registerListener(Ptr const& factory) = 0; + virtual void registerTest(TestCase const& testInfo) = 0; + virtual void registerTranslator(const IExceptionTranslator* translator) = 0; +}; + +IRegistryHub& getRegistryHub(); +IMutableRegistryHub& getMutableRegistryHub(); +void cleanUp(); +std::string translateActiveException(); +} + +namespace Catch { + +typedef std::string (*exceptionTranslateFunction)(); + +struct IExceptionTranslator; +typedef std::vector ExceptionTranslators; + +struct IExceptionTranslator { + virtual ~IExceptionTranslator(); + virtual std::string translate(ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd) const = 0; +}; + +struct IExceptionTranslatorRegistry { + virtual ~IExceptionTranslatorRegistry(); + + virtual std::string translateActiveException() const = 0; +}; + +class ExceptionTranslatorRegistrar { + template + class ExceptionTranslator : public IExceptionTranslator { + public: + ExceptionTranslator(std::string (*translateFunction)(T&)) + : m_translateFunction(translateFunction) {} + + virtual std::string translate(ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd) const CATCH_OVERRIDE { + try { + if (it == itEnd) + throw; + else + return (*it)->translate(it + 1, itEnd); + } catch (T& ex) { + return m_translateFunction(ex); + } + } + + protected: + std::string (*m_translateFunction)(T&); + }; + +public: + template + ExceptionTranslatorRegistrar(std::string (*translateFunction)(T&)) { + getMutableRegistryHub().registerTranslator(new ExceptionTranslator(translateFunction)); + } +}; +} + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature) \ + static std::string translatorName(signature); \ + namespace { \ + Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionRegistrar)(&translatorName); \ + } \ + static std::string translatorName(signature) + +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION2(INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature) + +// #included from: internal/catch_approx.hpp +#define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED + +#include +#include + +namespace Catch { +namespace Detail { + + class Approx { + public: + explicit Approx(double value) + : m_epsilon(std::numeric_limits::epsilon() * 100) + , m_scale(1.0) + , m_value(value) {} + + Approx(Approx const& other) + : m_epsilon(other.m_epsilon) + , m_scale(other.m_scale) + , m_value(other.m_value) {} + + static Approx custom() { + return Approx(0); + } + + Approx operator()(double value) { + Approx approx(value); + approx.epsilon(m_epsilon); + approx.scale(m_scale); + return approx; + } + + friend bool operator==(double lhs, Approx const& rhs) { + // Thanks to Richard Harris for his help refining this formula + return fabs(lhs - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + (std::max)(fabs(lhs), fabs(rhs.m_value))); + } + + friend bool operator==(Approx const& lhs, double rhs) { + return operator==(rhs, lhs); + } + + friend bool operator!=(double lhs, Approx const& rhs) { + return !operator==(lhs, rhs); + } + + friend bool operator!=(Approx const& lhs, double rhs) { + return !operator==(rhs, lhs); + } + + Approx& epsilon(double newEpsilon) { + m_epsilon = newEpsilon; + return *this; + } + + Approx& scale(double newScale) { + m_scale = newScale; + return *this; + } + + std::string toString() const { + std::ostringstream oss; + oss << "Approx( " << Catch::toString(m_value) << " )"; + return oss.str(); + } + + private: + double m_epsilon; + double m_scale; + double m_value; + }; +} + +template <> +inline std::string toString(Detail::Approx const& value) { + return value.toString(); +} + +} // end namespace Catch + +// #included from: internal/catch_interfaces_tag_alias_registry.h +#define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED + +// #included from: catch_tag_alias.h +#define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED + +#include + +namespace Catch { + +struct TagAlias { + TagAlias(std::string _tag, SourceLineInfo _lineInfo) + : tag(_tag) + , lineInfo(_lineInfo) {} + + std::string tag; + SourceLineInfo lineInfo; +}; + +struct RegistrarForTagAliases { + RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo); +}; + +} // end namespace Catch + +#define CATCH_REGISTER_TAG_ALIAS(alias, spec) \ + namespace { \ + Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME(AutoRegisterTagAlias)(alias, spec, CATCH_INTERNAL_LINEINFO); \ + } +// #included from: catch_option.hpp +#define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED + +namespace Catch { + +// An optional type +template +class Option { +public: + Option() + : nullableValue(CATCH_NULL) {} + Option(T const& _value) + : nullableValue(new (storage) T(_value)) {} + Option(Option const& _other) + : nullableValue(_other ? new (storage) T(*_other) : CATCH_NULL) {} + + ~Option() { + reset(); + } + + Option& operator=(Option const& _other) { + if (&_other != this) { + reset(); + if (_other) + nullableValue = new (storage) T(*_other); + } + return *this; + } + Option& operator=(T const& _value) { + reset(); + nullableValue = new (storage) T(_value); + return *this; + } + + void reset() { + if (nullableValue) + nullableValue->~T(); + nullableValue = CATCH_NULL; + } + + T& operator*() { return *nullableValue; } + T const& operator*() const { return *nullableValue; } + T* operator->() { return nullableValue; } + const T* operator->() const { return nullableValue; } + + T valueOr(T const& defaultValue) const { + return nullableValue ? *nullableValue : defaultValue; + } + + bool some() const { return nullableValue != CATCH_NULL; } + bool none() const { return nullableValue == CATCH_NULL; } + + bool operator!() const { return nullableValue == CATCH_NULL; } + operator SafeBool::type() const { + return SafeBool::makeSafe(some()); + } + +private: + T* nullableValue; + char storage[sizeof(T)]; +}; + +} // end namespace Catch + +namespace Catch { + +struct ITagAliasRegistry { + virtual ~ITagAliasRegistry(); + virtual Option find(std::string const& alias) const = 0; + virtual std::string expandAliases(std::string const& unexpandedTestSpec) const = 0; + + static ITagAliasRegistry const& get(); +}; + +} // end namespace Catch + +// These files are included here so the single_include script doesn't put them +// in the conditionally compiled sections +// #included from: internal/catch_test_case_info.h +#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED + +#include +#include + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +namespace Catch { + +struct ITestCase; + +struct TestCaseInfo { + enum SpecialProperties { + None = 0, + IsHidden = 1 << 1, + ShouldFail = 1 << 2, + MayFail = 1 << 3, + Throws = 1 << 4 + }; + + TestCaseInfo(std::string const& _name, + std::string const& _className, + std::string const& _description, + std::set const& _tags, + SourceLineInfo const& _lineInfo); + + TestCaseInfo(TestCaseInfo const& other); + + friend void setTags(TestCaseInfo& testCaseInfo, std::set const& tags); + + bool isHidden() const; + bool throws() const; + bool okToFail() const; + bool expectedToFail() const; + + std::string name; + std::string className; + std::string description; + std::set tags; + std::set lcaseTags; + std::string tagsAsString; + SourceLineInfo lineInfo; + SpecialProperties properties; +}; + +class TestCase : public TestCaseInfo { +public: + TestCase(ITestCase* testCase, TestCaseInfo const& info); + TestCase(TestCase const& other); + + TestCase withName(std::string const& _newName) const; + + void invoke() const; + + TestCaseInfo const& getTestCaseInfo() const; + + void swap(TestCase& other); + bool operator==(TestCase const& other) const; + bool operator<(TestCase const& other) const; + TestCase& operator=(TestCase const& other); + +private: + Ptr test; +}; + +TestCase makeTestCase(ITestCase* testCase, + std::string const& className, + std::string const& name, + std::string const& description, + SourceLineInfo const& lineInfo); +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef __OBJC__ +// #included from: internal/catch_objc.hpp +#define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED + +#import + +#include + +// NB. Any general catch headers included here must be included +// in catch.hpp first to make sure they are included by the single +// header for non obj-usage + +/////////////////////////////////////////////////////////////////////////////// +// This protocol is really only here for (self) documenting purposes, since +// all its methods are optional. +@protocol OcFixture + +@optional + +- (void)setUp; +- (void)tearDown; + +@end + +namespace Catch { + +class OcMethod : public SharedImpl { + +public: + OcMethod(Class cls, SEL sel) + : m_cls(cls) + , m_sel(sel) {} + + virtual void invoke() const { + id obj = [[m_cls alloc] init]; + + performOptionalSelector(obj, @selector(setUp)); + performOptionalSelector(obj, m_sel); + performOptionalSelector(obj, @selector(tearDown)); + + arcSafeRelease(obj); + } + +private: + virtual ~OcMethod() {} + + Class m_cls; + SEL m_sel; +}; + +namespace Detail { + + inline std::string getAnnotation(Class cls, + std::string const& annotationName, + std::string const& testCaseName) { + NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; + SEL sel = NSSelectorFromString(selStr); + arcSafeRelease(selStr); + id value = performOptionalSelector(cls, sel); + if (value) + return [(NSString*)value UTF8String]; + return ""; + } +} + +inline size_t registerTestMethods() { + size_t noTestMethods = 0; + int noClasses = objc_getClassList(CATCH_NULL, 0); + + Class* classes = (CATCH_UNSAFE_UNRETAINED Class*)malloc(sizeof(Class) * noClasses); + objc_getClassList(classes, noClasses); + + for (int c = 0; c < noClasses; c++) { + Class cls = classes[c]; + { + u_int count; + Method* methods = class_copyMethodList(cls, &count); + for (u_int m = 0; m < count; m++) { + SEL selector = method_getName(methods[m]); + std::string methodName = sel_getName(selector); + if (startsWith(methodName, "Catch_TestCase_")) { + std::string testCaseName = methodName.substr(15); + std::string name = Detail::getAnnotation(cls, "Name", testCaseName); + std::string desc = Detail::getAnnotation(cls, "Description", testCaseName); + const char* className = class_getName(cls); + + getMutableRegistryHub().registerTest(makeTestCase(new OcMethod(cls, selector), className, name.c_str(), desc.c_str(), SourceLineInfo())); + noTestMethods++; + } + } + free(methods); + } + } + return noTestMethods; +} + +namespace Matchers { + namespace Impl { + namespace NSStringMatchers { + + template + struct StringHolder : MatcherImpl { + StringHolder(NSString* substr) + : m_substr([substr copy]) {} + StringHolder(StringHolder const& other) + : m_substr([other.m_substr copy]) {} + StringHolder() { + arcSafeRelease(m_substr); + } + + NSString* m_substr; + }; + + struct Equals : StringHolder { + Equals(NSString* substr) + : StringHolder(substr) {} + + virtual bool match(ExpressionType const& str) const { + return (str != nil || m_substr == nil) && + [str isEqualToString:m_substr]; + } + + virtual std::string toString() const { + return "equals string: " + Catch::toString(m_substr); + } + }; + + struct Contains : StringHolder { + Contains(NSString* substr) + : StringHolder(substr) {} + + virtual bool match(ExpressionType const& str) const { + return (str != nil || m_substr == nil) && + [str rangeOfString:m_substr].location != NSNotFound; + } + + virtual std::string toString() const { + return "contains string: " + Catch::toString(m_substr); + } + }; + + struct StartsWith : StringHolder { + StartsWith(NSString* substr) + : StringHolder(substr) {} + + virtual bool match(ExpressionType const& str) const { + return (str != nil || m_substr == nil) && + [str rangeOfString:m_substr].location == 0; + } + + virtual std::string toString() const { + return "starts with: " + Catch::toString(m_substr); + } + }; + struct EndsWith : StringHolder { + EndsWith(NSString* substr) + : StringHolder(substr) {} + + virtual bool match(ExpressionType const& str) const { + return (str != nil || m_substr == nil) && + [str rangeOfString:m_substr].location == [str length] - [m_substr length]; + } + + virtual std::string toString() const { + return "ends with: " + Catch::toString(m_substr); + } + }; + + } // namespace NSStringMatchers + } // namespace Impl + + inline Impl::NSStringMatchers::Equals + Equals(NSString* substr) { return Impl::NSStringMatchers::Equals(substr); } + + inline Impl::NSStringMatchers::Contains + Contains(NSString* substr) { return Impl::NSStringMatchers::Contains(substr); } + + inline Impl::NSStringMatchers::StartsWith + StartsWith(NSString* substr) { return Impl::NSStringMatchers::StartsWith(substr); } + + inline Impl::NSStringMatchers::EndsWith + EndsWith(NSString* substr) { return Impl::NSStringMatchers::EndsWith(substr); } + +} // namespace Matchers + +using namespace Matchers; + +} // namespace Catch + +/////////////////////////////////////////////////////////////////////////////// +#define OC_TEST_CASE(name, desc) \ + +(NSString*)INTERNAL_CATCH_UNIQUE_NAME(Catch_Name_test) { \ + return @name; \ + } \ + +(NSString*)INTERNAL_CATCH_UNIQUE_NAME(Catch_Description_test) { \ + return @desc; \ + } \ + -(void)INTERNAL_CATCH_UNIQUE_NAME(Catch_TestCase_test) + +#endif + +#ifdef CATCH_IMPL +// #included from: internal/catch_impl.hpp +#define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED + +// Collect all the implementation files together here +// These are the equivalent of what would usually be cpp files + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wweak-vtables" +#endif + +// #included from: ../catch_session.hpp +#define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED + +// #included from: internal/catch_commandline.hpp +#define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED + +// #included from: catch_config.hpp +#define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED + +// #included from: catch_test_spec_parser.hpp +#define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +// #included from: catch_test_spec.hpp +#define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +// #included from: catch_wildcard_pattern.hpp +#define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED + +namespace Catch { +class WildcardPattern { + enum WildcardPosition { + NoWildcard = 0, + WildcardAtStart = 1, + WildcardAtEnd = 2, + WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd + }; + +public: + WildcardPattern(std::string const& pattern, CaseSensitive::Choice caseSensitivity) + : m_caseSensitivity(caseSensitivity) + , m_wildcard(NoWildcard) + , m_pattern(adjustCase(pattern)) { + if (startsWith(m_pattern, "*")) { + m_pattern = m_pattern.substr(1); + m_wildcard = WildcardAtStart; + } + if (endsWith(m_pattern, "*")) { + m_pattern = m_pattern.substr(0, m_pattern.size() - 1); + m_wildcard = static_cast(m_wildcard | WildcardAtEnd); + } + } + virtual ~WildcardPattern(); + virtual bool matches(std::string const& str) const { + switch (m_wildcard) { + case NoWildcard: + return m_pattern == adjustCase(str); + case WildcardAtStart: + return endsWith(adjustCase(str), m_pattern); + case WildcardAtEnd: + return startsWith(adjustCase(str), m_pattern); + case WildcardAtBothEnds: + return contains(adjustCase(str), m_pattern); + } + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunreachable-code" +#endif + throw std::logic_error("Unknown enum"); +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + } + +private: + std::string adjustCase(std::string const& str) const { + return m_caseSensitivity == CaseSensitive::No ? toLower(str) : str; + } + CaseSensitive::Choice m_caseSensitivity; + WildcardPosition m_wildcard; + std::string m_pattern; +}; +} + +#include +#include + +namespace Catch { + +class TestSpec { + struct Pattern : SharedImpl<> { + virtual ~Pattern(); + virtual bool matches(TestCaseInfo const& testCase) const = 0; + }; + class NamePattern : public Pattern { + public: + NamePattern(std::string const& name) + : m_wildcardPattern(toLower(name), CaseSensitive::No) {} + virtual ~NamePattern(); + virtual bool matches(TestCaseInfo const& testCase) const { + return m_wildcardPattern.matches(toLower(testCase.name)); + } + + private: + WildcardPattern m_wildcardPattern; + }; + + class TagPattern : public Pattern { + public: + TagPattern(std::string const& tag) + : m_tag(toLower(tag)) {} + virtual ~TagPattern(); + virtual bool matches(TestCaseInfo const& testCase) const { + return testCase.lcaseTags.find(m_tag) != testCase.lcaseTags.end(); + } + + private: + std::string m_tag; + }; + + class ExcludedPattern : public Pattern { + public: + ExcludedPattern(Ptr const& underlyingPattern) + : m_underlyingPattern(underlyingPattern) {} + virtual ~ExcludedPattern(); + virtual bool matches(TestCaseInfo const& testCase) const { return !m_underlyingPattern->matches(testCase); } + + private: + Ptr m_underlyingPattern; + }; + + struct Filter { + std::vector> m_patterns; + + bool matches(TestCaseInfo const& testCase) const { + // All patterns in a filter must match for the filter to be a match + for (std::vector>::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it) + if (!(*it)->matches(testCase)) + return false; + return true; + } + }; + +public: + bool hasFilters() const { + return !m_filters.empty(); + } + bool matches(TestCaseInfo const& testCase) const { + // A TestSpec matches if any filter matches + for (std::vector::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it) + if (it->matches(testCase)) + return true; + return false; + } + +private: + std::vector m_filters; + + friend class TestSpecParser; +}; +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +namespace Catch { + +class TestSpecParser { + enum Mode { None, + Name, + QuotedName, + Tag }; + Mode m_mode; + bool m_exclusion; + std::size_t m_start, m_pos; + std::string m_arg; + TestSpec::Filter m_currentFilter; + TestSpec m_testSpec; + ITagAliasRegistry const* m_tagAliases; + +public: + TestSpecParser(ITagAliasRegistry const& tagAliases) + : m_tagAliases(&tagAliases) {} + + TestSpecParser& parse(std::string const& arg) { + m_mode = None; + m_exclusion = false; + m_start = std::string::npos; + m_arg = m_tagAliases->expandAliases(arg); + for (m_pos = 0; m_pos < m_arg.size(); ++m_pos) + visitChar(m_arg[m_pos]); + if (m_mode == Name) + addPattern(); + return *this; + } + TestSpec testSpec() { + addFilter(); + return m_testSpec; + } + +private: + void visitChar(char c) { + if (m_mode == None) { + switch (c) { + case ' ': + return; + case '~': + m_exclusion = true; + return; + case '[': + return startNewMode(Tag, ++m_pos); + case '"': + return startNewMode(QuotedName, ++m_pos); + default: + startNewMode(Name, m_pos); + break; + } + } + if (m_mode == Name) { + if (c == ',') { + addPattern(); + addFilter(); + } else if (c == '[') { + if (subString() == "exclude:") + m_exclusion = true; + else + addPattern(); + startNewMode(Tag, ++m_pos); + } + } else if (m_mode == QuotedName && c == '"') + addPattern(); + else if (m_mode == Tag && c == ']') + addPattern(); + } + void startNewMode(Mode mode, std::size_t start) { + m_mode = mode; + m_start = start; + } + std::string subString() const { return m_arg.substr(m_start, m_pos - m_start); } + template + void addPattern() { + std::string token = subString(); + if (startsWith(token, "exclude:")) { + m_exclusion = true; + token = token.substr(8); + } + if (!token.empty()) { + Ptr pattern = new T(token); + if (m_exclusion) + pattern = new TestSpec::ExcludedPattern(pattern); + m_currentFilter.m_patterns.push_back(pattern); + } + m_exclusion = false; + m_mode = None; + } + void addFilter() { + if (!m_currentFilter.m_patterns.empty()) { + m_testSpec.m_filters.push_back(m_currentFilter); + m_currentFilter = TestSpec::Filter(); + } + } +}; +inline TestSpec parseTestSpec(std::string const& arg) { + return TestSpecParser(ITagAliasRegistry::get()).parse(arg).testSpec(); +} + +} // namespace Catch + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +// #included from: catch_interfaces_config.h +#define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED + +#include +#include +#include + +namespace Catch { + +struct Verbosity { + enum Level { + NoOutput = 0, + Quiet, + Normal + }; +}; + +struct WarnAbout { + enum What { + Nothing = 0x00, + NoAssertions = 0x01 + }; +}; + +struct ShowDurations { + enum OrNot { + DefaultForReporter, + Always, + Never + }; +}; +struct RunTests { + enum InWhatOrder { + InDeclarationOrder, + InLexicographicalOrder, + InRandomOrder + }; +}; +struct UseColour { + enum YesOrNo { + Auto, + Yes, + No + }; +}; + +class TestSpec; + +struct IConfig : IShared { + + virtual ~IConfig(); + + virtual bool allowThrows() const = 0; + virtual std::ostream& stream() const = 0; + virtual std::string name() const = 0; + virtual bool includeSuccessfulResults() const = 0; + virtual bool shouldDebugBreak() const = 0; + virtual bool warnAboutMissingAssertions() const = 0; + virtual int abortAfter() const = 0; + virtual bool showInvisibles() const = 0; + virtual ShowDurations::OrNot showDurations() const = 0; + virtual TestSpec const& testSpec() const = 0; + virtual RunTests::InWhatOrder runOrder() const = 0; + virtual unsigned int rngSeed() const = 0; + virtual UseColour::YesOrNo useColour() const = 0; +}; +} + +// #included from: catch_stream.h +#define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED + +// #included from: catch_streambuf.h +#define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED + +#include + +namespace Catch { + +class StreamBufBase : public std::streambuf { +public: + virtual ~StreamBufBase() CATCH_NOEXCEPT; +}; +} + +#include +#include +#include + +namespace Catch { + +std::ostream& cout(); +std::ostream& cerr(); + +struct IStream { + virtual ~IStream() CATCH_NOEXCEPT; + virtual std::ostream& stream() const = 0; +}; + +class FileStream : public IStream { + mutable std::ofstream m_ofs; + +public: + FileStream(std::string const& filename); + virtual ~FileStream() CATCH_NOEXCEPT; + +public: // IStream + virtual std::ostream& stream() const CATCH_OVERRIDE; +}; + +class CoutStream : public IStream { + mutable std::ostream m_os; + +public: + CoutStream(); + virtual ~CoutStream() CATCH_NOEXCEPT; + +public: // IStream + virtual std::ostream& stream() const CATCH_OVERRIDE; +}; + +class DebugOutStream : public IStream { + CATCH_AUTO_PTR(StreamBufBase) + m_streamBuf; + mutable std::ostream m_os; + +public: + DebugOutStream(); + virtual ~DebugOutStream() CATCH_NOEXCEPT; + +public: // IStream + virtual std::ostream& stream() const CATCH_OVERRIDE; +}; +} + +#include +#include +#include +#include +#include + +#ifndef CATCH_CONFIG_CONSOLE_WIDTH +#define CATCH_CONFIG_CONSOLE_WIDTH 80 +#endif + +namespace Catch { + +struct ConfigData { + + ConfigData() + : listTests(false) + , listTags(false) + , listReporters(false) + , listTestNamesOnly(false) + , showSuccessfulTests(false) + , shouldDebugBreak(false) + , noThrow(false) + , showHelp(false) + , showInvisibles(false) + , filenamesAsTags(false) + , abortAfter(-1) + , rngSeed(0) + , verbosity(Verbosity::Normal) + , warnings(WarnAbout::Nothing) + , showDurations(ShowDurations::DefaultForReporter) + , runOrder(RunTests::InDeclarationOrder) + , useColour(UseColour::Auto) {} + + bool listTests; + bool listTags; + bool listReporters; + bool listTestNamesOnly; + + bool showSuccessfulTests; + bool shouldDebugBreak; + bool noThrow; + bool showHelp; + bool showInvisibles; + bool filenamesAsTags; + + int abortAfter; + unsigned int rngSeed; + + Verbosity::Level verbosity; + WarnAbout::What warnings; + ShowDurations::OrNot showDurations; + RunTests::InWhatOrder runOrder; + UseColour::YesOrNo useColour; + + std::string outputFilename; + std::string name; + std::string processName; + + std::vector reporterNames; + std::vector testsOrTags; +}; + +class Config : public SharedImpl { +private: + Config(Config const& other); + Config& operator=(Config const& other); + virtual void dummy(); + +public: + Config() {} + + Config(ConfigData const& data) + : m_data(data) + , m_stream(openStream()) { + if (!data.testsOrTags.empty()) { + TestSpecParser parser(ITagAliasRegistry::get()); + for (std::size_t i = 0; i < data.testsOrTags.size(); ++i) + parser.parse(data.testsOrTags[i]); + m_testSpec = parser.testSpec(); + } + } + + virtual ~Config() { + } + + std::string const& getFilename() const { + return m_data.outputFilename; + } + + bool listTests() const { return m_data.listTests; } + bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } + bool listTags() const { return m_data.listTags; } + bool listReporters() const { return m_data.listReporters; } + + std::string getProcessName() const { return m_data.processName; } + + bool shouldDebugBreak() const { return m_data.shouldDebugBreak; } + + std::vector getReporterNames() const { return m_data.reporterNames; } + + int abortAfter() const { return m_data.abortAfter; } + + TestSpec const& testSpec() const { return m_testSpec; } + + bool showHelp() const { return m_data.showHelp; } + bool showInvisibles() const { return m_data.showInvisibles; } + + // IConfig interface + virtual bool allowThrows() const { return !m_data.noThrow; } + virtual std::ostream& stream() const { return m_stream->stream(); } + virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } + virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; } + virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; } + virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; } + virtual RunTests::InWhatOrder runOrder() const { return m_data.runOrder; } + virtual unsigned int rngSeed() const { return m_data.rngSeed; } + virtual UseColour::YesOrNo useColour() const { return m_data.useColour; } + +private: + IStream const* openStream() { + if (m_data.outputFilename.empty()) + return new CoutStream(); + else if (m_data.outputFilename[0] == '%') { + if (m_data.outputFilename == "%debug") + return new DebugOutStream(); + else + throw std::domain_error("Unrecognised stream: " + m_data.outputFilename); + } else + return new FileStream(m_data.outputFilename); + } + ConfigData m_data; + + CATCH_AUTO_PTR(IStream const) + m_stream; + TestSpec m_testSpec; +}; + +} // end namespace Catch + +// #included from: catch_clara.h +#define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED + +// Use Catch's value for console width (store Clara's off to the side, if present) +#ifdef CLARA_CONFIG_CONSOLE_WIDTH +#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH +#undef CLARA_CONFIG_CONSOLE_WIDTH +#endif +#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH + +// Declare Clara inside the Catch namespace +#define STITCH_CLARA_OPEN_NAMESPACE namespace Catch { +// #included from: ../external/clara.h + +// Version 0.0.2.4 + +// Only use header guard if we are not using an outer namespace +#if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE) + +#ifndef STITCH_CLARA_OPEN_NAMESPACE +#define TWOBLUECUBES_CLARA_H_INCLUDED +#define STITCH_CLARA_OPEN_NAMESPACE +#define STITCH_CLARA_CLOSE_NAMESPACE +#else +#define STITCH_CLARA_CLOSE_NAMESPACE } +#endif + +#define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE + +// ----------- #included from tbc_text_format.h ----------- + +// Only use header guard if we are not using an outer namespace +#if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE) +#ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE +#define TBC_TEXT_FORMAT_H_INCLUDED +#endif + +#include +#include +#include +#include + +// Use optional outer namespace +#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE +namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE { +#endif + +namespace Tbc { + +#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH + const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; +#else +const unsigned int consoleWidth = 80; +#endif + + struct TextAttributes { + TextAttributes() + : initialIndent(std::string::npos) + , indent(0) + , width(consoleWidth - 1) + , tabChar('\t') {} + + TextAttributes& setInitialIndent(std::size_t _value) { + initialIndent = _value; + return *this; + } + TextAttributes& setIndent(std::size_t _value) { + indent = _value; + return *this; + } + TextAttributes& setWidth(std::size_t _value) { + width = _value; + return *this; + } + TextAttributes& setTabChar(char _value) { + tabChar = _value; + return *this; + } + + std::size_t initialIndent; // indent of first line, or npos + std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos + std::size_t width; // maximum width of text, including indent. Longer text will wrap + char tabChar; // If this char is seen the indent is changed to current pos + }; + + class Text { + public: + Text(std::string const& _str, TextAttributes const& _attr = TextAttributes()) + : attr(_attr) { + std::string wrappableChars = " [({.,/|\\-"; + std::size_t indent = _attr.initialIndent != std::string::npos + ? _attr.initialIndent + : _attr.indent; + std::string remainder = _str; + + while (!remainder.empty()) { + if (lines.size() >= 1000) { + lines.push_back("... message truncated due to excessive size"); + return; + } + std::size_t tabPos = std::string::npos; + std::size_t width = (std::min)(remainder.size(), _attr.width - indent); + std::size_t pos = remainder.find_first_of('\n'); + if (pos <= width) { + width = pos; + } + pos = remainder.find_last_of(_attr.tabChar, width); + if (pos != std::string::npos) { + tabPos = pos; + if (remainder[width] == '\n') + width--; + remainder = remainder.substr(0, tabPos) + remainder.substr(tabPos + 1); + } + + if (width == remainder.size()) { + spliceLine(indent, remainder, width); + } else if (remainder[width] == '\n') { + spliceLine(indent, remainder, width); + if (width <= 1 || remainder.size() != 1) + remainder = remainder.substr(1); + indent = _attr.indent; + } else { + pos = remainder.find_last_of(wrappableChars, width); + if (pos != std::string::npos && pos > 0) { + spliceLine(indent, remainder, pos); + if (remainder[0] == ' ') + remainder = remainder.substr(1); + } else { + spliceLine(indent, remainder, width - 1); + lines.back() += "-"; + } + if (lines.size() == 1) + indent = _attr.indent; + if (tabPos != std::string::npos) + indent += tabPos; + } + } + } + + void spliceLine(std::size_t _indent, std::string& _remainder, std::size_t _pos) { + lines.push_back(std::string(_indent, ' ') + _remainder.substr(0, _pos)); + _remainder = _remainder.substr(_pos); + } + + typedef std::vector::const_iterator const_iterator; + + const_iterator begin() const { return lines.begin(); } + const_iterator end() const { return lines.end(); } + std::string const& last() const { return lines.back(); } + std::size_t size() const { return lines.size(); } + std::string const& operator[](std::size_t _index) const { return lines[_index]; } + std::string toString() const { + std::ostringstream oss; + oss << *this; + return oss.str(); + } + + inline friend std::ostream& operator<<(std::ostream& _stream, Text const& _text) { + for (Text::const_iterator it = _text.begin(), itEnd = _text.end(); + it != itEnd; ++it) { + if (it != _text.begin()) + _stream << "\n"; + _stream << *it; + } + return _stream; + } + + private: + std::string str; + TextAttributes attr; + std::vector lines; + }; + +} // end namespace Tbc + +#ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE +} // end outer namespace +#endif + +#endif // TBC_TEXT_FORMAT_H_INCLUDED + +// ----------- end of #include from tbc_text_format.h ----------- +// ........... back in clara.h + +#undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE + +// ----------- #included from clara_compilers.h ----------- + +#ifndef TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED +#define TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED + +// Detect a number of compiler features - mostly C++11/14 conformance - by compiler +// The following features are defined: +// +// CLARA_CONFIG_CPP11_NULLPTR : is nullptr supported? +// CLARA_CONFIG_CPP11_NOEXCEPT : is noexcept supported? +// CLARA_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods +// CLARA_CONFIG_CPP11_OVERRIDE : is override supported? +// CLARA_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) + +// CLARA_CONFIG_CPP11_OR_GREATER : Is C++11 supported? + +// CLARA_CONFIG_VARIADIC_MACROS : are variadic macros supported? + +// In general each macro has a _NO_ form +// (e.g. CLARA_CONFIG_CPP11_NO_NULLPTR) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +// All the C++11 features can be disabled with CLARA_CONFIG_NO_CPP11 + +#ifdef __clang__ + +#if __has_feature(cxx_nullptr) +#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +#if __has_feature(cxx_noexcept) +#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT +#endif + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// GCC +#ifdef __GNUC__ + +#if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) +#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +// - otherwise more recent versions define __cplusplus >= 201103L +// and will get picked up below + +#endif // __GNUC__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#ifdef _MSC_VER + +#if (_MSC_VER >= 1600) +#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR +#define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR +#endif + +#if (_MSC_VER >= 1900) // (VC++ 13 (VS2015)) +#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT +#define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#endif + +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// +// C++ language feature support + +// catch all support for C++11 +#if defined(__cplusplus) && __cplusplus >= 201103L + +#define CLARA_CPP11_OR_GREATER + +#if !defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) +#define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR +#endif + +#ifndef CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT +#define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT +#endif + +#ifndef CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS +#endif + +#if !defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) +#define CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE +#endif +#if !defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) +#define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR +#endif + +#endif // __cplusplus >= 201103L + +// Now set the actual defines based on the above + anything the user has configured +#if defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NO_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_NULLPTR +#endif +#if defined(CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_NOEXCEPT +#endif +#if defined(CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_GENERATED_METHODS +#endif +#if defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_OVERRIDE) && !defined(CLARA_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_OVERRIDE +#endif +#if defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_UNIQUE_PTR) && !defined(CLARA_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_CPP11) +#define CLARA_CONFIG_CPP11_UNIQUE_PTR +#endif + +// noexcept support: +#if defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_NOEXCEPT) +#define CLARA_NOEXCEPT noexcept +#define CLARA_NOEXCEPT_IS(x) noexcept(x) +#else +#define CLARA_NOEXCEPT throw() +#define CLARA_NOEXCEPT_IS(x) +#endif + +// nullptr support +#ifdef CLARA_CONFIG_CPP11_NULLPTR +#define CLARA_NULL nullptr +#else +#define CLARA_NULL NULL +#endif + +// override support +#ifdef CLARA_CONFIG_CPP11_OVERRIDE +#define CLARA_OVERRIDE override +#else +#define CLARA_OVERRIDE +#endif + +// unique_ptr support +#ifdef CLARA_CONFIG_CPP11_UNIQUE_PTR +#define CLARA_AUTO_PTR(T) std::unique_ptr +#else +#define CLARA_AUTO_PTR(T) std::auto_ptr +#endif + +#endif // TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED + +// ----------- end of #include from clara_compilers.h ----------- +// ........... back in clara.h + +#include +#include +#include + +#if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) +#define CLARA_PLATFORM_WINDOWS +#endif + +// Use optional outer namespace +#ifdef STITCH_CLARA_OPEN_NAMESPACE +STITCH_CLARA_OPEN_NAMESPACE +#endif + +namespace Clara { + +struct UnpositionalTag {}; + +extern UnpositionalTag _; + +#ifdef CLARA_CONFIG_MAIN +UnpositionalTag _; +#endif + +namespace Detail { + +#ifdef CLARA_CONSOLE_WIDTH + const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; +#else + const unsigned int consoleWidth = 80; +#endif + + using namespace Tbc; + + inline bool startsWith(std::string const& str, std::string const& prefix) { + return str.size() >= prefix.size() && str.substr(0, prefix.size()) == prefix; + } + + template + struct RemoveConstRef { typedef T type; }; + template + struct RemoveConstRef { typedef T type; }; + template + struct RemoveConstRef { typedef T type; }; + template + struct RemoveConstRef { typedef T type; }; + + template + struct IsBool { static const bool value = false; }; + template <> + struct IsBool { static const bool value = true; }; + + template + void convertInto(std::string const& _source, T& _dest) { + std::stringstream ss; + ss << _source; + ss >> _dest; + if (ss.fail()) + throw std::runtime_error("Unable to convert " + _source + " to destination type"); + } + inline void convertInto(std::string const& _source, std::string& _dest) { + _dest = _source; + } + inline void convertInto(std::string const& _source, bool& _dest) { + std::string sourceLC = _source; + std::transform(sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower); + if (sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on") + _dest = true; + else if (sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off") + _dest = false; + else + throw std::runtime_error("Expected a boolean value but did not recognise:\n '" + _source + "'"); + } + + template + struct IArgFunction { + virtual ~IArgFunction() {} +#ifdef CLARA_CONFIG_CPP11_GENERATED_METHODS + IArgFunction() = default; + IArgFunction(IArgFunction const&) = default; +#endif + virtual void set(ConfigT& config, std::string const& value) const = 0; + virtual bool takesArg() const = 0; + virtual IArgFunction* clone() const = 0; + }; + + template + class BoundArgFunction { + public: + BoundArgFunction() + : functionObj(CLARA_NULL) {} + BoundArgFunction(IArgFunction* _functionObj) + : functionObj(_functionObj) {} + BoundArgFunction(BoundArgFunction const& other) + : functionObj(other.functionObj ? other.functionObj->clone() : CLARA_NULL) {} + BoundArgFunction& operator=(BoundArgFunction const& other) { + IArgFunction* newFunctionObj = other.functionObj ? other.functionObj->clone() : CLARA_NULL; + delete functionObj; + functionObj = newFunctionObj; + return *this; + } + ~BoundArgFunction() { delete functionObj; } + + void set(ConfigT& config, std::string const& value) const { + functionObj->set(config, value); + } + bool takesArg() const { return functionObj->takesArg(); } + + bool isSet() const { + return functionObj != CLARA_NULL; + } + + private: + IArgFunction* functionObj; + }; + + template + struct NullBinder : IArgFunction { + virtual void set(C&, std::string const&) const {} + virtual bool takesArg() const { return true; } + virtual IArgFunction* clone() const { return new NullBinder(*this); } + }; + + template + struct BoundDataMember : IArgFunction { + BoundDataMember(M C::*_member) + : member(_member) {} + virtual void set(C& p, std::string const& stringValue) const { + convertInto(stringValue, p.*member); + } + virtual bool takesArg() const { return !IsBool::value; } + virtual IArgFunction* clone() const { return new BoundDataMember(*this); } + M C::*member; + }; + template + struct BoundUnaryMethod : IArgFunction { + BoundUnaryMethod(void (C::*_member)(M)) + : member(_member) {} + virtual void set(C& p, std::string const& stringValue) const { + typename RemoveConstRef::type value; + convertInto(stringValue, value); + (p.*member)(value); + } + virtual bool takesArg() const { return !IsBool::value; } + virtual IArgFunction* clone() const { return new BoundUnaryMethod(*this); } + void (C::*member)(M); + }; + template + struct BoundNullaryMethod : IArgFunction { + BoundNullaryMethod(void (C::*_member)()) + : member(_member) {} + virtual void set(C& p, std::string const& stringValue) const { + bool value; + convertInto(stringValue, value); + if (value) + (p.*member)(); + } + virtual bool takesArg() const { return false; } + virtual IArgFunction* clone() const { return new BoundNullaryMethod(*this); } + void (C::*member)(); + }; + + template + struct BoundUnaryFunction : IArgFunction { + BoundUnaryFunction(void (*_function)(C&)) + : function(_function) {} + virtual void set(C& obj, std::string const& stringValue) const { + bool value; + convertInto(stringValue, value); + if (value) + function(obj); + } + virtual bool takesArg() const { return false; } + virtual IArgFunction* clone() const { return new BoundUnaryFunction(*this); } + void (*function)(C&); + }; + + template + struct BoundBinaryFunction : IArgFunction { + BoundBinaryFunction(void (*_function)(C&, T)) + : function(_function) {} + virtual void set(C& obj, std::string const& stringValue) const { + typename RemoveConstRef::type value; + convertInto(stringValue, value); + function(obj, value); + } + virtual bool takesArg() const { return !IsBool::value; } + virtual IArgFunction* clone() const { return new BoundBinaryFunction(*this); } + void (*function)(C&, T); + }; + +} // namespace Detail + +inline std::vector argsToVector(int argc, char const* const* const argv) { + std::vector args(static_cast(argc)); + for (std::size_t i = 0; i < static_cast(argc); ++i) + args[i] = argv[i]; + + return args; +} + +class Parser { + enum Mode { None, + MaybeShortOpt, + SlashOpt, + ShortOpt, + LongOpt, + Positional }; + Mode mode; + std::size_t from; + bool inQuotes; + +public: + struct Token { + enum Type { Positional, + ShortOpt, + LongOpt }; + Token(Type _type, std::string const& _data) + : type(_type) + , data(_data) {} + Type type; + std::string data; + }; + + Parser() + : mode(None) + , from(0) + , inQuotes(false) {} + + void parseIntoTokens(std::vector const& args, std::vector& tokens) { + const std::string doubleDash = "--"; + for (std::size_t i = 1; i < args.size() && args[i] != doubleDash; ++i) + parseIntoTokens(args[i], tokens); + } + + void parseIntoTokens(std::string const& arg, std::vector& tokens) { + for (std::size_t i = 0; i <= arg.size(); ++i) { + char c = arg[i]; + if (c == '"') + inQuotes = !inQuotes; + mode = handleMode(i, c, arg, tokens); + } + } + Mode handleMode(std::size_t i, char c, std::string const& arg, std::vector& tokens) { + switch (mode) { + case None: + return handleNone(i, c); + case MaybeShortOpt: + return handleMaybeShortOpt(i, c); + case ShortOpt: + case LongOpt: + case SlashOpt: + return handleOpt(i, c, arg, tokens); + case Positional: + return handlePositional(i, c, arg, tokens); + default: + throw std::logic_error("Unknown mode"); + } + } + + Mode handleNone(std::size_t i, char c) { + if (inQuotes) { + from = i; + return Positional; + } + switch (c) { + case '-': + return MaybeShortOpt; +#ifdef CLARA_PLATFORM_WINDOWS + case '/': + from = i + 1; + return SlashOpt; +#endif + default: + from = i; + return Positional; + } + } + Mode handleMaybeShortOpt(std::size_t i, char c) { + switch (c) { + case '-': + from = i + 1; + return LongOpt; + default: + from = i; + return ShortOpt; + } + } + Mode handleOpt(std::size_t i, char c, std::string const& arg, std::vector& tokens) { + if (std::string(":=\0", 3).find(c) == std::string::npos) + return mode; + + std::string optName = arg.substr(from, i - from); + if (mode == ShortOpt) + for (std::size_t j = 0; j < optName.size(); ++j) + tokens.push_back(Token(Token::ShortOpt, optName.substr(j, 1))); + else if (mode == SlashOpt && optName.size() == 1) + tokens.push_back(Token(Token::ShortOpt, optName)); + else + tokens.push_back(Token(Token::LongOpt, optName)); + return None; + } + Mode handlePositional(std::size_t i, char c, std::string const& arg, std::vector& tokens) { + if (inQuotes || std::string("\0", 1).find(c) == std::string::npos) + return mode; + + std::string data = arg.substr(from, i - from); + tokens.push_back(Token(Token::Positional, data)); + return None; + } +}; + +template +struct CommonArgProperties { + CommonArgProperties() {} + CommonArgProperties(Detail::BoundArgFunction const& _boundField) + : boundField(_boundField) {} + + Detail::BoundArgFunction boundField; + std::string description; + std::string detail; + std::string placeholder; // Only value if boundField takes an arg + + bool takesArg() const { + return !placeholder.empty(); + } + void validate() const { + if (!boundField.isSet()) + throw std::logic_error("option not bound"); + } +}; +struct OptionArgProperties { + std::vector shortNames; + std::string longName; + + bool hasShortName(std::string const& shortName) const { + return std::find(shortNames.begin(), shortNames.end(), shortName) != shortNames.end(); + } + bool hasLongName(std::string const& _longName) const { + return _longName == longName; + } +}; +struct PositionalArgProperties { + PositionalArgProperties() + : position(-1) {} + int position; // -1 means non-positional (floating) + + bool isFixedPositional() const { + return position != -1; + } +}; + +template +class CommandLine { + + struct Arg : CommonArgProperties, OptionArgProperties, PositionalArgProperties { + Arg() {} + Arg(Detail::BoundArgFunction const& _boundField) + : CommonArgProperties(_boundField) {} + + using CommonArgProperties::placeholder; // !TBD + + std::string dbgName() const { + if (!longName.empty()) + return "--" + longName; + if (!shortNames.empty()) + return "-" + shortNames[0]; + return "positional args"; + } + std::string commands() const { + std::ostringstream oss; + bool first = true; + std::vector::const_iterator it = shortNames.begin(), itEnd = shortNames.end(); + for (; it != itEnd; ++it) { + if (first) + first = false; + else + oss << ", "; + oss << "-" << *it; + } + if (!longName.empty()) { + if (!first) + oss << ", "; + oss << "--" << longName; + } + if (!placeholder.empty()) + oss << " <" << placeholder << ">"; + return oss.str(); + } + }; + + typedef CLARA_AUTO_PTR(Arg) ArgAutoPtr; + + friend void addOptName(Arg& arg, std::string const& optName) { + if (optName.empty()) + return; + if (Detail::startsWith(optName, "--")) { + if (!arg.longName.empty()) + throw std::logic_error("Only one long opt may be specified. '" + + arg.longName + + "' already specified, now attempting to add '" + + optName + "'"); + arg.longName = optName.substr(2); + } else if (Detail::startsWith(optName, "-")) + arg.shortNames.push_back(optName.substr(1)); + else + throw std::logic_error("option must begin with - or --. Option was: '" + optName + "'"); + } + friend void setPositionalArg(Arg& arg, int position) { + arg.position = position; + } + + class ArgBuilder { + public: + ArgBuilder(Arg* arg) + : m_arg(arg) {} + + // Bind a non-boolean data member (requires placeholder string) + template + void bind(M C::*field, std::string const& placeholder) { + m_arg->boundField = new Detail::BoundDataMember(field); + m_arg->placeholder = placeholder; + } + // Bind a boolean data member (no placeholder required) + template + void bind(bool C::*field) { + m_arg->boundField = new Detail::BoundDataMember(field); + } + + // Bind a method taking a single, non-boolean argument (requires a placeholder string) + template + void bind(void (C::*unaryMethod)(M), std::string const& placeholder) { + m_arg->boundField = new Detail::BoundUnaryMethod(unaryMethod); + m_arg->placeholder = placeholder; + } + + // Bind a method taking a single, boolean argument (no placeholder string required) + template + void bind(void (C::*unaryMethod)(bool)) { + m_arg->boundField = new Detail::BoundUnaryMethod(unaryMethod); + } + + // Bind a method that takes no arguments (will be called if opt is present) + template + void bind(void (C::*nullaryMethod)()) { + m_arg->boundField = new Detail::BoundNullaryMethod(nullaryMethod); + } + + // Bind a free function taking a single argument - the object to operate on (no placeholder string required) + template + void bind(void (*unaryFunction)(C&)) { + m_arg->boundField = new Detail::BoundUnaryFunction(unaryFunction); + } + + // Bind a free function taking a single argument - the object to operate on (requires a placeholder string) + template + void bind(void (*binaryFunction)(C&, T), std::string const& placeholder) { + m_arg->boundField = new Detail::BoundBinaryFunction(binaryFunction); + m_arg->placeholder = placeholder; + } + + ArgBuilder& describe(std::string const& description) { + m_arg->description = description; + return *this; + } + ArgBuilder& detail(std::string const& detail) { + m_arg->detail = detail; + return *this; + } + + protected: + Arg* m_arg; + }; + + class OptBuilder : public ArgBuilder { + public: + OptBuilder(Arg* arg) + : ArgBuilder(arg) {} + OptBuilder(OptBuilder& other) + : ArgBuilder(other) {} + + OptBuilder& operator[](std::string const& optName) { + addOptName(*ArgBuilder::m_arg, optName); + return *this; + } + }; + +public: + CommandLine() + : m_boundProcessName(new Detail::NullBinder()) + , m_highestSpecifiedArgPosition(0) + , m_throwOnUnrecognisedTokens(false) {} + CommandLine(CommandLine const& other) + : m_boundProcessName(other.m_boundProcessName) + , m_options(other.m_options) + , m_positionalArgs(other.m_positionalArgs) + , m_highestSpecifiedArgPosition(other.m_highestSpecifiedArgPosition) + , m_throwOnUnrecognisedTokens(other.m_throwOnUnrecognisedTokens) { + if (other.m_floatingArg.get()) + m_floatingArg.reset(new Arg(*other.m_floatingArg)); + } + + CommandLine& setThrowOnUnrecognisedTokens(bool shouldThrow = true) { + m_throwOnUnrecognisedTokens = shouldThrow; + return *this; + } + + OptBuilder operator[](std::string const& optName) { + m_options.push_back(Arg()); + addOptName(m_options.back(), optName); + OptBuilder builder(&m_options.back()); + return builder; + } + + ArgBuilder operator[](int position) { + m_positionalArgs.insert(std::make_pair(position, Arg())); + if (position > m_highestSpecifiedArgPosition) + m_highestSpecifiedArgPosition = position; + setPositionalArg(m_positionalArgs[position], position); + ArgBuilder builder(&m_positionalArgs[position]); + return builder; + } + + // Invoke this with the _ instance + ArgBuilder operator[](UnpositionalTag) { + if (m_floatingArg.get()) + throw std::logic_error("Only one unpositional argument can be added"); + m_floatingArg.reset(new Arg()); + ArgBuilder builder(m_floatingArg.get()); + return builder; + } + + template + void bindProcessName(M C::*field) { + m_boundProcessName = new Detail::BoundDataMember(field); + } + template + void bindProcessName(void (C::*_unaryMethod)(M)) { + m_boundProcessName = new Detail::BoundUnaryMethod(_unaryMethod); + } + + void optUsage(std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth) const { + typename std::vector::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it; + std::size_t maxWidth = 0; + for (it = itBegin; it != itEnd; ++it) + maxWidth = (std::max)(maxWidth, it->commands().size()); + + for (it = itBegin; it != itEnd; ++it) { + Detail::Text usage(it->commands(), Detail::TextAttributes() + .setWidth(maxWidth + indent) + .setIndent(indent)); + Detail::Text desc(it->description, Detail::TextAttributes() + .setWidth(width - maxWidth - 3)); + + for (std::size_t i = 0; i < (std::max)(usage.size(), desc.size()); ++i) { + std::string usageCol = i < usage.size() ? usage[i] : ""; + os << usageCol; + + if (i < desc.size() && !desc[i].empty()) + os << std::string(indent + 2 + maxWidth - usageCol.size(), ' ') + << desc[i]; + os << "\n"; + } + } + } + std::string optUsage() const { + std::ostringstream oss; + optUsage(oss); + return oss.str(); + } + + void argSynopsis(std::ostream& os) const { + for (int i = 1; i <= m_highestSpecifiedArgPosition; ++i) { + if (i > 1) + os << " "; + typename std::map::const_iterator it = m_positionalArgs.find(i); + if (it != m_positionalArgs.end()) + os << "<" << it->second.placeholder << ">"; + else if (m_floatingArg.get()) + os << "<" << m_floatingArg->placeholder << ">"; + else + throw std::logic_error("non consecutive positional arguments with no floating args"); + } + // !TBD No indication of mandatory args + if (m_floatingArg.get()) { + if (m_highestSpecifiedArgPosition > 1) + os << " "; + os << "[<" << m_floatingArg->placeholder << "> ...]"; + } + } + std::string argSynopsis() const { + std::ostringstream oss; + argSynopsis(oss); + return oss.str(); + } + + void usage(std::ostream& os, std::string const& procName) const { + validate(); + os << "usage:\n " << procName << " "; + argSynopsis(os); + if (!m_options.empty()) { + os << " [options]\n\nwhere options are: \n"; + optUsage(os, 2); + } + os << "\n"; + } + std::string usage(std::string const& procName) const { + std::ostringstream oss; + usage(oss, procName); + return oss.str(); + } + + ConfigT parse(std::vector const& args) const { + ConfigT config; + parseInto(args, config); + return config; + } + + std::vector parseInto(std::vector const& args, ConfigT& config) const { + std::string processName = args[0]; + std::size_t lastSlash = processName.find_last_of("/\\"); + if (lastSlash != std::string::npos) + processName = processName.substr(lastSlash + 1); + m_boundProcessName.set(config, processName); + std::vector tokens; + Parser parser; + parser.parseIntoTokens(args, tokens); + return populate(tokens, config); + } + + std::vector populate(std::vector const& tokens, ConfigT& config) const { + validate(); + std::vector unusedTokens = populateOptions(tokens, config); + unusedTokens = populateFixedArgs(unusedTokens, config); + unusedTokens = populateFloatingArgs(unusedTokens, config); + return unusedTokens; + } + + std::vector populateOptions(std::vector const& tokens, ConfigT& config) const { + std::vector unusedTokens; + std::vector errors; + for (std::size_t i = 0; i < tokens.size(); ++i) { + Parser::Token const& token = tokens[i]; + typename std::vector::const_iterator it = m_options.begin(), itEnd = m_options.end(); + for (; it != itEnd; ++it) { + Arg const& arg = *it; + + try { + if ((token.type == Parser::Token::ShortOpt && arg.hasShortName(token.data)) || (token.type == Parser::Token::LongOpt && arg.hasLongName(token.data))) { + if (arg.takesArg()) { + if (i == tokens.size() - 1 || tokens[i + 1].type != Parser::Token::Positional) + errors.push_back("Expected argument to option: " + token.data); + else + arg.boundField.set(config, tokens[++i].data); + } else { + arg.boundField.set(config, "true"); + } + break; + } + } catch (std::exception& ex) { + errors.push_back(std::string(ex.what()) + "\n- while parsing: (" + arg.commands() + ")"); + } + } + if (it == itEnd) { + if (token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens) + unusedTokens.push_back(token); + else if (errors.empty() && m_throwOnUnrecognisedTokens) + errors.push_back("unrecognised option: " + token.data); + } + } + if (!errors.empty()) { + std::ostringstream oss; + for (std::vector::const_iterator it = errors.begin(), itEnd = errors.end(); + it != itEnd; + ++it) { + if (it != errors.begin()) + oss << "\n"; + oss << *it; + } + throw std::runtime_error(oss.str()); + } + return unusedTokens; + } + std::vector populateFixedArgs(std::vector const& tokens, ConfigT& config) const { + std::vector unusedTokens; + int position = 1; + for (std::size_t i = 0; i < tokens.size(); ++i) { + Parser::Token const& token = tokens[i]; + typename std::map::const_iterator it = m_positionalArgs.find(position); + if (it != m_positionalArgs.end()) + it->second.boundField.set(config, token.data); + else + unusedTokens.push_back(token); + if (token.type == Parser::Token::Positional) + position++; + } + return unusedTokens; + } + std::vector populateFloatingArgs(std::vector const& tokens, ConfigT& config) const { + if (!m_floatingArg.get()) + return tokens; + std::vector unusedTokens; + for (std::size_t i = 0; i < tokens.size(); ++i) { + Parser::Token const& token = tokens[i]; + if (token.type == Parser::Token::Positional) + m_floatingArg->boundField.set(config, token.data); + else + unusedTokens.push_back(token); + } + return unusedTokens; + } + + void validate() const { + if (m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get()) + throw std::logic_error("No options or arguments specified"); + + for (typename std::vector::const_iterator it = m_options.begin(), + itEnd = m_options.end(); + it != itEnd; ++it) + it->validate(); + } + +private: + Detail::BoundArgFunction m_boundProcessName; + std::vector m_options; + std::map m_positionalArgs; + ArgAutoPtr m_floatingArg; + int m_highestSpecifiedArgPosition; + bool m_throwOnUnrecognisedTokens; +}; + +} // end namespace Clara + +STITCH_CLARA_CLOSE_NAMESPACE +#undef STITCH_CLARA_OPEN_NAMESPACE +#undef STITCH_CLARA_CLOSE_NAMESPACE + +#endif // TWOBLUECUBES_CLARA_H_INCLUDED +#undef STITCH_CLARA_OPEN_NAMESPACE + +// Restore Clara's value for console width, if present +#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#endif + +#include + +namespace Catch { + +inline void abortAfterFirst(ConfigData& config) { config.abortAfter = 1; } +inline void abortAfterX(ConfigData& config, int x) { + if (x < 1) + throw std::runtime_error("Value after -x or --abortAfter must be greater than zero"); + config.abortAfter = x; +} +inline void addTestOrTags(ConfigData& config, std::string const& _testSpec) { config.testsOrTags.push_back(_testSpec); } +inline void addReporterName(ConfigData& config, std::string const& _reporterName) { config.reporterNames.push_back(_reporterName); } + +inline void addWarning(ConfigData& config, std::string const& _warning) { + if (_warning == "NoAssertions") + config.warnings = static_cast(config.warnings | WarnAbout::NoAssertions); + else + throw std::runtime_error("Unrecognised warning: '" + _warning + "'"); +} +inline void setOrder(ConfigData& config, std::string const& order) { + if (startsWith("declared", order)) + config.runOrder = RunTests::InDeclarationOrder; + else if (startsWith("lexical", order)) + config.runOrder = RunTests::InLexicographicalOrder; + else if (startsWith("random", order)) + config.runOrder = RunTests::InRandomOrder; + else + throw std::runtime_error("Unrecognised ordering: '" + order + "'"); +} +inline void setRngSeed(ConfigData& config, std::string const& seed) { + if (seed == "time") { + config.rngSeed = static_cast(std::time(0)); + } else { + std::stringstream ss; + ss << seed; + ss >> config.rngSeed; + if (ss.fail()) + throw std::runtime_error("Argment to --rng-seed should be the word 'time' or a number"); + } +} +inline void setVerbosity(ConfigData& config, int level) { + // !TBD: accept strings? + config.verbosity = static_cast(level); +} +inline void setShowDurations(ConfigData& config, bool _showDurations) { + config.showDurations = _showDurations + ? ShowDurations::Always + : ShowDurations::Never; +} +inline void setUseColour(ConfigData& config, std::string const& value) { + std::string mode = toLower(value); + + if (mode == "yes") + config.useColour = UseColour::Yes; + else if (mode == "no") + config.useColour = UseColour::No; + else if (mode == "auto") + config.useColour = UseColour::Auto; + else + throw std::runtime_error("colour mode must be one of: auto, yes or no"); +} +inline void forceColour(ConfigData& config) { + config.useColour = UseColour::Yes; +} +inline void loadTestNamesFromFile(ConfigData& config, std::string const& _filename) { + std::ifstream f(_filename.c_str()); + if (!f.is_open()) + throw std::domain_error("Unable to load input file: " + _filename); + + std::string line; + while (std::getline(f, line)) { + line = trim(line); + if (!line.empty() && !startsWith(line, "#")) + addTestOrTags(config, "\"" + line + "\","); + } +} + +inline Clara::CommandLine makeCommandLineParser() { + + using namespace Clara; + CommandLine cli; + + cli.bindProcessName(&ConfigData::processName); + + cli["-?"]["-h"]["--help"] + .describe("display usage information") + .bind(&ConfigData::showHelp); + + cli["-l"]["--list-tests"] + .describe("list all/matching test cases") + .bind(&ConfigData::listTests); + + cli["-t"]["--list-tags"] + .describe("list all/matching tags") + .bind(&ConfigData::listTags); + + cli["-s"]["--success"] + .describe("include successful tests in output") + .bind(&ConfigData::showSuccessfulTests); + + cli["-b"]["--break"] + .describe("break into debugger on failure") + .bind(&ConfigData::shouldDebugBreak); + + cli["-e"]["--nothrow"] + .describe("skip exception tests") + .bind(&ConfigData::noThrow); + + cli["-i"]["--invisibles"] + .describe("show invisibles (tabs, newlines)") + .bind(&ConfigData::showInvisibles); + + cli["-o"]["--out"] + .describe("output filename") + .bind(&ConfigData::outputFilename, "filename"); + + cli["-r"]["--reporter"] + // .placeholder( "name[:filename]" ) + .describe("reporter to use (defaults to console)") + .bind(&addReporterName, "name"); + + cli["-n"]["--name"] + .describe("suite name") + .bind(&ConfigData::name, "name"); + + cli["-a"]["--abort"] + .describe("abort at first failure") + .bind(&abortAfterFirst); + + cli["-x"]["--abortx"] + .describe("abort after x failures") + .bind(&abortAfterX, "no. failures"); + + cli["-w"]["--warn"] + .describe("enable warnings") + .bind(&addWarning, "warning name"); + + // - needs updating if reinstated + // cli.into( &setVerbosity ) + // .describe( "level of verbosity (0=no output)" ) + // .shortOpt( "v") + // .longOpt( "verbosity" ) + // .placeholder( "level" ); + + cli[_] + .describe("which test or tests to use") + .bind(&addTestOrTags, "test name, pattern or tags"); + + cli["-d"]["--durations"] + .describe("show test durations") + .bind(&setShowDurations, "yes|no"); + + cli["-f"]["--input-file"] + .describe("load test names to run from a file") + .bind(&loadTestNamesFromFile, "filename"); + + cli["-#"]["--filenames-as-tags"] + .describe("adds a tag for the filename") + .bind(&ConfigData::filenamesAsTags); + + // Less common commands which don't have a short form + cli["--list-test-names-only"] + .describe("list all/matching test cases names only") + .bind(&ConfigData::listTestNamesOnly); + + cli["--list-reporters"] + .describe("list all reporters") + .bind(&ConfigData::listReporters); + + cli["--order"] + .describe("test case order (defaults to decl)") + .bind(&setOrder, "decl|lex|rand"); + + cli["--rng-seed"] + .describe("set a specific seed for random numbers") + .bind(&setRngSeed, "'time'|number"); + + cli["--force-colour"] + .describe("force colourised output (deprecated)") + .bind(&forceColour); + + cli["--use-colour"] + .describe("should output be colourised") + .bind(&setUseColour, "yes|no"); + + return cli; +} + +} // end namespace Catch + +// #included from: internal/catch_list.hpp +#define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED + +// #included from: catch_text.h +#define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED + +#define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH + +#define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch +// #included from: ../external/tbc_text_format.h +// Only use header guard if we are not using an outer namespace +#ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE +#ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED +#ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED +#define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED +#endif +#else +#define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED +#endif +#endif +#ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED +#include +#include +#include + +// Use optional outer namespace +#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE +namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE { +#endif + +namespace Tbc { + +#ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH + const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; +#else +const unsigned int consoleWidth = 80; +#endif + + struct TextAttributes { + TextAttributes() + : initialIndent(std::string::npos) + , indent(0) + , width(consoleWidth - 1) + , tabChar('\t') {} + + TextAttributes& setInitialIndent(std::size_t _value) { + initialIndent = _value; + return *this; + } + TextAttributes& setIndent(std::size_t _value) { + indent = _value; + return *this; + } + TextAttributes& setWidth(std::size_t _value) { + width = _value; + return *this; + } + TextAttributes& setTabChar(char _value) { + tabChar = _value; + return *this; + } + + std::size_t initialIndent; // indent of first line, or npos + std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos + std::size_t width; // maximum width of text, including indent. Longer text will wrap + char tabChar; // If this char is seen the indent is changed to current pos + }; + + class Text { + public: + Text(std::string const& _str, TextAttributes const& _attr = TextAttributes()) + : attr(_attr) { + std::string wrappableChars = " [({.,/|\\-"; + std::size_t indent = _attr.initialIndent != std::string::npos + ? _attr.initialIndent + : _attr.indent; + std::string remainder = _str; + + while (!remainder.empty()) { + if (lines.size() >= 1000) { + lines.push_back("... message truncated due to excessive size"); + return; + } + std::size_t tabPos = std::string::npos; + std::size_t width = (std::min)(remainder.size(), _attr.width - indent); + std::size_t pos = remainder.find_first_of('\n'); + if (pos <= width) { + width = pos; + } + pos = remainder.find_last_of(_attr.tabChar, width); + if (pos != std::string::npos) { + tabPos = pos; + if (remainder[width] == '\n') + width--; + remainder = remainder.substr(0, tabPos) + remainder.substr(tabPos + 1); + } + + if (width == remainder.size()) { + spliceLine(indent, remainder, width); + } else if (remainder[width] == '\n') { + spliceLine(indent, remainder, width); + if (width <= 1 || remainder.size() != 1) + remainder = remainder.substr(1); + indent = _attr.indent; + } else { + pos = remainder.find_last_of(wrappableChars, width); + if (pos != std::string::npos && pos > 0) { + spliceLine(indent, remainder, pos); + if (remainder[0] == ' ') + remainder = remainder.substr(1); + } else { + spliceLine(indent, remainder, width - 1); + lines.back() += "-"; + } + if (lines.size() == 1) + indent = _attr.indent; + if (tabPos != std::string::npos) + indent += tabPos; + } + } + } + + void spliceLine(std::size_t _indent, std::string& _remainder, std::size_t _pos) { + lines.push_back(std::string(_indent, ' ') + _remainder.substr(0, _pos)); + _remainder = _remainder.substr(_pos); + } + + typedef std::vector::const_iterator const_iterator; + + const_iterator begin() const { return lines.begin(); } + const_iterator end() const { return lines.end(); } + std::string const& last() const { return lines.back(); } + std::size_t size() const { return lines.size(); } + std::string const& operator[](std::size_t _index) const { return lines[_index]; } + std::string toString() const { + std::ostringstream oss; + oss << *this; + return oss.str(); + } + + inline friend std::ostream& operator<<(std::ostream& _stream, Text const& _text) { + for (Text::const_iterator it = _text.begin(), itEnd = _text.end(); + it != itEnd; ++it) { + if (it != _text.begin()) + _stream << "\n"; + _stream << *it; + } + return _stream; + } + + private: + std::string str; + TextAttributes attr; + std::vector lines; + }; + +} // end namespace Tbc + +#ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE +} // end outer namespace +#endif + +#endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED +#undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE + +namespace Catch { +using Tbc::Text; +using Tbc::TextAttributes; +} + +// #included from: catch_console_colour.hpp +#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED + +namespace Catch { + +struct Colour { + enum Code { + None = 0, + + White, + Red, + Green, + Blue, + Cyan, + Yellow, + Grey, + + Bright = 0x10, + + BrightRed = Bright | Red, + BrightGreen = Bright | Green, + LightGrey = Bright | Grey, + BrightWhite = Bright | White, + + // By intention + FileName = LightGrey, + Warning = Yellow, + ResultError = BrightRed, + ResultSuccess = BrightGreen, + ResultExpectedFailure = Warning, + + Error = BrightRed, + Success = Green, + + OriginalExpression = Cyan, + ReconstructedExpression = Yellow, + + SecondaryText = LightGrey, + Headers = White + }; + + // Use constructed object for RAII guard + Colour(Code _colourCode); + Colour(Colour const& other); + ~Colour(); + + // Use static method for one-shot changes + static void use(Code _colourCode); + +private: + bool m_moved; +}; + +inline std::ostream& operator<<(std::ostream& os, Colour const&) { return os; } + +} // end namespace Catch + +// #included from: catch_interfaces_reporter.h +#define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED + +#include +#include +#include +#include + +namespace Catch { +struct ReporterConfig { + explicit ReporterConfig(Ptr const& _fullConfig) + : m_stream(&_fullConfig->stream()) + , m_fullConfig(_fullConfig) {} + + ReporterConfig(Ptr const& _fullConfig, std::ostream& _stream) + : m_stream(&_stream) + , m_fullConfig(_fullConfig) {} + + std::ostream& stream() const { return *m_stream; } + Ptr fullConfig() const { return m_fullConfig; } + +private: + std::ostream* m_stream; + Ptr m_fullConfig; +}; + +struct ReporterPreferences { + ReporterPreferences() + : shouldRedirectStdOut(false) {} + + bool shouldRedirectStdOut; +}; + +template +struct LazyStat : Option { + LazyStat() + : used(false) {} + LazyStat& operator=(T const& _value) { + Option::operator=(_value); + used = false; + return *this; + } + void reset() { + Option::reset(); + used = false; + } + bool used; +}; + +struct TestRunInfo { + TestRunInfo(std::string const& _name) + : name(_name) {} + std::string name; +}; +struct GroupInfo { + GroupInfo(std::string const& _name, + std::size_t _groupIndex, + std::size_t _groupsCount) + : name(_name) + , groupIndex(_groupIndex) + , groupsCounts(_groupsCount) {} + + std::string name; + std::size_t groupIndex; + std::size_t groupsCounts; +}; + +struct AssertionStats { + AssertionStats(AssertionResult const& _assertionResult, + std::vector const& _infoMessages, + Totals const& _totals) + : assertionResult(_assertionResult) + , infoMessages(_infoMessages) + , totals(_totals) { + if (assertionResult.hasMessage()) { + // Copy message into messages list. + // !TBD This should have been done earlier, somewhere + MessageBuilder builder(assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType()); + builder << assertionResult.getMessage(); + builder.m_info.message = builder.m_stream.str(); + + infoMessages.push_back(builder.m_info); + } + } + virtual ~AssertionStats(); + +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + AssertionStats(AssertionStats const&) = default; + AssertionStats(AssertionStats&&) = default; + AssertionStats& operator=(AssertionStats const&) = default; + AssertionStats& operator=(AssertionStats&&) = default; +#endif + + AssertionResult assertionResult; + std::vector infoMessages; + Totals totals; +}; + +struct SectionStats { + SectionStats(SectionInfo const& _sectionInfo, + Counts const& _assertions, + double _durationInSeconds, + bool _missingAssertions) + : sectionInfo(_sectionInfo) + , assertions(_assertions) + , durationInSeconds(_durationInSeconds) + , missingAssertions(_missingAssertions) {} + virtual ~SectionStats(); +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + SectionStats(SectionStats const&) = default; + SectionStats(SectionStats&&) = default; + SectionStats& operator=(SectionStats const&) = default; + SectionStats& operator=(SectionStats&&) = default; +#endif + + SectionInfo sectionInfo; + Counts assertions; + double durationInSeconds; + bool missingAssertions; +}; + +struct TestCaseStats { + TestCaseStats(TestCaseInfo const& _testInfo, + Totals const& _totals, + std::string const& _stdOut, + std::string const& _stdErr, + bool _aborting) + : testInfo(_testInfo) + , totals(_totals) + , stdOut(_stdOut) + , stdErr(_stdErr) + , aborting(_aborting) {} + virtual ~TestCaseStats(); + +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + TestCaseStats(TestCaseStats const&) = default; + TestCaseStats(TestCaseStats&&) = default; + TestCaseStats& operator=(TestCaseStats const&) = default; + TestCaseStats& operator=(TestCaseStats&&) = default; +#endif + + TestCaseInfo testInfo; + Totals totals; + std::string stdOut; + std::string stdErr; + bool aborting; +}; + +struct TestGroupStats { + TestGroupStats(GroupInfo const& _groupInfo, + Totals const& _totals, + bool _aborting) + : groupInfo(_groupInfo) + , totals(_totals) + , aborting(_aborting) {} + TestGroupStats(GroupInfo const& _groupInfo) + : groupInfo(_groupInfo) + , aborting(false) {} + virtual ~TestGroupStats(); + +#ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS + TestGroupStats(TestGroupStats const&) = default; + TestGroupStats(TestGroupStats&&) = default; + TestGroupStats& operator=(TestGroupStats const&) = default; + TestGroupStats& operator=(TestGroupStats&&) = default; +#endif + + GroupInfo groupInfo; + Totals totals; + bool aborting; +}; + +struct TestRunStats { + TestRunStats(TestRunInfo const& _runInfo, + Totals const& _totals, + bool _aborting) + : runInfo(_runInfo) + , totals(_totals) + , aborting(_aborting) {} + virtual ~TestRunStats(); + +#ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS + TestRunStats(TestRunStats const& _other) + : runInfo(_other.runInfo) + , totals(_other.totals) + , aborting(_other.aborting) {} +#else + TestRunStats(TestRunStats const&) = default; + TestRunStats(TestRunStats&&) = default; + TestRunStats& operator=(TestRunStats const&) = default; + TestRunStats& operator=(TestRunStats&&) = default; +#endif + + TestRunInfo runInfo; + Totals totals; + bool aborting; +}; + +class MultipleReporters; + +struct IStreamingReporter : IShared { + virtual ~IStreamingReporter(); + + // Implementing class must also provide the following static method: + // static std::string getDescription(); + + virtual ReporterPreferences getPreferences() const = 0; + + virtual void noMatchingTestCases(std::string const& spec) = 0; + + virtual void testRunStarting(TestRunInfo const& testRunInfo) = 0; + virtual void testGroupStarting(GroupInfo const& groupInfo) = 0; + + virtual void testCaseStarting(TestCaseInfo const& testInfo) = 0; + virtual void sectionStarting(SectionInfo const& sectionInfo) = 0; + + virtual void assertionStarting(AssertionInfo const& assertionInfo) = 0; + + // The return value indicates if the messages buffer should be cleared: + virtual bool assertionEnded(AssertionStats const& assertionStats) = 0; + + virtual void sectionEnded(SectionStats const& sectionStats) = 0; + virtual void testCaseEnded(TestCaseStats const& testCaseStats) = 0; + virtual void testGroupEnded(TestGroupStats const& testGroupStats) = 0; + virtual void testRunEnded(TestRunStats const& testRunStats) = 0; + + virtual void skipTest(TestCaseInfo const& testInfo) = 0; + + virtual MultipleReporters* tryAsMulti() { return CATCH_NULL; } +}; + +struct IReporterFactory : IShared { + virtual ~IReporterFactory(); + virtual IStreamingReporter* create(ReporterConfig const& config) const = 0; + virtual std::string getDescription() const = 0; +}; + +struct IReporterRegistry { + typedef std::map> FactoryMap; + typedef std::vector> Listeners; + + virtual ~IReporterRegistry(); + virtual IStreamingReporter* create(std::string const& name, Ptr const& config) const = 0; + virtual FactoryMap const& getFactories() const = 0; + virtual Listeners const& getListeners() const = 0; +}; + +Ptr addReporter(Ptr const& existingReporter, Ptr const& additionalReporter); +} + +#include +#include + +namespace Catch { + +inline std::size_t listTests(Config const& config) { + + TestSpec testSpec = config.testSpec(); + if (config.testSpec().hasFilters()) + Catch::cout() << "Matching test cases:\n"; + else { + Catch::cout() << "All available test cases:\n"; + testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("*").testSpec(); + } + + std::size_t matchedTests = 0; + TextAttributes nameAttr, tagsAttr; + nameAttr.setInitialIndent(2).setIndent(4); + tagsAttr.setIndent(6); + + std::vector matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config); + for (std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); + it != itEnd; + ++it) { + matchedTests++; + TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); + Colour::Code colour = testCaseInfo.isHidden() + ? Colour::SecondaryText + : Colour::None; + Colour colourGuard(colour); + + Catch::cout() << Text(testCaseInfo.name, nameAttr) << std::endl; + if (!testCaseInfo.tags.empty()) + Catch::cout() << Text(testCaseInfo.tagsAsString, tagsAttr) << std::endl; + } + + if (!config.testSpec().hasFilters()) + Catch::cout() << pluralise(matchedTests, "test case") << "\n" << std::endl; + else + Catch::cout() << pluralise(matchedTests, "matching test case") << "\n" << std::endl; + return matchedTests; +} + +inline std::size_t listTestsNamesOnly(Config const& config) { + TestSpec testSpec = config.testSpec(); + if (!config.testSpec().hasFilters()) + testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("*").testSpec(); + std::size_t matchedTests = 0; + std::vector matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config); + for (std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); + it != itEnd; + ++it) { + matchedTests++; + TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); + Catch::cout() << testCaseInfo.name << std::endl; + } + return matchedTests; +} + +struct TagInfo { + TagInfo() + : count(0) {} + void add(std::string const& spelling) { + ++count; + spellings.insert(spelling); + } + std::string all() const { + std::string out; + for (std::set::const_iterator it = spellings.begin(), itEnd = spellings.end(); + it != itEnd; + ++it) + out += "[" + *it + "]"; + return out; + } + std::set spellings; + std::size_t count; +}; + +inline std::size_t listTags(Config const& config) { + TestSpec testSpec = config.testSpec(); + if (config.testSpec().hasFilters()) + Catch::cout() << "Tags for matching test cases:\n"; + else { + Catch::cout() << "All available tags:\n"; + testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("*").testSpec(); + } + + std::map tagCounts; + + std::vector matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config); + for (std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); + it != itEnd; + ++it) { + for (std::set::const_iterator tagIt = it->getTestCaseInfo().tags.begin(), + tagItEnd = it->getTestCaseInfo().tags.end(); + tagIt != tagItEnd; + ++tagIt) { + std::string tagName = *tagIt; + std::string lcaseTagName = toLower(tagName); + std::map::iterator countIt = tagCounts.find(lcaseTagName); + if (countIt == tagCounts.end()) + countIt = tagCounts.insert(std::make_pair(lcaseTagName, TagInfo())).first; + countIt->second.add(tagName); + } + } + + for (std::map::const_iterator countIt = tagCounts.begin(), + countItEnd = tagCounts.end(); + countIt != countItEnd; + ++countIt) { + std::ostringstream oss; + oss << " " << std::setw(2) << countIt->second.count << " "; + Text wrapper(countIt->second.all(), TextAttributes() + .setInitialIndent(0) + .setIndent(oss.str().size()) + .setWidth(CATCH_CONFIG_CONSOLE_WIDTH - 10)); + Catch::cout() << oss.str() << wrapper << "\n"; + } + Catch::cout() << pluralise(tagCounts.size(), "tag") << "\n" << std::endl; + return tagCounts.size(); +} + +inline std::size_t listReporters(Config const& /*config*/) { + Catch::cout() << "Available reporters:\n"; + IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); + IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it; + std::size_t maxNameLen = 0; + for (it = itBegin; it != itEnd; ++it) + maxNameLen = (std::max)(maxNameLen, it->first.size()); + + for (it = itBegin; it != itEnd; ++it) { + Text wrapper(it->second->getDescription(), TextAttributes() + .setInitialIndent(0) + .setIndent(7 + maxNameLen) + .setWidth(CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8)); + Catch::cout() << " " + << it->first + << ":" + << std::string(maxNameLen - it->first.size() + 2, ' ') + << wrapper << "\n"; + } + Catch::cout() << std::endl; + return factories.size(); +} + +inline Option list(Config const& config) { + Option listedCount; + if (config.listTests()) + listedCount = listedCount.valueOr(0) + listTests(config); + if (config.listTestNamesOnly()) + listedCount = listedCount.valueOr(0) + listTestsNamesOnly(config); + if (config.listTags()) + listedCount = listedCount.valueOr(0) + listTags(config); + if (config.listReporters()) + listedCount = listedCount.valueOr(0) + listReporters(config); + return listedCount; +} + +} // end namespace Catch + +// #included from: internal/catch_run_context.hpp +#define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED + +// #included from: catch_test_case_tracker.hpp +#define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED + +#include +#include +#include +#include + +namespace Catch { +namespace TestCaseTracking { + + struct ITracker : SharedImpl<> { + virtual ~ITracker(); + + // static queries + virtual std::string name() const = 0; + + // dynamic queries + virtual bool isComplete() const = 0; // Successfully completed or failed + virtual bool isSuccessfullyCompleted() const = 0; + virtual bool isOpen() const = 0; // Started but not complete + virtual bool hasChildren() const = 0; + + virtual ITracker& parent() = 0; + + // actions + virtual void close() = 0; // Successfully complete + virtual void fail() = 0; + virtual void markAsNeedingAnotherRun() = 0; + + virtual void addChild(Ptr const& child) = 0; + virtual ITracker* findChild(std::string const& name) = 0; + virtual void openChild() = 0; + + // Debug/ checking + virtual bool isSectionTracker() const = 0; + virtual bool isIndexTracker() const = 0; + }; + + class TrackerContext { + + enum RunState { + NotStarted, + Executing, + CompletedCycle + }; + + Ptr m_rootTracker; + ITracker* m_currentTracker; + RunState m_runState; + + public: + static TrackerContext& instance() { + static TrackerContext s_instance; + return s_instance; + } + + TrackerContext() + : m_currentTracker(CATCH_NULL) + , m_runState(NotStarted) {} + + ITracker& startRun(); + + void endRun() { + m_rootTracker.reset(); + m_currentTracker = CATCH_NULL; + m_runState = NotStarted; + } + + void startCycle() { + m_currentTracker = m_rootTracker.get(); + m_runState = Executing; + } + void completeCycle() { + m_runState = CompletedCycle; + } + + bool completedCycle() const { + return m_runState == CompletedCycle; + } + ITracker& currentTracker() { + return *m_currentTracker; + } + void setCurrentTracker(ITracker* tracker) { + m_currentTracker = tracker; + } + }; + + class TrackerBase : public ITracker { + protected: + enum CycleState { + NotStarted, + Executing, + ExecutingChildren, + NeedsAnotherRun, + CompletedSuccessfully, + Failed + }; + class TrackerHasName { + std::string m_name; + + public: + TrackerHasName(std::string const& name) + : m_name(name) {} + bool operator()(Ptr const& tracker) { + return tracker->name() == m_name; + } + }; + typedef std::vector> Children; + std::string m_name; + TrackerContext& m_ctx; + ITracker* m_parent; + Children m_children; + CycleState m_runState; + + public: + TrackerBase(std::string const& name, TrackerContext& ctx, ITracker* parent) + : m_name(name) + , m_ctx(ctx) + , m_parent(parent) + , m_runState(NotStarted) {} + virtual ~TrackerBase(); + + virtual std::string name() const CATCH_OVERRIDE { + return m_name; + } + virtual bool isComplete() const CATCH_OVERRIDE { + return m_runState == CompletedSuccessfully || m_runState == Failed; + } + virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE { + return m_runState == CompletedSuccessfully; + } + virtual bool isOpen() const CATCH_OVERRIDE { + return m_runState != NotStarted && !isComplete(); + } + virtual bool hasChildren() const CATCH_OVERRIDE { + return !m_children.empty(); + } + + virtual void addChild(Ptr const& child) CATCH_OVERRIDE { + m_children.push_back(child); + } + + virtual ITracker* findChild(std::string const& name) CATCH_OVERRIDE { + Children::const_iterator it = std::find_if(m_children.begin(), m_children.end(), TrackerHasName(name)); + return (it != m_children.end()) + ? it->get() + : CATCH_NULL; + } + virtual ITracker& parent() CATCH_OVERRIDE { + assert(m_parent); // Should always be non-null except for root + return *m_parent; + } + + virtual void openChild() CATCH_OVERRIDE { + if (m_runState != ExecutingChildren) { + m_runState = ExecutingChildren; + if (m_parent) + m_parent->openChild(); + } + } + + virtual bool isSectionTracker() const CATCH_OVERRIDE { return false; } + virtual bool isIndexTracker() const CATCH_OVERRIDE { return false; } + + void open() { + m_runState = Executing; + moveToThis(); + if (m_parent) + m_parent->openChild(); + } + + virtual void close() CATCH_OVERRIDE { + + // Close any still open children (e.g. generators) + while (&m_ctx.currentTracker() != this) + m_ctx.currentTracker().close(); + + switch (m_runState) { + case NotStarted: + case CompletedSuccessfully: + case Failed: + throw std::logic_error("Illogical state"); + + case NeedsAnotherRun: + break; + ; + + case Executing: + m_runState = CompletedSuccessfully; + break; + case ExecutingChildren: + if (m_children.empty() || m_children.back()->isComplete()) + m_runState = CompletedSuccessfully; + break; + + default: + throw std::logic_error("Unexpected state"); + } + moveToParent(); + m_ctx.completeCycle(); + } + virtual void fail() CATCH_OVERRIDE { + m_runState = Failed; + if (m_parent) + m_parent->markAsNeedingAnotherRun(); + moveToParent(); + m_ctx.completeCycle(); + } + virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE { + m_runState = NeedsAnotherRun; + } + + private: + void moveToParent() { + assert(m_parent); + m_ctx.setCurrentTracker(m_parent); + } + void moveToThis() { + m_ctx.setCurrentTracker(this); + } + }; + + class SectionTracker : public TrackerBase { + public: + SectionTracker(std::string const& name, TrackerContext& ctx, ITracker* parent) + : TrackerBase(name, ctx, parent) {} + virtual ~SectionTracker(); + + virtual bool isSectionTracker() const CATCH_OVERRIDE { return true; } + + static SectionTracker& acquire(TrackerContext& ctx, std::string const& name) { + SectionTracker* section = CATCH_NULL; + + ITracker& currentTracker = ctx.currentTracker(); + if (ITracker* childTracker = currentTracker.findChild(name)) { + assert(childTracker); + assert(childTracker->isSectionTracker()); + section = static_cast(childTracker); + } else { + section = new SectionTracker(name, ctx, ¤tTracker); + currentTracker.addChild(section); + } + if (!ctx.completedCycle() && !section->isComplete()) { + + section->open(); + } + return *section; + } + }; + + class IndexTracker : public TrackerBase { + int m_size; + int m_index; + + public: + IndexTracker(std::string const& name, TrackerContext& ctx, ITracker* parent, int size) + : TrackerBase(name, ctx, parent) + , m_size(size) + , m_index(-1) {} + virtual ~IndexTracker(); + + virtual bool isIndexTracker() const CATCH_OVERRIDE { return true; } + + static IndexTracker& acquire(TrackerContext& ctx, std::string const& name, int size) { + IndexTracker* tracker = CATCH_NULL; + + ITracker& currentTracker = ctx.currentTracker(); + if (ITracker* childTracker = currentTracker.findChild(name)) { + assert(childTracker); + assert(childTracker->isIndexTracker()); + tracker = static_cast(childTracker); + } else { + tracker = new IndexTracker(name, ctx, ¤tTracker, size); + currentTracker.addChild(tracker); + } + + if (!ctx.completedCycle() && !tracker->isComplete()) { + if (tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun) + tracker->moveNext(); + tracker->open(); + } + + return *tracker; + } + + int index() const { return m_index; } + + void moveNext() { + m_index++; + m_children.clear(); + } + + virtual void close() CATCH_OVERRIDE { + TrackerBase::close(); + if (m_runState == CompletedSuccessfully && m_index < m_size - 1) + m_runState = Executing; + } + }; + + inline ITracker& TrackerContext::startRun() { + m_rootTracker = new SectionTracker("{root}", *this, CATCH_NULL); + m_currentTracker = CATCH_NULL; + m_runState = Executing; + return *m_rootTracker; + } + +} // namespace TestCaseTracking + +using TestCaseTracking::ITracker; +using TestCaseTracking::TrackerContext; +using TestCaseTracking::SectionTracker; +using TestCaseTracking::IndexTracker; + +} // namespace Catch + +// #included from: catch_fatal_condition.hpp +#define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED + +namespace Catch { + +// Report the error condition then exit the process +inline void fatal(std::string const& message, int exitCode) { + IContext& context = Catch::getCurrentContext(); + IResultCapture* resultCapture = context.getResultCapture(); + resultCapture->handleFatalErrorCondition(message); + + if (Catch::alwaysTrue()) // avoids "no return" warnings + exit(exitCode); +} + +} // namespace Catch + +#if defined(CATCH_PLATFORM_WINDOWS) ///////////////////////////////////////// + +namespace Catch { + +struct FatalConditionHandler { + void reset() {} +}; + +} // namespace Catch + +#else // Not Windows - assumed to be POSIX compatible ////////////////////////// + +#include + +namespace Catch { + +struct SignalDefs { + int id; + const char* name; +}; +extern SignalDefs signalDefs[]; +SignalDefs signalDefs[] = { + {SIGINT, "SIGINT - Terminal interrupt signal"}, + {SIGILL, "SIGILL - Illegal instruction signal"}, + {SIGFPE, "SIGFPE - Floating point error signal"}, + {SIGSEGV, "SIGSEGV - Segmentation violation signal"}, + {SIGTERM, "SIGTERM - Termination request signal"}, + {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}}; + +struct FatalConditionHandler { + + static void handleSignal(int sig) { + for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) + if (sig == signalDefs[i].id) + fatal(signalDefs[i].name, -sig); + fatal("", -sig); + } + + FatalConditionHandler() + : m_isSet(true) { + for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) + signal(signalDefs[i].id, handleSignal); + } + ~FatalConditionHandler() { + reset(); + } + void reset() { + if (m_isSet) { + for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) + signal(signalDefs[i].id, SIG_DFL); + m_isSet = false; + } + } + + bool m_isSet; +}; + +} // namespace Catch + +#endif // not Windows + +#include +#include + +namespace Catch { + +class StreamRedirect { + +public: + StreamRedirect(std::ostream& stream, std::string& targetString) + : m_stream(stream) + , m_prevBuf(stream.rdbuf()) + , m_targetString(targetString) { + stream.rdbuf(m_oss.rdbuf()); + } + + ~StreamRedirect() { + m_targetString += m_oss.str(); + m_stream.rdbuf(m_prevBuf); + } + +private: + std::ostream& m_stream; + std::streambuf* m_prevBuf; + std::ostringstream m_oss; + std::string& m_targetString; +}; + +/////////////////////////////////////////////////////////////////////////// + +class RunContext : public IResultCapture, public IRunner { + + RunContext(RunContext const&); + void operator=(RunContext const&); + +public: + explicit RunContext(Ptr const& _config, Ptr const& reporter) + : m_runInfo(_config->name()) + , m_context(getCurrentMutableContext()) + , m_activeTestCase(CATCH_NULL) + , m_config(_config) + , m_reporter(reporter) { + m_context.setRunner(this); + m_context.setConfig(m_config); + m_context.setResultCapture(this); + m_reporter->testRunStarting(m_runInfo); + } + + virtual ~RunContext() { + m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting())); + } + + void testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) { + m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount)); + } + void testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) { + m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting())); + } + + Totals runTest(TestCase const& testCase) { + Totals prevTotals = m_totals; + + std::string redirectedCout; + std::string redirectedCerr; + + TestCaseInfo testInfo = testCase.getTestCaseInfo(); + + m_reporter->testCaseStarting(testInfo); + + m_activeTestCase = &testCase; + + do { + m_trackerContext.startRun(); + do { + m_trackerContext.startCycle(); + m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, testInfo.name); + runCurrentTest(redirectedCout, redirectedCerr); + } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting()); + } + // !TBD: deprecated - this will be replaced by indexed trackers + while (getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting()); + + Totals deltaTotals = m_totals.delta(prevTotals); + if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) { + deltaTotals.assertions.failed++; + deltaTotals.testCases.passed--; + deltaTotals.testCases.failed++; + } + m_totals.testCases += deltaTotals.testCases; + m_reporter->testCaseEnded(TestCaseStats(testInfo, + deltaTotals, + redirectedCout, + redirectedCerr, + aborting())); + + m_activeTestCase = CATCH_NULL; + m_testCaseTracker = CATCH_NULL; + + return deltaTotals; + } + + Ptr config() const { + return m_config; + } + +private: // IResultCapture + virtual void assertionEnded(AssertionResult const& result) { + if (result.getResultType() == ResultWas::Ok) { + m_totals.assertions.passed++; + } else if (!result.isOk()) { + m_totals.assertions.failed++; + } + + if (m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals))) + m_messages.clear(); + + // Reset working state + m_lastAssertionInfo = AssertionInfo("", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}", m_lastAssertionInfo.resultDisposition); + m_lastResult = result; + } + + virtual bool sectionStarted( + SectionInfo const& sectionInfo, + Counts& assertions) { + std::ostringstream oss; + oss << sectionInfo.name << "@" << sectionInfo.lineInfo; + + ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, oss.str()); + if (!sectionTracker.isOpen()) + return false; + m_activeSections.push_back(§ionTracker); + + m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; + + m_reporter->sectionStarting(sectionInfo); + + assertions = m_totals.assertions; + + return true; + } + bool testForMissingAssertions(Counts& assertions) { + if (assertions.total() != 0) + return false; + if (!m_config->warnAboutMissingAssertions()) + return false; + if (m_trackerContext.currentTracker().hasChildren()) + return false; + m_totals.assertions.failed++; + assertions.failed++; + return true; + } + + virtual void sectionEnded(SectionEndInfo const& endInfo) { + Counts assertions = m_totals.assertions - endInfo.prevAssertions; + bool missingAssertions = testForMissingAssertions(assertions); + + if (!m_activeSections.empty()) { + m_activeSections.back()->close(); + m_activeSections.pop_back(); + } + + m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions)); + m_messages.clear(); + } + + virtual void sectionEndedEarly(SectionEndInfo const& endInfo) { + if (m_unfinishedSections.empty()) + m_activeSections.back()->fail(); + else + m_activeSections.back()->close(); + m_activeSections.pop_back(); + + m_unfinishedSections.push_back(endInfo); + } + + virtual void pushScopedMessage(MessageInfo const& message) { + m_messages.push_back(message); + } + + virtual void popScopedMessage(MessageInfo const& message) { + m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end()); + } + + virtual std::string getCurrentTestName() const { + return m_activeTestCase + ? m_activeTestCase->getTestCaseInfo().name + : ""; + } + + virtual const AssertionResult* getLastResult() const { + return &m_lastResult; + } + + virtual void handleFatalErrorCondition(std::string const& message) { + ResultBuilder resultBuilder = makeUnexpectedResultBuilder(); + resultBuilder.setResultType(ResultWas::FatalErrorCondition); + resultBuilder << message; + resultBuilder.captureExpression(); + + handleUnfinishedSections(); + + // Recreate section for test case (as we will lose the one that was in scope) + TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); + SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description); + + Counts assertions; + assertions.failed = 1; + SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false); + m_reporter->sectionEnded(testCaseSectionStats); + + TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); + + Totals deltaTotals; + deltaTotals.testCases.failed = 1; + m_reporter->testCaseEnded(TestCaseStats(testInfo, + deltaTotals, + "", + "", + false)); + m_totals.testCases.failed++; + testGroupEnded("", m_totals, 1, 1); + m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false)); + } + +public: + // !TBD We need to do this another way! + bool aborting() const { + return m_totals.assertions.failed == static_cast(m_config->abortAfter()); + } + +private: + void runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr) { + TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); + SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description); + m_reporter->sectionStarting(testCaseSection); + Counts prevAssertions = m_totals.assertions; + double duration = 0; + try { + m_lastAssertionInfo = AssertionInfo("TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal); + + seedRng(*m_config); + + Timer timer; + timer.start(); + if (m_reporter->getPreferences().shouldRedirectStdOut) { + StreamRedirect coutRedir(Catch::cout(), redirectedCout); + StreamRedirect cerrRedir(Catch::cerr(), redirectedCerr); + invokeActiveTestCase(); + } else { + invokeActiveTestCase(); + } + duration = timer.getElapsedSeconds(); + } catch (TestFailureException&) { + // This just means the test was aborted due to failure + } catch (...) { + makeUnexpectedResultBuilder().useActiveException(); + } + m_testCaseTracker->close(); + handleUnfinishedSections(); + m_messages.clear(); + + Counts assertions = m_totals.assertions - prevAssertions; + bool missingAssertions = testForMissingAssertions(assertions); + + if (testCaseInfo.okToFail()) { + std::swap(assertions.failedButOk, assertions.failed); + m_totals.assertions.failed -= assertions.failedButOk; + m_totals.assertions.failedButOk += assertions.failedButOk; + } + + SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions); + m_reporter->sectionEnded(testCaseSectionStats); + } + + void invokeActiveTestCase() { + FatalConditionHandler fatalConditionHandler; // Handle signals + m_activeTestCase->invoke(); + fatalConditionHandler.reset(); + } + +private: + ResultBuilder makeUnexpectedResultBuilder() const { + return ResultBuilder(m_lastAssertionInfo.macroName.c_str(), + m_lastAssertionInfo.lineInfo, + m_lastAssertionInfo.capturedExpression.c_str(), + m_lastAssertionInfo.resultDisposition); + } + + void handleUnfinishedSections() { + // If sections ended prematurely due to an exception we stored their + // infos here so we can tear them down outside the unwind process. + for (std::vector::const_reverse_iterator it = m_unfinishedSections.rbegin(), + itEnd = m_unfinishedSections.rend(); + it != itEnd; + ++it) + sectionEnded(*it); + m_unfinishedSections.clear(); + } + + TestRunInfo m_runInfo; + IMutableContext& m_context; + TestCase const* m_activeTestCase; + ITracker* m_testCaseTracker; + ITracker* m_currentSectionTracker; + AssertionResult m_lastResult; + + Ptr m_config; + Totals m_totals; + Ptr m_reporter; + std::vector m_messages; + AssertionInfo m_lastAssertionInfo; + std::vector m_unfinishedSections; + std::vector m_activeSections; + TrackerContext m_trackerContext; +}; + +IResultCapture& getResultCapture() { + if (IResultCapture* capture = getCurrentContext().getResultCapture()) + return *capture; + else + throw std::logic_error("No result capture instance"); +} + +} // end namespace Catch + +// #included from: internal/catch_version.h +#define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED + +namespace Catch { + +// Versioning information +struct Version { + Version(unsigned int _majorVersion, + unsigned int _minorVersion, + unsigned int _patchNumber, + std::string const& _branchName, + unsigned int _buildNumber); + + unsigned int const majorVersion; + unsigned int const minorVersion; + unsigned int const patchNumber; + + // buildNumber is only used if branchName is not null + std::string const branchName; + unsigned int const buildNumber; + + friend std::ostream& operator<<(std::ostream& os, Version const& version); + +private: + void operator=(Version const&); +}; + +extern Version libraryVersion; +} + +#include +#include +#include + +namespace Catch { + +Ptr createReporter(std::string const& reporterName, Ptr const& config) { + Ptr reporter = getRegistryHub().getReporterRegistry().create(reporterName, config.get()); + if (!reporter) { + std::ostringstream oss; + oss << "No reporter registered with name: '" << reporterName << "'"; + throw std::domain_error(oss.str()); + } + return reporter; +} + +Ptr makeReporter(Ptr const& config) { + std::vector reporters = config->getReporterNames(); + if (reporters.empty()) + reporters.push_back("console"); + + Ptr reporter; + for (std::vector::const_iterator it = reporters.begin(), itEnd = reporters.end(); + it != itEnd; + ++it) + reporter = addReporter(reporter, createReporter(*it, config)); + return reporter; +} +Ptr addListeners(Ptr const& config, Ptr reporters) { + IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners(); + for (IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end(); + it != itEnd; + ++it) + reporters = addReporter(reporters, (*it)->create(ReporterConfig(config))); + return reporters; +} + +Totals runTests(Ptr const& config) { + + Ptr iconfig = config.get(); + + Ptr reporter = makeReporter(config); + reporter = addListeners(iconfig, reporter); + + RunContext context(iconfig, reporter); + + Totals totals; + + context.testGroupStarting(config->name(), 1, 1); + + TestSpec testSpec = config->testSpec(); + if (!testSpec.hasFilters()) + testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("~[.]").testSpec(); // All not hidden tests + + std::vector const& allTestCases = getAllTestCasesSorted(*iconfig); + for (std::vector::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end(); + it != itEnd; + ++it) { + if (!context.aborting() && matchTest(*it, testSpec, *iconfig)) + totals += context.runTest(*it); + else + reporter->skipTest(*it); + } + + context.testGroupEnded(iconfig->name(), totals, 1, 1); + return totals; +} + +void applyFilenamesAsTags(IConfig const& config) { + std::vector const& tests = getAllTestCasesSorted(config); + for (std::size_t i = 0; i < tests.size(); ++i) { + TestCase& test = const_cast(tests[i]); + std::set tags = test.tags; + + std::string filename = test.lineInfo.file; + std::string::size_type lastSlash = filename.find_last_of("\\/"); + if (lastSlash != std::string::npos) + filename = filename.substr(lastSlash + 1); + + std::string::size_type lastDot = filename.find_last_of("."); + if (lastDot != std::string::npos) + filename = filename.substr(0, lastDot); + + tags.insert("#" + filename); + setTags(test, tags); + } +} + +class Session : NonCopyable { + static bool alreadyInstantiated; + +public: + struct OnUnusedOptions { + enum DoWhat { Ignore, + Fail }; + }; + + Session() + : m_cli(makeCommandLineParser()) { + if (alreadyInstantiated) { + std::string msg = "Only one instance of Catch::Session can ever be used"; + Catch::cerr() << msg << std::endl; + throw std::logic_error(msg); + } + alreadyInstantiated = true; + } + ~Session() { + Catch::cleanUp(); + } + + void showHelp(std::string const& processName) { + Catch::cout() << "\nCatch v" << libraryVersion << "\n"; + + m_cli.usage(Catch::cout(), processName); + Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; + } + + int applyCommandLine(int argc, char const* const* const argv, OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail) { + try { + m_cli.setThrowOnUnrecognisedTokens(unusedOptionBehaviour == OnUnusedOptions::Fail); + m_unusedTokens = m_cli.parseInto(Clara::argsToVector(argc, argv), m_configData); + if (m_configData.showHelp) + showHelp(m_configData.processName); + m_config.reset(); + } catch (std::exception& ex) { + { + Colour colourGuard(Colour::Red); + Catch::cerr() + << "\nError(s) in input:\n" + << Text(ex.what(), TextAttributes().setIndent(2)) + << "\n\n"; + } + m_cli.usage(Catch::cout(), m_configData.processName); + return (std::numeric_limits::max)(); + } + return 0; + } + + void useConfigData(ConfigData const& _configData) { + m_configData = _configData; + m_config.reset(); + } + + int run(int argc, char const* const* const argv) { + + int returnCode = applyCommandLine(argc, argv); + if (returnCode == 0) + returnCode = run(); + return returnCode; + } + + int run() { + if (m_configData.showHelp) + return 0; + + try { + config(); // Force config to be constructed + + seedRng(*m_config); + + if (m_configData.filenamesAsTags) + applyFilenamesAsTags(*m_config); + + // Handle list request + if (Option listed = list(config())) + return static_cast(*listed); + + return static_cast(runTests(m_config).assertions.failed); + } catch (std::exception& ex) { + Catch::cerr() << ex.what() << std::endl; + return (std::numeric_limits::max)(); + } + } + + Clara::CommandLine const& cli() const { + return m_cli; + } + std::vector const& unusedTokens() const { + return m_unusedTokens; + } + ConfigData& configData() { + return m_configData; + } + Config& config() { + if (!m_config) + m_config = new Config(m_configData); + return *m_config; + } + +private: + Clara::CommandLine m_cli; + std::vector m_unusedTokens; + ConfigData m_configData; + Ptr m_config; +}; + +bool Session::alreadyInstantiated = false; + +} // end namespace Catch + +// #included from: catch_registry_hub.hpp +#define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED + +// #included from: catch_test_case_registry_impl.hpp +#define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED + +#include +#include +#include +#include +#include + +#ifdef CATCH_CPP14_OR_GREATER +#include +#endif + +namespace Catch { + +struct RandomNumberGenerator { + typedef int result_type; + + result_type operator()(result_type n) const { return std::rand() % n; } + +#ifdef CATCH_CPP14_OR_GREATER + static constexpr result_type min() { return 0; } + static constexpr result_type max() { return 1000000; } + result_type operator()() const { return std::rand() % max(); } +#endif + template + static void shuffle(V& vector) { + RandomNumberGenerator rng; +#ifdef CATCH_CPP14_OR_GREATER + std::shuffle(vector.begin(), vector.end(), rng); +#else + std::random_shuffle(vector.begin(), vector.end(), rng); +#endif + } +}; + +inline std::vector sortTests(IConfig const& config, std::vector const& unsortedTestCases) { + + std::vector sorted = unsortedTestCases; + + switch (config.runOrder()) { + case RunTests::InLexicographicalOrder: + std::sort(sorted.begin(), sorted.end()); + break; + case RunTests::InRandomOrder: { + seedRng(config); + RandomNumberGenerator::shuffle(sorted); + } break; + case RunTests::InDeclarationOrder: + // already in declaration order + break; + } + return sorted; +} +bool matchTest(TestCase const& testCase, TestSpec const& testSpec, IConfig const& config) { + return testSpec.matches(testCase) && (config.allowThrows() || !testCase.throws()); +} + +void enforceNoDuplicateTestCases(std::vector const& functions) { + std::set seenFunctions; + for (std::vector::const_iterator it = functions.begin(), itEnd = functions.end(); + it != itEnd; + ++it) { + std::pair::const_iterator, bool> prev = seenFunctions.insert(*it); + if (!prev.second) { + std::ostringstream ss; + + ss << Colour(Colour::Red) + << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n" + << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n" + << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl; + + throw std::runtime_error(ss.str()); + } + } +} + +std::vector filterTests(std::vector const& testCases, TestSpec const& testSpec, IConfig const& config) { + std::vector filtered; + filtered.reserve(testCases.size()); + for (std::vector::const_iterator it = testCases.begin(), itEnd = testCases.end(); + it != itEnd; + ++it) + if (matchTest(*it, testSpec, config)) + filtered.push_back(*it); + return filtered; +} +std::vector const& getAllTestCasesSorted(IConfig const& config) { + return getRegistryHub().getTestCaseRegistry().getAllTestsSorted(config); +} + +class TestRegistry : public ITestCaseRegistry { +public: + TestRegistry() + : m_currentSortOrder(RunTests::InDeclarationOrder) + , m_unnamedCount(0) {} + virtual ~TestRegistry(); + + virtual void registerTest(TestCase const& testCase) { + std::string name = testCase.getTestCaseInfo().name; + if (name == "") { + std::ostringstream oss; + oss << "Anonymous test case " << ++m_unnamedCount; + return registerTest(testCase.withName(oss.str())); + } + m_functions.push_back(testCase); + } + + virtual std::vector const& getAllTests() const { + return m_functions; + } + virtual std::vector const& getAllTestsSorted(IConfig const& config) const { + if (m_sortedFunctions.empty()) + enforceNoDuplicateTestCases(m_functions); + + if (m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty()) { + m_sortedFunctions = sortTests(config, m_functions); + m_currentSortOrder = config.runOrder(); + } + return m_sortedFunctions; + } + +private: + std::vector m_functions; + mutable RunTests::InWhatOrder m_currentSortOrder; + mutable std::vector m_sortedFunctions; + size_t m_unnamedCount; + std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised +}; + +/////////////////////////////////////////////////////////////////////////// + +class FreeFunctionTestCase : public SharedImpl { +public: + FreeFunctionTestCase(TestFunction fun) + : m_fun(fun) {} + + virtual void invoke() const { + m_fun(); + } + +private: + virtual ~FreeFunctionTestCase(); + + TestFunction m_fun; +}; + +inline std::string extractClassName(std::string const& classOrQualifiedMethodName) { + std::string className = classOrQualifiedMethodName; + if (startsWith(className, "&")) { + std::size_t lastColons = className.rfind("::"); + std::size_t penultimateColons = className.rfind("::", lastColons - 1); + if (penultimateColons == std::string::npos) + penultimateColons = 1; + className = className.substr(penultimateColons, lastColons - penultimateColons); + } + return className; +} + +void registerTestCase(ITestCase* testCase, + char const* classOrQualifiedMethodName, + NameAndDesc const& nameAndDesc, + SourceLineInfo const& lineInfo) { + + getMutableRegistryHub().registerTest(makeTestCase(testCase, + extractClassName(classOrQualifiedMethodName), + nameAndDesc.name, + nameAndDesc.description, + lineInfo)); +} +void registerTestCaseFunction(TestFunction function, + SourceLineInfo const& lineInfo, + NameAndDesc const& nameAndDesc) { + registerTestCase(new FreeFunctionTestCase(function), "", nameAndDesc, lineInfo); +} + +/////////////////////////////////////////////////////////////////////////// + +AutoReg::AutoReg(TestFunction function, + SourceLineInfo const& lineInfo, + NameAndDesc const& nameAndDesc) { + registerTestCaseFunction(function, lineInfo, nameAndDesc); +} + +AutoReg::~AutoReg() {} + +} // end namespace Catch + +// #included from: catch_reporter_registry.hpp +#define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED + +#include + +namespace Catch { + +class ReporterRegistry : public IReporterRegistry { + +public: + virtual ~ReporterRegistry() CATCH_OVERRIDE {} + + virtual IStreamingReporter* create(std::string const& name, Ptr const& config) const CATCH_OVERRIDE { + FactoryMap::const_iterator it = m_factories.find(name); + if (it == m_factories.end()) + return CATCH_NULL; + return it->second->create(ReporterConfig(config)); + } + + void registerReporter(std::string const& name, Ptr const& factory) { + m_factories.insert(std::make_pair(name, factory)); + } + void registerListener(Ptr const& factory) { + m_listeners.push_back(factory); + } + + virtual FactoryMap const& getFactories() const CATCH_OVERRIDE { + return m_factories; + } + virtual Listeners const& getListeners() const CATCH_OVERRIDE { + return m_listeners; + } + +private: + FactoryMap m_factories; + Listeners m_listeners; +}; +} + +// #included from: catch_exception_translator_registry.hpp +#define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED + +#ifdef __OBJC__ +#import "Foundation/Foundation.h" +#endif + +namespace Catch { + +class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { +public: + ~ExceptionTranslatorRegistry() { + deleteAll(m_translators); + } + + virtual void registerTranslator(const IExceptionTranslator* translator) { + m_translators.push_back(translator); + } + + virtual std::string translateActiveException() const { + try { +#ifdef __OBJC__ + // In Objective-C try objective-c exceptions first + @try { + return tryTranslators(); + } + @catch (NSException* exception) { + return Catch::toString([exception description]); + } +#else + return tryTranslators(); +#endif + } catch (TestFailureException&) { + throw; + } catch (std::exception& ex) { + return ex.what(); + } catch (std::string& msg) { + return msg; + } catch (const char* msg) { + return msg; + } catch (...) { + return "Unknown exception"; + } + } + + std::string tryTranslators() const { + if (m_translators.empty()) + throw; + else + return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end()); + } + +private: + std::vector m_translators; +}; +} + +namespace Catch { + +namespace { + + class RegistryHub : public IRegistryHub, public IMutableRegistryHub { + + RegistryHub(RegistryHub const&); + void operator=(RegistryHub const&); + + public: // IRegistryHub + RegistryHub() { + } + virtual IReporterRegistry const& getReporterRegistry() const CATCH_OVERRIDE { + return m_reporterRegistry; + } + virtual ITestCaseRegistry const& getTestCaseRegistry() const CATCH_OVERRIDE { + return m_testCaseRegistry; + } + virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE { + return m_exceptionTranslatorRegistry; + } + + public: // IMutableRegistryHub + virtual void registerReporter(std::string const& name, Ptr const& factory) CATCH_OVERRIDE { + m_reporterRegistry.registerReporter(name, factory); + } + virtual void registerListener(Ptr const& factory) CATCH_OVERRIDE { + m_reporterRegistry.registerListener(factory); + } + virtual void registerTest(TestCase const& testInfo) CATCH_OVERRIDE { + m_testCaseRegistry.registerTest(testInfo); + } + virtual void registerTranslator(const IExceptionTranslator* translator) CATCH_OVERRIDE { + m_exceptionTranslatorRegistry.registerTranslator(translator); + } + + private: + TestRegistry m_testCaseRegistry; + ReporterRegistry m_reporterRegistry; + ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; + }; + + // Single, global, instance + inline RegistryHub*& getTheRegistryHub() { + static RegistryHub* theRegistryHub = CATCH_NULL; + if (!theRegistryHub) + theRegistryHub = new RegistryHub(); + return theRegistryHub; + } +} + +IRegistryHub& getRegistryHub() { + return *getTheRegistryHub(); +} +IMutableRegistryHub& getMutableRegistryHub() { + return *getTheRegistryHub(); +} +void cleanUp() { + delete getTheRegistryHub(); + getTheRegistryHub() = CATCH_NULL; + cleanUpContext(); +} +std::string translateActiveException() { + return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); +} + +} // end namespace Catch + +// #included from: catch_notimplemented_exception.hpp +#define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED + +#include + +namespace Catch { + +NotImplementedException::NotImplementedException(SourceLineInfo const& lineInfo) + : m_lineInfo(lineInfo) { + std::ostringstream oss; + oss << lineInfo << ": function "; + oss << "not implemented"; + m_what = oss.str(); +} + +const char* NotImplementedException::what() const CATCH_NOEXCEPT { + return m_what.c_str(); +} + +} // end namespace Catch + +// #included from: catch_context_impl.hpp +#define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED + +// #included from: catch_stream.hpp +#define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED + +#include +#include +#include + +namespace Catch { + +template +class StreamBufImpl : public StreamBufBase { + char data[bufferSize]; + WriterF m_writer; + +public: + StreamBufImpl() { + setp(data, data + sizeof(data)); + } + + ~StreamBufImpl() CATCH_NOEXCEPT { + sync(); + } + +private: + int overflow(int c) { + sync(); + + if (c != EOF) { + if (pbase() == epptr()) + m_writer(std::string(1, static_cast(c))); + else + sputc(static_cast(c)); + } + return 0; + } + + int sync() { + if (pbase() != pptr()) { + m_writer(std::string(pbase(), static_cast(pptr() - pbase()))); + setp(pbase(), epptr()); + } + return 0; + } +}; + +/////////////////////////////////////////////////////////////////////////// + +FileStream::FileStream(std::string const& filename) { + m_ofs.open(filename.c_str()); + if (m_ofs.fail()) { + std::ostringstream oss; + oss << "Unable to open file: '" << filename << "'"; + throw std::domain_error(oss.str()); + } +} + +std::ostream& FileStream::stream() const { + return m_ofs; +} + +struct OutputDebugWriter { + + void operator()(std::string const& str) { + writeToDebugConsole(str); + } +}; + +DebugOutStream::DebugOutStream() + : m_streamBuf(new StreamBufImpl()) + , m_os(m_streamBuf.get()) {} + +std::ostream& DebugOutStream::stream() const { + return m_os; +} + +// Store the streambuf from cout up-front because +// cout may get redirected when running tests +CoutStream::CoutStream() + : m_os(Catch::cout().rdbuf()) {} + +std::ostream& CoutStream::stream() const { + return m_os; +} + +#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions +std::ostream& cout() { + return std::cout; +} +std::ostream& cerr() { + return std::cerr; +} +#endif +} + +namespace Catch { + +class Context : public IMutableContext { + + Context() + : m_config(CATCH_NULL) + , m_runner(CATCH_NULL) + , m_resultCapture(CATCH_NULL) {} + Context(Context const&); + void operator=(Context const&); + +public: // IContext + virtual IResultCapture* getResultCapture() { + return m_resultCapture; + } + virtual IRunner* getRunner() { + return m_runner; + } + virtual size_t getGeneratorIndex(std::string const& fileInfo, size_t totalSize) { + return getGeneratorsForCurrentTest() + .getGeneratorInfo(fileInfo, totalSize) + .getCurrentIndex(); + } + virtual bool advanceGeneratorsForCurrentTest() { + IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); + return generators && generators->moveNext(); + } + + virtual Ptr getConfig() const { + return m_config; + } + +public: // IMutableContext + virtual void setResultCapture(IResultCapture* resultCapture) { + m_resultCapture = resultCapture; + } + virtual void setRunner(IRunner* runner) { + m_runner = runner; + } + virtual void setConfig(Ptr const& config) { + m_config = config; + } + + friend IMutableContext& getCurrentMutableContext(); + +private: + IGeneratorsForTest* findGeneratorsForCurrentTest() { + std::string testName = getResultCapture()->getCurrentTestName(); + + std::map::const_iterator it = m_generatorsByTestName.find(testName); + return it != m_generatorsByTestName.end() + ? it->second + : CATCH_NULL; + } + + IGeneratorsForTest& getGeneratorsForCurrentTest() { + IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); + if (!generators) { + std::string testName = getResultCapture()->getCurrentTestName(); + generators = createGeneratorsForTest(); + m_generatorsByTestName.insert(std::make_pair(testName, generators)); + } + return *generators; + } + +private: + Ptr m_config; + IRunner* m_runner; + IResultCapture* m_resultCapture; + std::map m_generatorsByTestName; +}; + +namespace { + Context* currentContext = CATCH_NULL; +} +IMutableContext& getCurrentMutableContext() { + if (!currentContext) + currentContext = new Context(); + return *currentContext; +} +IContext& getCurrentContext() { + return getCurrentMutableContext(); +} + +void cleanUpContext() { + delete currentContext; + currentContext = CATCH_NULL; +} +} + +// #included from: catch_console_colour_impl.hpp +#define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED + +namespace Catch { +namespace { + + struct IColourImpl { + virtual ~IColourImpl() {} + virtual void use(Colour::Code _colourCode) = 0; + }; + + struct NoColourImpl : IColourImpl { + void use(Colour::Code) {} + + static IColourImpl* instance() { + static NoColourImpl s_instance; + return &s_instance; + } + }; + +} // anon namespace +} // namespace Catch + +#if !defined(CATCH_CONFIG_COLOUR_NONE) && !defined(CATCH_CONFIG_COLOUR_WINDOWS) && !defined(CATCH_CONFIG_COLOUR_ANSI) +#ifdef CATCH_PLATFORM_WINDOWS +#define CATCH_CONFIG_COLOUR_WINDOWS +#else +#define CATCH_CONFIG_COLOUR_ANSI +#endif +#endif + +#if defined(CATCH_CONFIG_COLOUR_WINDOWS) ///////////////////////////////////////// + +#ifndef NOMINMAX +#define NOMINMAX +#endif + +#ifdef __AFXDLL +#include +#else +#include +#endif + +namespace Catch { +namespace { + + class Win32ColourImpl : public IColourImpl { + public: + Win32ColourImpl() + : stdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE)) { + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo); + originalForegroundAttributes = csbiInfo.wAttributes & ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY); + originalBackgroundAttributes = csbiInfo.wAttributes & ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY); + } + + virtual void use(Colour::Code _colourCode) { + switch (_colourCode) { + case Colour::None: + return setTextAttribute(originalForegroundAttributes); + case Colour::White: + return setTextAttribute(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); + case Colour::Red: + return setTextAttribute(FOREGROUND_RED); + case Colour::Green: + return setTextAttribute(FOREGROUND_GREEN); + case Colour::Blue: + return setTextAttribute(FOREGROUND_BLUE); + case Colour::Cyan: + return setTextAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN); + case Colour::Yellow: + return setTextAttribute(FOREGROUND_RED | FOREGROUND_GREEN); + case Colour::Grey: + return setTextAttribute(0); + + case Colour::LightGrey: + return setTextAttribute(FOREGROUND_INTENSITY); + case Colour::BrightRed: + return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED); + case Colour::BrightGreen: + return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN); + case Colour::BrightWhite: + return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); + + case Colour::Bright: + throw std::logic_error("not a colour"); + } + } + + private: + void setTextAttribute(WORD _textAttribute) { + SetConsoleTextAttribute(stdoutHandle, _textAttribute | originalBackgroundAttributes); + } + HANDLE stdoutHandle; + WORD originalForegroundAttributes; + WORD originalBackgroundAttributes; + }; + + IColourImpl* platformColourInstance() { + static Win32ColourImpl s_instance; + + Ptr config = getCurrentContext().getConfig(); + UseColour::YesOrNo colourMode = config + ? config->useColour() + : UseColour::Auto; + if (colourMode == UseColour::Auto) + colourMode = !isDebuggerActive() + ? UseColour::Yes + : UseColour::No; + return colourMode == UseColour::Yes + ? &s_instance + : NoColourImpl::instance(); + } + +} // end anon namespace +} // end namespace Catch + +#elif defined(CATCH_CONFIG_COLOUR_ANSI) ////////////////////////////////////// + +#include + +namespace Catch { +namespace { + + // use POSIX/ ANSI console terminal codes + // Thanks to Adam Strzelecki for original contribution + // (http://github.com/nanoant) + // https://github.com/philsquared/Catch/pull/131 + class PosixColourImpl : public IColourImpl { + public: + virtual void use(Colour::Code _colourCode) { + switch (_colourCode) { + case Colour::None: + case Colour::White: + return setColour("[0m"); + case Colour::Red: + return setColour("[0;31m"); + case Colour::Green: + return setColour("[0;32m"); + case Colour::Blue: + return setColour("[0:34m"); + case Colour::Cyan: + return setColour("[0;36m"); + case Colour::Yellow: + return setColour("[0;33m"); + case Colour::Grey: + return setColour("[1;30m"); + + case Colour::LightGrey: + return setColour("[0;37m"); + case Colour::BrightRed: + return setColour("[1;31m"); + case Colour::BrightGreen: + return setColour("[1;32m"); + case Colour::BrightWhite: + return setColour("[1;37m"); + + case Colour::Bright: + throw std::logic_error("not a colour"); + } + } + static IColourImpl* instance() { + static PosixColourImpl s_instance; + return &s_instance; + } + + private: + void setColour(const char* _escapeCode) { + Catch::cout() << '\033' << _escapeCode; + } + }; + + IColourImpl* platformColourInstance() { + Ptr config = getCurrentContext().getConfig(); + UseColour::YesOrNo colourMode = config + ? config->useColour() + : UseColour::Auto; + if (colourMode == UseColour::Auto) + colourMode = (!isDebuggerActive() && isatty(STDOUT_FILENO)) + ? UseColour::Yes + : UseColour::No; + return colourMode == UseColour::Yes + ? PosixColourImpl::instance() + : NoColourImpl::instance(); + } + +} // end anon namespace +} // end namespace Catch + +#else // not Windows or ANSI /////////////////////////////////////////////// + +namespace Catch { + +static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } + +} // end namespace Catch + +#endif // Windows/ ANSI/ None + +namespace Catch { + +Colour::Colour(Code _colourCode) + : m_moved(false) { use(_colourCode); } +Colour::Colour(Colour const& _other) + : m_moved(false) { const_cast(_other).m_moved = true; } +Colour::~Colour() { + if (!m_moved) + use(None); +} + +void Colour::use(Code _colourCode) { + static IColourImpl* impl = platformColourInstance(); + impl->use(_colourCode); +} + +} // end namespace Catch + +// #included from: catch_generators_impl.hpp +#define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED + +#include +#include +#include + +namespace Catch { + +struct GeneratorInfo : IGeneratorInfo { + + GeneratorInfo(std::size_t size) + : m_size(size) + , m_currentIndex(0) {} + + bool moveNext() { + if (++m_currentIndex == m_size) { + m_currentIndex = 0; + return false; + } + return true; + } + + std::size_t getCurrentIndex() const { + return m_currentIndex; + } + + std::size_t m_size; + std::size_t m_currentIndex; +}; + +/////////////////////////////////////////////////////////////////////////// + +class GeneratorsForTest : public IGeneratorsForTest { + +public: + ~GeneratorsForTest() { + deleteAll(m_generatorsInOrder); + } + + IGeneratorInfo& getGeneratorInfo(std::string const& fileInfo, std::size_t size) { + std::map::const_iterator it = m_generatorsByName.find(fileInfo); + if (it == m_generatorsByName.end()) { + IGeneratorInfo* info = new GeneratorInfo(size); + m_generatorsByName.insert(std::make_pair(fileInfo, info)); + m_generatorsInOrder.push_back(info); + return *info; + } + return *it->second; + } + + bool moveNext() { + std::vector::const_iterator it = m_generatorsInOrder.begin(); + std::vector::const_iterator itEnd = m_generatorsInOrder.end(); + for (; it != itEnd; ++it) { + if ((*it)->moveNext()) + return true; + } + return false; + } + +private: + std::map m_generatorsByName; + std::vector m_generatorsInOrder; +}; + +IGeneratorsForTest* createGeneratorsForTest() { + return new GeneratorsForTest(); +} + +} // end namespace Catch + +// #included from: catch_assertionresult.hpp +#define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED + +namespace Catch { + +AssertionInfo::AssertionInfo(std::string const& _macroName, + SourceLineInfo const& _lineInfo, + std::string const& _capturedExpression, + ResultDisposition::Flags _resultDisposition) + : macroName(_macroName) + , lineInfo(_lineInfo) + , capturedExpression(_capturedExpression) + , resultDisposition(_resultDisposition) {} + +AssertionResult::AssertionResult() {} + +AssertionResult::AssertionResult(AssertionInfo const& info, AssertionResultData const& data) + : m_info(info) + , m_resultData(data) {} + +AssertionResult::~AssertionResult() {} + +// Result was a success +bool AssertionResult::succeeded() const { + return Catch::isOk(m_resultData.resultType); +} + +// Result was a success, or failure is suppressed +bool AssertionResult::isOk() const { + return Catch::isOk(m_resultData.resultType) || shouldSuppressFailure(m_info.resultDisposition); +} + +ResultWas::OfType AssertionResult::getResultType() const { + return m_resultData.resultType; +} + +bool AssertionResult::hasExpression() const { + return !m_info.capturedExpression.empty(); +} + +bool AssertionResult::hasMessage() const { + return !m_resultData.message.empty(); +} + +std::string AssertionResult::getExpression() const { + if (isFalseTest(m_info.resultDisposition)) + return "!" + m_info.capturedExpression; + else + return m_info.capturedExpression; +} +std::string AssertionResult::getExpressionInMacro() const { + if (m_info.macroName.empty()) + return m_info.capturedExpression; + else + return m_info.macroName + "( " + m_info.capturedExpression + " )"; +} + +bool AssertionResult::hasExpandedExpression() const { + return hasExpression() && getExpandedExpression() != getExpression(); +} + +std::string AssertionResult::getExpandedExpression() const { + return m_resultData.reconstructedExpression; +} + +std::string AssertionResult::getMessage() const { + return m_resultData.message; +} +SourceLineInfo AssertionResult::getSourceInfo() const { + return m_info.lineInfo; +} + +std::string AssertionResult::getTestMacroName() const { + return m_info.macroName; +} + +} // end namespace Catch + +// #included from: catch_test_case_info.hpp +#define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED + +namespace Catch { + +inline TestCaseInfo::SpecialProperties parseSpecialTag(std::string const& tag) { + if (startsWith(tag, ".") || tag == "hide" || tag == "!hide") + return TestCaseInfo::IsHidden; + else if (tag == "!throws") + return TestCaseInfo::Throws; + else if (tag == "!shouldfail") + return TestCaseInfo::ShouldFail; + else if (tag == "!mayfail") + return TestCaseInfo::MayFail; + else + return TestCaseInfo::None; +} +inline bool isReservedTag(std::string const& tag) { + return parseSpecialTag(tag) == TestCaseInfo::None && tag.size() > 0 && !isalnum(tag[0]); +} +inline void enforceNotReservedTag(std::string const& tag, SourceLineInfo const& _lineInfo) { + if (isReservedTag(tag)) { + { + Colour colourGuard(Colour::Red); + Catch::cerr() + << "Tag name [" << tag << "] not allowed.\n" + << "Tag names starting with non alpha-numeric characters are reserved\n"; + } + { + Colour colourGuard(Colour::FileName); + Catch::cerr() << _lineInfo << std::endl; + } + exit(1); + } +} + +TestCase makeTestCase(ITestCase* _testCase, + std::string const& _className, + std::string const& _name, + std::string const& _descOrTags, + SourceLineInfo const& _lineInfo) { + bool isHidden(startsWith(_name, "./")); // Legacy support + + // Parse out tags + std::set tags; + std::string desc, tag; + bool inTag = false; + for (std::size_t i = 0; i < _descOrTags.size(); ++i) { + char c = _descOrTags[i]; + if (!inTag) { + if (c == '[') + inTag = true; + else + desc += c; + } else { + if (c == ']') { + TestCaseInfo::SpecialProperties prop = parseSpecialTag(tag); + if (prop == TestCaseInfo::IsHidden) + isHidden = true; + else if (prop == TestCaseInfo::None) + enforceNotReservedTag(tag, _lineInfo); + + tags.insert(tag); + tag.clear(); + inTag = false; + } else + tag += c; + } + } + if (isHidden) { + tags.insert("hide"); + tags.insert("."); + } + + TestCaseInfo info(_name, _className, desc, tags, _lineInfo); + return TestCase(_testCase, info); +} + +void setTags(TestCaseInfo& testCaseInfo, std::set const& tags) { + testCaseInfo.tags = tags; + testCaseInfo.lcaseTags.clear(); + + std::ostringstream oss; + for (std::set::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it) { + oss << "[" << *it << "]"; + std::string lcaseTag = toLower(*it); + testCaseInfo.properties = static_cast(testCaseInfo.properties | parseSpecialTag(lcaseTag)); + testCaseInfo.lcaseTags.insert(lcaseTag); + } + testCaseInfo.tagsAsString = oss.str(); +} + +TestCaseInfo::TestCaseInfo(std::string const& _name, + std::string const& _className, + std::string const& _description, + std::set const& _tags, + SourceLineInfo const& _lineInfo) + : name(_name) + , className(_className) + , description(_description) + , lineInfo(_lineInfo) + , properties(None) { + setTags(*this, _tags); +} + +TestCaseInfo::TestCaseInfo(TestCaseInfo const& other) + : name(other.name) + , className(other.className) + , description(other.description) + , tags(other.tags) + , lcaseTags(other.lcaseTags) + , tagsAsString(other.tagsAsString) + , lineInfo(other.lineInfo) + , properties(other.properties) {} + +bool TestCaseInfo::isHidden() const { + return (properties & IsHidden) != 0; +} +bool TestCaseInfo::throws() const { + return (properties & Throws) != 0; +} +bool TestCaseInfo::okToFail() const { + return (properties & (ShouldFail | MayFail)) != 0; +} +bool TestCaseInfo::expectedToFail() const { + return (properties & (ShouldFail)) != 0; +} + +TestCase::TestCase(ITestCase* testCase, TestCaseInfo const& info) + : TestCaseInfo(info) + , test(testCase) {} + +TestCase::TestCase(TestCase const& other) + : TestCaseInfo(other) + , test(other.test) {} + +TestCase TestCase::withName(std::string const& _newName) const { + TestCase other(*this); + other.name = _newName; + return other; +} + +void TestCase::swap(TestCase& other) { + test.swap(other.test); + name.swap(other.name); + className.swap(other.className); + description.swap(other.description); + tags.swap(other.tags); + lcaseTags.swap(other.lcaseTags); + tagsAsString.swap(other.tagsAsString); + std::swap(TestCaseInfo::properties, static_cast(other).properties); + std::swap(lineInfo, other.lineInfo); +} + +void TestCase::invoke() const { + test->invoke(); +} + +bool TestCase::operator==(TestCase const& other) const { + return test.get() == other.test.get() && name == other.name && className == other.className; +} + +bool TestCase::operator<(TestCase const& other) const { + return name < other.name; +} +TestCase& TestCase::operator=(TestCase const& other) { + TestCase temp(other); + swap(temp); + return *this; +} + +TestCaseInfo const& TestCase::getTestCaseInfo() const { + return *this; +} + +} // end namespace Catch + +// #included from: catch_version.hpp +#define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED + +namespace Catch { + +Version::Version(unsigned int _majorVersion, + unsigned int _minorVersion, + unsigned int _patchNumber, + std::string const& _branchName, + unsigned int _buildNumber) + : majorVersion(_majorVersion) + , minorVersion(_minorVersion) + , patchNumber(_patchNumber) + , branchName(_branchName) + , buildNumber(_buildNumber) {} + +std::ostream& operator<<(std::ostream& os, Version const& version) { + os << version.majorVersion << "." + << version.minorVersion << "." + << version.patchNumber; + + if (!version.branchName.empty()) { + os << "-" << version.branchName + << "." << version.buildNumber; + } + return os; +} + +Version libraryVersion(1, 5, 6, "", 0); +} + +// #included from: catch_message.hpp +#define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED + +namespace Catch { + +MessageInfo::MessageInfo(std::string const& _macroName, + SourceLineInfo const& _lineInfo, + ResultWas::OfType _type) + : macroName(_macroName) + , lineInfo(_lineInfo) + , type(_type) + , sequence(++globalCount) {} + +// This may need protecting if threading support is added +unsigned int MessageInfo::globalCount = 0; + +//////////////////////////////////////////////////////////////////////////// + +ScopedMessage::ScopedMessage(MessageBuilder const& builder) + : m_info(builder.m_info) { + m_info.message = builder.m_stream.str(); + getResultCapture().pushScopedMessage(m_info); +} +ScopedMessage::ScopedMessage(ScopedMessage const& other) + : m_info(other.m_info) {} + +ScopedMessage::~ScopedMessage() { + getResultCapture().popScopedMessage(m_info); +} + +} // end namespace Catch + +// #included from: catch_legacy_reporter_adapter.hpp +#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED + +// #included from: catch_legacy_reporter_adapter.h +#define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED + +namespace Catch { +// Deprecated +struct IReporter : IShared { + virtual ~IReporter(); + + virtual bool shouldRedirectStdout() const = 0; + + virtual void StartTesting() = 0; + virtual void EndTesting(Totals const& totals) = 0; + virtual void StartGroup(std::string const& groupName) = 0; + virtual void EndGroup(std::string const& groupName, Totals const& totals) = 0; + virtual void StartTestCase(TestCaseInfo const& testInfo) = 0; + virtual void EndTestCase(TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr) = 0; + virtual void StartSection(std::string const& sectionName, std::string const& description) = 0; + virtual void EndSection(std::string const& sectionName, Counts const& assertions) = 0; + virtual void NoAssertionsInSection(std::string const& sectionName) = 0; + virtual void NoAssertionsInTestCase(std::string const& testName) = 0; + virtual void Aborted() = 0; + virtual void Result(AssertionResult const& result) = 0; +}; + +class LegacyReporterAdapter : public SharedImpl { +public: + LegacyReporterAdapter(Ptr const& legacyReporter); + virtual ~LegacyReporterAdapter(); + + virtual ReporterPreferences getPreferences() const; + virtual void noMatchingTestCases(std::string const&); + virtual void testRunStarting(TestRunInfo const&); + virtual void testGroupStarting(GroupInfo const& groupInfo); + virtual void testCaseStarting(TestCaseInfo const& testInfo); + virtual void sectionStarting(SectionInfo const& sectionInfo); + virtual void assertionStarting(AssertionInfo const&); + virtual bool assertionEnded(AssertionStats const& assertionStats); + virtual void sectionEnded(SectionStats const& sectionStats); + virtual void testCaseEnded(TestCaseStats const& testCaseStats); + virtual void testGroupEnded(TestGroupStats const& testGroupStats); + virtual void testRunEnded(TestRunStats const& testRunStats); + virtual void skipTest(TestCaseInfo const&); + +private: + Ptr m_legacyReporter; +}; +} + +namespace Catch { +LegacyReporterAdapter::LegacyReporterAdapter(Ptr const& legacyReporter) + : m_legacyReporter(legacyReporter) {} +LegacyReporterAdapter::~LegacyReporterAdapter() {} + +ReporterPreferences LegacyReporterAdapter::getPreferences() const { + ReporterPreferences prefs; + prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout(); + return prefs; +} + +void LegacyReporterAdapter::noMatchingTestCases(std::string const&) {} +void LegacyReporterAdapter::testRunStarting(TestRunInfo const&) { + m_legacyReporter->StartTesting(); +} +void LegacyReporterAdapter::testGroupStarting(GroupInfo const& groupInfo) { + m_legacyReporter->StartGroup(groupInfo.name); +} +void LegacyReporterAdapter::testCaseStarting(TestCaseInfo const& testInfo) { + m_legacyReporter->StartTestCase(testInfo); +} +void LegacyReporterAdapter::sectionStarting(SectionInfo const& sectionInfo) { + m_legacyReporter->StartSection(sectionInfo.name, sectionInfo.description); +} +void LegacyReporterAdapter::assertionStarting(AssertionInfo const&) { + // Not on legacy interface +} + +bool LegacyReporterAdapter::assertionEnded(AssertionStats const& assertionStats) { + if (assertionStats.assertionResult.getResultType() != ResultWas::Ok) { + for (std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); + it != itEnd; + ++it) { + if (it->type == ResultWas::Info) { + ResultBuilder rb(it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal); + rb << it->message; + rb.setResultType(ResultWas::Info); + AssertionResult result = rb.build(); + m_legacyReporter->Result(result); + } + } + } + m_legacyReporter->Result(assertionStats.assertionResult); + return true; +} +void LegacyReporterAdapter::sectionEnded(SectionStats const& sectionStats) { + if (sectionStats.missingAssertions) + m_legacyReporter->NoAssertionsInSection(sectionStats.sectionInfo.name); + m_legacyReporter->EndSection(sectionStats.sectionInfo.name, sectionStats.assertions); +} +void LegacyReporterAdapter::testCaseEnded(TestCaseStats const& testCaseStats) { + m_legacyReporter->EndTestCase(testCaseStats.testInfo, + testCaseStats.totals, + testCaseStats.stdOut, + testCaseStats.stdErr); +} +void LegacyReporterAdapter::testGroupEnded(TestGroupStats const& testGroupStats) { + if (testGroupStats.aborting) + m_legacyReporter->Aborted(); + m_legacyReporter->EndGroup(testGroupStats.groupInfo.name, testGroupStats.totals); +} +void LegacyReporterAdapter::testRunEnded(TestRunStats const& testRunStats) { + m_legacyReporter->EndTesting(testRunStats.totals); +} +void LegacyReporterAdapter::skipTest(TestCaseInfo const&) { +} +} + +// #included from: catch_timer.hpp + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wc++11-long-long" +#endif + +#ifdef CATCH_PLATFORM_WINDOWS +#include +#else +#include +#endif + +namespace Catch { + +namespace { +#ifdef CATCH_PLATFORM_WINDOWS + uint64_t getCurrentTicks() { + static uint64_t hz = 0, hzo = 0; + if (!hz) { + QueryPerformanceFrequency(reinterpret_cast(&hz)); + QueryPerformanceCounter(reinterpret_cast(&hzo)); + } + uint64_t t; + QueryPerformanceCounter(reinterpret_cast(&t)); + return ((t - hzo) * 1000000) / hz; + } +#else + uint64_t getCurrentTicks() { + timeval t; + gettimeofday(&t, CATCH_NULL); + return static_cast(t.tv_sec) * 1000000ull + static_cast(t.tv_usec); + } +#endif +} + +void Timer::start() { + m_ticks = getCurrentTicks(); +} +unsigned int Timer::getElapsedMicroseconds() const { + return static_cast(getCurrentTicks() - m_ticks); +} +unsigned int Timer::getElapsedMilliseconds() const { + return static_cast(getElapsedMicroseconds() / 1000); +} +double Timer::getElapsedSeconds() const { + return getElapsedMicroseconds() / 1000000.0; +} + +} // namespace Catch + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +// #included from: catch_common.hpp +#define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED + +namespace Catch { + +bool startsWith(std::string const& s, std::string const& prefix) { + return s.size() >= prefix.size() && s.substr(0, prefix.size()) == prefix; +} +bool endsWith(std::string const& s, std::string const& suffix) { + return s.size() >= suffix.size() && s.substr(s.size() - suffix.size(), suffix.size()) == suffix; +} +bool contains(std::string const& s, std::string const& infix) { + return s.find(infix) != std::string::npos; +} +void toLowerInPlace(std::string& s) { + std::transform(s.begin(), s.end(), s.begin(), ::tolower); +} +std::string toLower(std::string const& s) { + std::string lc = s; + toLowerInPlace(lc); + return lc; +} +std::string trim(std::string const& str) { + static char const* whitespaceChars = "\n\r\t "; + std::string::size_type start = str.find_first_not_of(whitespaceChars); + std::string::size_type end = str.find_last_not_of(whitespaceChars); + + return start != std::string::npos ? str.substr(start, 1 + end - start) : ""; +} + +bool replaceInPlace(std::string& str, std::string const& replaceThis, std::string const& withThis) { + bool replaced = false; + std::size_t i = str.find(replaceThis); + while (i != std::string::npos) { + replaced = true; + str = str.substr(0, i) + withThis + str.substr(i + replaceThis.size()); + if (i < str.size() - withThis.size()) + i = str.find(replaceThis, i + withThis.size()); + else + i = std::string::npos; + } + return replaced; +} + +pluralise::pluralise(std::size_t count, std::string const& label) + : m_count(count) + , m_label(label) {} + +std::ostream& operator<<(std::ostream& os, pluralise const& pluraliser) { + os << pluraliser.m_count << " " << pluraliser.m_label; + if (pluraliser.m_count != 1) + os << "s"; + return os; +} + +SourceLineInfo::SourceLineInfo() + : line(0) {} +SourceLineInfo::SourceLineInfo(char const* _file, std::size_t _line) + : file(_file) + , line(_line) {} +SourceLineInfo::SourceLineInfo(SourceLineInfo const& other) + : file(other.file) + , line(other.line) {} +bool SourceLineInfo::empty() const { + return file.empty(); +} +bool SourceLineInfo::operator==(SourceLineInfo const& other) const { + return line == other.line && file == other.file; +} +bool SourceLineInfo::operator<(SourceLineInfo const& other) const { + return line < other.line || (line == other.line && file < other.file); +} + +void seedRng(IConfig const& config) { + if (config.rngSeed() != 0) + std::srand(config.rngSeed()); +} +unsigned int rngSeed() { + return getCurrentContext().getConfig()->rngSeed(); +} + +std::ostream& operator<<(std::ostream& os, SourceLineInfo const& info) { +#ifndef __GNUG__ + os << info.file << "(" << info.line << ")"; +#else + os << info.file << ":" << info.line; +#endif + return os; +} + +void throwLogicError(std::string const& message, SourceLineInfo const& locationInfo) { + std::ostringstream oss; + oss << locationInfo << ": Internal Catch error: '" << message << "'"; + if (alwaysTrue()) + throw std::logic_error(oss.str()); +} +} + +// #included from: catch_section.hpp +#define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED + +namespace Catch { + +SectionInfo::SectionInfo(SourceLineInfo const& _lineInfo, + std::string const& _name, + std::string const& _description) + : name(_name) + , description(_description) + , lineInfo(_lineInfo) {} + +Section::Section(SectionInfo const& info) + : m_info(info) + , m_sectionIncluded(getResultCapture().sectionStarted(m_info, m_assertions)) { + m_timer.start(); +} + +Section::~Section() { + if (m_sectionIncluded) { + SectionEndInfo endInfo(m_info, m_assertions, m_timer.getElapsedSeconds()); + if (std::uncaught_exception()) + getResultCapture().sectionEndedEarly(endInfo); + else + getResultCapture().sectionEnded(endInfo); + } +} + +// This indicates whether the section should be executed or not +Section::operator bool() const { + return m_sectionIncluded; +} + +} // end namespace Catch + +// #included from: catch_debugger.hpp +#define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED + +#include + +#ifdef CATCH_PLATFORM_MAC + +#include +#include +#include +#include +#include + +namespace Catch { + +// The following function is taken directly from the following technical note: +// http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html + +// Returns true if the current process is being debugged (either +// running under the debugger or has a debugger attached post facto). +bool isDebuggerActive() { + + int mib[4]; + struct kinfo_proc info; + size_t size; + + // Initialize the flags so that, if sysctl fails for some bizarre + // reason, we get a predictable result. + + info.kp_proc.p_flag = 0; + + // Initialize mib, which tells sysctl the info we want, in this case + // we're looking for information about a specific process ID. + + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); + + // Call sysctl. + + size = sizeof(info); + if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, CATCH_NULL, 0) != 0) { + Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; + return false; + } + + // We're being debugged if the P_TRACED flag is set. + + return ((info.kp_proc.p_flag & P_TRACED) != 0); +} +} // namespace Catch + +#elif defined(_MSC_VER) +extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); +namespace Catch { +bool isDebuggerActive() { + return IsDebuggerPresent() != 0; +} +} +#elif defined(__MINGW32__) +extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); +namespace Catch { +bool isDebuggerActive() { + return IsDebuggerPresent() != 0; +} +} +#else +namespace Catch { +inline bool isDebuggerActive() { return false; } +} +#endif // Platform + +#ifdef CATCH_PLATFORM_WINDOWS +extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char*); +namespace Catch { +void writeToDebugConsole(std::string const& text) { + ::OutputDebugStringA(text.c_str()); +} +} +#else +namespace Catch { +void writeToDebugConsole(std::string const& text) { + // !TBD: Need a version for Mac/ XCode and other IDEs + Catch::cout() << text; +} +} +#endif // Platform + +// #included from: catch_tostring.hpp +#define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED + +namespace Catch { + +namespace Detail { + + const std::string unprintableString = "{?}"; + + namespace { + const int hexThreshold = 255; + + struct Endianness { + enum Arch { Big, + Little }; + + static Arch which() { + union _ { + int asInt; + char asChar[sizeof(int)]; + } u; + + u.asInt = 1; + return (u.asChar[sizeof(int) - 1] == 1) ? Big : Little; + } + }; + } + + std::string rawMemoryToString(const void* object, std::size_t size) { + // Reverse order for little endian architectures + int i = 0, end = static_cast(size), inc = 1; + if (Endianness::which() == Endianness::Little) { + i = end - 1; + end = inc = -1; + } + + unsigned char const* bytes = static_cast(object); + std::ostringstream os; + os << "0x" << std::setfill('0') << std::hex; + for (; i != end; i += inc) + os << std::setw(2) << static_cast(bytes[i]); + return os.str(); + } +} + +std::string toString(std::string const& value) { + std::string s = value; + if (getCurrentContext().getConfig()->showInvisibles()) { + for (size_t i = 0; i < s.size(); ++i) { + std::string subs; + switch (s[i]) { + case '\n': + subs = "\\n"; + break; + case '\t': + subs = "\\t"; + break; + default: + break; + } + if (!subs.empty()) { + s = s.substr(0, i) + subs + s.substr(i + 1); + ++i; + } + } + } + return "\"" + s + "\""; +} +std::string toString(std::wstring const& value) { + + std::string s; + s.reserve(value.size()); + for (size_t i = 0; i < value.size(); ++i) + s += value[i] <= 0xff ? static_cast(value[i]) : '?'; + return Catch::toString(s); +} + +std::string toString(const char* const value) { + return value ? Catch::toString(std::string(value)) : std::string("{null string}"); +} + +std::string toString(char* const value) { + return Catch::toString(static_cast(value)); +} + +std::string toString(const wchar_t* const value) { + return value ? Catch::toString(std::wstring(value)) : std::string("{null string}"); +} + +std::string toString(wchar_t* const value) { + return Catch::toString(static_cast(value)); +} + +std::string toString(int value) { + std::ostringstream oss; + oss << value; + if (value > Detail::hexThreshold) + oss << " (0x" << std::hex << value << ")"; + return oss.str(); +} + +std::string toString(unsigned long value) { + std::ostringstream oss; + oss << value; + if (value > Detail::hexThreshold) + oss << " (0x" << std::hex << value << ")"; + return oss.str(); +} + +std::string toString(unsigned int value) { + return Catch::toString(static_cast(value)); +} + +template +std::string fpToString(T value, int precision) { + std::ostringstream oss; + oss << std::setprecision(precision) + << std::fixed + << value; + std::string d = oss.str(); + std::size_t i = d.find_last_not_of('0'); + if (i != std::string::npos && i != d.size() - 1) { + if (d[i] == '.') + i++; + d = d.substr(0, i + 1); + } + return d; +} + +std::string toString(const double value) { + return fpToString(value, 10); +} +std::string toString(const float value) { + return fpToString(value, 5) + "f"; +} + +std::string toString(bool value) { + return value ? "true" : "false"; +} + +std::string toString(char value) { + return value < ' ' + ? toString(static_cast(value)) + : Detail::makeString(value); +} + +std::string toString(signed char value) { + return toString(static_cast(value)); +} + +std::string toString(unsigned char value) { + return toString(static_cast(value)); +} + +#ifdef CATCH_CONFIG_CPP11_LONG_LONG +std::string toString(long long value) { + std::ostringstream oss; + oss << value; + if (value > Detail::hexThreshold) + oss << " (0x" << std::hex << value << ")"; + return oss.str(); +} +std::string toString(unsigned long long value) { + std::ostringstream oss; + oss << value; + if (value > Detail::hexThreshold) + oss << " (0x" << std::hex << value << ")"; + return oss.str(); +} +#endif + +#ifdef CATCH_CONFIG_CPP11_NULLPTR +std::string toString(std::nullptr_t) { + return "nullptr"; +} +#endif + +#ifdef __OBJC__ +std::string toString(NSString const* const& nsstring) { + if (!nsstring) + return "nil"; + return "@" + toString([nsstring UTF8String]); +} +std::string toString(NSString* CATCH_ARC_STRONG const& nsstring) { + if (!nsstring) + return "nil"; + return "@" + toString([nsstring UTF8String]); +} +std::string toString(NSObject* const& nsObject) { + return toString([nsObject description]); +} +#endif + +} // end namespace Catch + +// #included from: catch_result_builder.hpp +#define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED + +namespace Catch { + +std::string capturedExpressionWithSecondArgument(std::string const& capturedExpression, std::string const& secondArg) { + return secondArg.empty() || secondArg == "\"\"" + ? capturedExpression + : capturedExpression + ", " + secondArg; +} +ResultBuilder::ResultBuilder(char const* macroName, + SourceLineInfo const& lineInfo, + char const* capturedExpression, + ResultDisposition::Flags resultDisposition, + char const* secondArg) + : m_assertionInfo(macroName, lineInfo, capturedExpressionWithSecondArgument(capturedExpression, secondArg), resultDisposition) + , m_shouldDebugBreak(false) + , m_shouldThrow(false) {} + +ResultBuilder& ResultBuilder::setResultType(ResultWas::OfType result) { + m_data.resultType = result; + return *this; +} +ResultBuilder& ResultBuilder::setResultType(bool result) { + m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; + return *this; +} +ResultBuilder& ResultBuilder::setLhs(std::string const& lhs) { + m_exprComponents.lhs = lhs; + return *this; +} +ResultBuilder& ResultBuilder::setRhs(std::string const& rhs) { + m_exprComponents.rhs = rhs; + return *this; +} +ResultBuilder& ResultBuilder::setOp(std::string const& op) { + m_exprComponents.op = op; + return *this; +} + +void ResultBuilder::endExpression() { + m_exprComponents.testFalse = isFalseTest(m_assertionInfo.resultDisposition); + captureExpression(); +} + +void ResultBuilder::useActiveException(ResultDisposition::Flags resultDisposition) { + m_assertionInfo.resultDisposition = resultDisposition; + m_stream.oss << Catch::translateActiveException(); + captureResult(ResultWas::ThrewException); +} + +void ResultBuilder::captureResult(ResultWas::OfType resultType) { + setResultType(resultType); + captureExpression(); +} +void ResultBuilder::captureExpectedException(std::string const& expectedMessage) { + if (expectedMessage.empty()) + captureExpectedException(Matchers::Impl::Generic::AllOf()); + else + captureExpectedException(Matchers::Equals(expectedMessage)); +} + +void ResultBuilder::captureExpectedException(Matchers::Impl::Matcher const& matcher) { + + assert(m_exprComponents.testFalse == false); + AssertionResultData data = m_data; + data.resultType = ResultWas::Ok; + data.reconstructedExpression = m_assertionInfo.capturedExpression; + + std::string actualMessage = Catch::translateActiveException(); + if (!matcher.match(actualMessage)) { + data.resultType = ResultWas::ExpressionFailed; + data.reconstructedExpression = actualMessage; + } + AssertionResult result(m_assertionInfo, data); + handleResult(result); +} + +void ResultBuilder::captureExpression() { + AssertionResult result = build(); + handleResult(result); +} +void ResultBuilder::handleResult(AssertionResult const& result) { + getResultCapture().assertionEnded(result); + + if (!result.isOk()) { + if (getCurrentContext().getConfig()->shouldDebugBreak()) + m_shouldDebugBreak = true; + if (getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal)) + m_shouldThrow = true; + } +} +void ResultBuilder::react() { + if (m_shouldThrow) + throw Catch::TestFailureException(); +} + +bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; } +bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); } + +AssertionResult ResultBuilder::build() const { + assert(m_data.resultType != ResultWas::Unknown); + + AssertionResultData data = m_data; + + // Flip bool results if testFalse is set + if (m_exprComponents.testFalse) { + if (data.resultType == ResultWas::Ok) + data.resultType = ResultWas::ExpressionFailed; + else if (data.resultType == ResultWas::ExpressionFailed) + data.resultType = ResultWas::Ok; + } + + data.message = m_stream.oss.str(); + data.reconstructedExpression = reconstructExpression(); + if (m_exprComponents.testFalse) { + if (m_exprComponents.op == "") + data.reconstructedExpression = "!" + data.reconstructedExpression; + else + data.reconstructedExpression = "!(" + data.reconstructedExpression + ")"; + } + return AssertionResult(m_assertionInfo, data); +} +std::string ResultBuilder::reconstructExpression() const { + if (m_exprComponents.op == "") + return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs; + else if (m_exprComponents.op == "matches") + return m_exprComponents.lhs + " " + m_exprComponents.rhs; + else if (m_exprComponents.op != "!") { + if (m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 && m_exprComponents.lhs.find("\n") == std::string::npos && m_exprComponents.rhs.find("\n") == std::string::npos) + return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs; + else + return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs; + } else + return "{can't expand - use " + m_assertionInfo.macroName + "_FALSE( " + m_assertionInfo.capturedExpression.substr(1) + " ) instead of " + m_assertionInfo.macroName + "( " + m_assertionInfo.capturedExpression + " ) for better diagnostics}"; +} + +} // end namespace Catch + +// #included from: catch_tag_alias_registry.hpp +#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED + +// #included from: catch_tag_alias_registry.h +#define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED + +#include + +namespace Catch { + +class TagAliasRegistry : public ITagAliasRegistry { +public: + virtual ~TagAliasRegistry(); + virtual Option find(std::string const& alias) const; + virtual std::string expandAliases(std::string const& unexpandedTestSpec) const; + void add(char const* alias, char const* tag, SourceLineInfo const& lineInfo); + static TagAliasRegistry& get(); + +private: + std::map m_registry; +}; + +} // end namespace Catch + +#include +#include + +namespace Catch { + +TagAliasRegistry::~TagAliasRegistry() {} + +Option TagAliasRegistry::find(std::string const& alias) const { + std::map::const_iterator it = m_registry.find(alias); + if (it != m_registry.end()) + return it->second; + else + return Option(); +} + +std::string TagAliasRegistry::expandAliases(std::string const& unexpandedTestSpec) const { + std::string expandedTestSpec = unexpandedTestSpec; + for (std::map::const_iterator it = m_registry.begin(), itEnd = m_registry.end(); + it != itEnd; + ++it) { + std::size_t pos = expandedTestSpec.find(it->first); + if (pos != std::string::npos) { + expandedTestSpec = expandedTestSpec.substr(0, pos) + it->second.tag + expandedTestSpec.substr(pos + it->first.size()); + } + } + return expandedTestSpec; +} + +void TagAliasRegistry::add(char const* alias, char const* tag, SourceLineInfo const& lineInfo) { + + if (!startsWith(alias, "[@") || !endsWith(alias, "]")) { + std::ostringstream oss; + oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo; + throw std::domain_error(oss.str().c_str()); + } + if (!m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second) { + std::ostringstream oss; + oss << "error: tag alias, \"" << alias << "\" already registered.\n" + << "\tFirst seen at " << find(alias)->lineInfo << "\n" + << "\tRedefined at " << lineInfo; + throw std::domain_error(oss.str().c_str()); + } +} + +TagAliasRegistry& TagAliasRegistry::get() { + static TagAliasRegistry instance; + return instance; +} + +ITagAliasRegistry::~ITagAliasRegistry() {} +ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); } + +RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) { + try { + TagAliasRegistry::get().add(alias, tag, lineInfo); + } catch (std::exception& ex) { + Colour colourGuard(Colour::Red); + Catch::cerr() << ex.what() << std::endl; + exit(1); + } +} + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_multi.hpp +#define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED + +namespace Catch { + +class MultipleReporters : public SharedImpl { + typedef std::vector> Reporters; + Reporters m_reporters; + +public: + void add(Ptr const& reporter) { + m_reporters.push_back(reporter); + } + +public: // IStreamingReporter + virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { + return m_reporters[0]->getPreferences(); + } + + virtual void noMatchingTestCases(std::string const& spec) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->noMatchingTestCases(spec); + } + + virtual void testRunStarting(TestRunInfo const& testRunInfo) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->testRunStarting(testRunInfo); + } + + virtual void testGroupStarting(GroupInfo const& groupInfo) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->testGroupStarting(groupInfo); + } + + virtual void testCaseStarting(TestCaseInfo const& testInfo) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->testCaseStarting(testInfo); + } + + virtual void sectionStarting(SectionInfo const& sectionInfo) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->sectionStarting(sectionInfo); + } + + virtual void assertionStarting(AssertionInfo const& assertionInfo) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->assertionStarting(assertionInfo); + } + + // The return value indicates if the messages buffer should be cleared: + virtual bool assertionEnded(AssertionStats const& assertionStats) CATCH_OVERRIDE { + bool clearBuffer = false; + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + clearBuffer |= (*it)->assertionEnded(assertionStats); + return clearBuffer; + } + + virtual void sectionEnded(SectionStats const& sectionStats) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->sectionEnded(sectionStats); + } + + virtual void testCaseEnded(TestCaseStats const& testCaseStats) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->testCaseEnded(testCaseStats); + } + + virtual void testGroupEnded(TestGroupStats const& testGroupStats) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->testGroupEnded(testGroupStats); + } + + virtual void testRunEnded(TestRunStats const& testRunStats) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->testRunEnded(testRunStats); + } + + virtual void skipTest(TestCaseInfo const& testInfo) CATCH_OVERRIDE { + for (Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); + it != itEnd; + ++it) + (*it)->skipTest(testInfo); + } + + virtual MultipleReporters* tryAsMulti() CATCH_OVERRIDE { + return this; + } +}; + +Ptr addReporter(Ptr const& existingReporter, Ptr const& additionalReporter) { + Ptr resultingReporter; + + if (existingReporter) { + MultipleReporters* multi = existingReporter->tryAsMulti(); + if (!multi) { + multi = new MultipleReporters; + resultingReporter = Ptr(multi); + if (existingReporter) + multi->add(existingReporter); + } else + resultingReporter = existingReporter; + multi->add(additionalReporter); + } else + resultingReporter = additionalReporter; + + return resultingReporter; +} + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_xml.hpp +#define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED + +// #included from: catch_reporter_bases.hpp +#define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED + +#include + +namespace Catch { + +struct StreamingReporterBase : SharedImpl { + + StreamingReporterBase(ReporterConfig const& _config) + : m_config(_config.fullConfig()) + , stream(_config.stream()) { + m_reporterPrefs.shouldRedirectStdOut = false; + } + + virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { + return m_reporterPrefs; + } + + virtual ~StreamingReporterBase() CATCH_OVERRIDE; + + virtual void noMatchingTestCases(std::string const&) CATCH_OVERRIDE {} + + virtual void testRunStarting(TestRunInfo const& _testRunInfo) CATCH_OVERRIDE { + currentTestRunInfo = _testRunInfo; + } + virtual void testGroupStarting(GroupInfo const& _groupInfo) CATCH_OVERRIDE { + currentGroupInfo = _groupInfo; + } + + virtual void testCaseStarting(TestCaseInfo const& _testInfo) CATCH_OVERRIDE { + currentTestCaseInfo = _testInfo; + } + virtual void sectionStarting(SectionInfo const& _sectionInfo) CATCH_OVERRIDE { + m_sectionStack.push_back(_sectionInfo); + } + + virtual void sectionEnded(SectionStats const& /* _sectionStats */) CATCH_OVERRIDE { + m_sectionStack.pop_back(); + } + virtual void testCaseEnded(TestCaseStats const& /* _testCaseStats */) CATCH_OVERRIDE { + currentTestCaseInfo.reset(); + } + virtual void testGroupEnded(TestGroupStats const& /* _testGroupStats */) CATCH_OVERRIDE { + currentGroupInfo.reset(); + } + virtual void testRunEnded(TestRunStats const& /* _testRunStats */) CATCH_OVERRIDE { + currentTestCaseInfo.reset(); + currentGroupInfo.reset(); + currentTestRunInfo.reset(); + } + + virtual void skipTest(TestCaseInfo const&) CATCH_OVERRIDE { + // Don't do anything with this by default. + // It can optionally be overridden in the derived class. + } + + Ptr m_config; + std::ostream& stream; + + LazyStat currentTestRunInfo; + LazyStat currentGroupInfo; + LazyStat currentTestCaseInfo; + + std::vector m_sectionStack; + ReporterPreferences m_reporterPrefs; +}; + +struct CumulativeReporterBase : SharedImpl { + template + struct Node : SharedImpl<> { + explicit Node(T const& _value) + : value(_value) {} + virtual ~Node() {} + + typedef std::vector> ChildNodes; + T value; + ChildNodes children; + }; + struct SectionNode : SharedImpl<> { + explicit SectionNode(SectionStats const& _stats) + : stats(_stats) {} + virtual ~SectionNode(); + + bool operator==(SectionNode const& other) const { + return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; + } + bool operator==(Ptr const& other) const { + return operator==(*other); + } + + SectionStats stats; + typedef std::vector> ChildSections; + typedef std::vector Assertions; + ChildSections childSections; + Assertions assertions; + std::string stdOut; + std::string stdErr; + }; + + struct BySectionInfo { + BySectionInfo(SectionInfo const& other) + : m_other(other) {} + BySectionInfo(BySectionInfo const& other) + : m_other(other.m_other) {} + bool operator()(Ptr const& node) const { + return node->stats.sectionInfo.lineInfo == m_other.lineInfo; + } + + private: + void operator=(BySectionInfo const&); + SectionInfo const& m_other; + }; + + typedef Node TestCaseNode; + typedef Node TestGroupNode; + typedef Node TestRunNode; + + CumulativeReporterBase(ReporterConfig const& _config) + : m_config(_config.fullConfig()) + , stream(_config.stream()) { + m_reporterPrefs.shouldRedirectStdOut = false; + } + ~CumulativeReporterBase(); + + virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { + return m_reporterPrefs; + } + + virtual void testRunStarting(TestRunInfo const&) CATCH_OVERRIDE {} + virtual void testGroupStarting(GroupInfo const&) CATCH_OVERRIDE {} + + virtual void testCaseStarting(TestCaseInfo const&) CATCH_OVERRIDE {} + + virtual void sectionStarting(SectionInfo const& sectionInfo) CATCH_OVERRIDE { + SectionStats incompleteStats(sectionInfo, Counts(), 0, false); + Ptr node; + if (m_sectionStack.empty()) { + if (!m_rootSection) + m_rootSection = new SectionNode(incompleteStats); + node = m_rootSection; + } else { + SectionNode& parentNode = *m_sectionStack.back(); + SectionNode::ChildSections::const_iterator it = std::find_if(parentNode.childSections.begin(), + parentNode.childSections.end(), + BySectionInfo(sectionInfo)); + if (it == parentNode.childSections.end()) { + node = new SectionNode(incompleteStats); + parentNode.childSections.push_back(node); + } else + node = *it; + } + m_sectionStack.push_back(node); + m_deepestSection = node; + } + + virtual void assertionStarting(AssertionInfo const&) CATCH_OVERRIDE {} + + virtual bool assertionEnded(AssertionStats const& assertionStats) CATCH_OVERRIDE { + assert(!m_sectionStack.empty()); + SectionNode& sectionNode = *m_sectionStack.back(); + sectionNode.assertions.push_back(assertionStats); + return true; + } + virtual void sectionEnded(SectionStats const& sectionStats) CATCH_OVERRIDE { + assert(!m_sectionStack.empty()); + SectionNode& node = *m_sectionStack.back(); + node.stats = sectionStats; + m_sectionStack.pop_back(); + } + virtual void testCaseEnded(TestCaseStats const& testCaseStats) CATCH_OVERRIDE { + Ptr node = new TestCaseNode(testCaseStats); + assert(m_sectionStack.size() == 0); + node->children.push_back(m_rootSection); + m_testCases.push_back(node); + m_rootSection.reset(); + + assert(m_deepestSection); + m_deepestSection->stdOut = testCaseStats.stdOut; + m_deepestSection->stdErr = testCaseStats.stdErr; + } + virtual void testGroupEnded(TestGroupStats const& testGroupStats) CATCH_OVERRIDE { + Ptr node = new TestGroupNode(testGroupStats); + node->children.swap(m_testCases); + m_testGroups.push_back(node); + } + virtual void testRunEnded(TestRunStats const& testRunStats) CATCH_OVERRIDE { + Ptr node = new TestRunNode(testRunStats); + node->children.swap(m_testGroups); + m_testRuns.push_back(node); + testRunEndedCumulative(); + } + virtual void testRunEndedCumulative() = 0; + + virtual void skipTest(TestCaseInfo const&) CATCH_OVERRIDE {} + + Ptr m_config; + std::ostream& stream; + std::vector m_assertions; + std::vector>> m_sections; + std::vector> m_testCases; + std::vector> m_testGroups; + + std::vector> m_testRuns; + + Ptr m_rootSection; + Ptr m_deepestSection; + std::vector> m_sectionStack; + ReporterPreferences m_reporterPrefs; +}; + +template +char const* getLineOfChars() { + static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; + if (!*line) { + memset(line, C, CATCH_CONFIG_CONSOLE_WIDTH - 1); + line[CATCH_CONFIG_CONSOLE_WIDTH - 1] = 0; + } + return line; +} + +struct TestEventListenerBase : StreamingReporterBase { + TestEventListenerBase(ReporterConfig const& _config) + : StreamingReporterBase(_config) {} + + virtual void assertionStarting(AssertionInfo const&) CATCH_OVERRIDE {} + virtual bool assertionEnded(AssertionStats const&) CATCH_OVERRIDE { + return false; + } +}; + +} // end namespace Catch + +// #included from: ../internal/catch_reporter_registrars.hpp +#define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED + +namespace Catch { + +template +class LegacyReporterRegistrar { + + class ReporterFactory : public IReporterFactory { + virtual IStreamingReporter* create(ReporterConfig const& config) const { + return new LegacyReporterAdapter(new T(config)); + } + + virtual std::string getDescription() const { + return T::getDescription(); + } + }; + +public: + LegacyReporterRegistrar(std::string const& name) { + getMutableRegistryHub().registerReporter(name, new ReporterFactory()); + } +}; + +template +class ReporterRegistrar { + + class ReporterFactory : public SharedImpl { + + // *** Please Note ***: + // - If you end up here looking at a compiler error because it's trying to register + // your custom reporter class be aware that the native reporter interface has changed + // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via + // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter. + // However please consider updating to the new interface as the old one is now + // deprecated and will probably be removed quite soon! + // Please contact me via github if you have any questions at all about this. + // In fact, ideally, please contact me anyway to let me know you've hit this - as I have + // no idea who is actually using custom reporters at all (possibly no-one!). + // The new interface is designed to minimise exposure to interface changes in the future. + virtual IStreamingReporter* create(ReporterConfig const& config) const { + return new T(config); + } + + virtual std::string getDescription() const { + return T::getDescription(); + } + }; + +public: + ReporterRegistrar(std::string const& name) { + getMutableRegistryHub().registerReporter(name, new ReporterFactory()); + } +}; + +template +class ListenerRegistrar { + + class ListenerFactory : public SharedImpl { + + virtual IStreamingReporter* create(ReporterConfig const& config) const { + return new T(config); + } + virtual std::string getDescription() const { + return ""; + } + }; + +public: + ListenerRegistrar() { + getMutableRegistryHub().registerListener(new ListenerFactory()); + } +}; +} + +#define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER(name, reporterType) \ + namespace { \ + Catch::LegacyReporterRegistrar catch_internal_RegistrarFor##reporterType(name); \ + } + +#define INTERNAL_CATCH_REGISTER_REPORTER(name, reporterType) \ + namespace { \ + Catch::ReporterRegistrar catch_internal_RegistrarFor##reporterType(name); \ + } + +#define INTERNAL_CATCH_REGISTER_LISTENER(listenerType) \ + namespace { \ + Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; \ + } + +// #included from: ../internal/catch_xmlwriter.hpp +#define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED + +#include +#include +#include +#include + +namespace Catch { + +class XmlEncode { +public: + enum ForWhat { ForTextNodes, + ForAttributes }; + + XmlEncode(std::string const& str, ForWhat forWhat = ForTextNodes) + : m_str(str) + , m_forWhat(forWhat) {} + + void encodeTo(std::ostream& os) const { + + // Apostrophe escaping not necessary if we always use " to write attributes + // (see: http://www.w3.org/TR/xml/#syntax) + + for (std::size_t i = 0; i < m_str.size(); ++i) { + char c = m_str[i]; + switch (c) { + case '<': + os << "<"; + break; + case '&': + os << "&"; + break; + + case '>': + // See: http://www.w3.org/TR/xml/#syntax + if (i > 2 && m_str[i - 1] == ']' && m_str[i - 2] == ']') + os << ">"; + else + os << c; + break; + + case '\"': + if (m_forWhat == ForAttributes) + os << """; + else + os << c; + break; + + default: + // Escape control chars - based on contribution by @espenalb in PR #465 + if ((c < '\x09') || (c > '\x0D' && c < '\x20') || c == '\x7F') + os << "&#x" << std::uppercase << std::hex << static_cast(c); + else + os << c; + } + } + } + + friend std::ostream& operator<<(std::ostream& os, XmlEncode const& xmlEncode) { + xmlEncode.encodeTo(os); + return os; + } + +private: + std::string m_str; + ForWhat m_forWhat; +}; + +class XmlWriter { +public: + class ScopedElement { + public: + ScopedElement(XmlWriter* writer) + : m_writer(writer) {} + + ScopedElement(ScopedElement const& other) + : m_writer(other.m_writer) { + other.m_writer = CATCH_NULL; + } + + ~ScopedElement() { + if (m_writer) + m_writer->endElement(); + } + + ScopedElement& writeText(std::string const& text, bool indent = true) { + m_writer->writeText(text, indent); + return *this; + } + + template + ScopedElement& writeAttribute(std::string const& name, T const& attribute) { + m_writer->writeAttribute(name, attribute); + return *this; + } + + private: + mutable XmlWriter* m_writer; + }; + + XmlWriter() + : m_tagIsOpen(false) + , m_needsNewline(false) + , m_os(&Catch::cout()) {} + + XmlWriter(std::ostream& os) + : m_tagIsOpen(false) + , m_needsNewline(false) + , m_os(&os) {} + + ~XmlWriter() { + while (!m_tags.empty()) + endElement(); + } + + XmlWriter& startElement(std::string const& name) { + ensureTagClosed(); + newlineIfNecessary(); + stream() << m_indent << "<" << name; + m_tags.push_back(name); + m_indent += " "; + m_tagIsOpen = true; + return *this; + } + + ScopedElement scopedElement(std::string const& name) { + ScopedElement scoped(this); + startElement(name); + return scoped; + } + + XmlWriter& endElement() { + newlineIfNecessary(); + m_indent = m_indent.substr(0, m_indent.size() - 2); + if (m_tagIsOpen) { + stream() << "/>\n"; + m_tagIsOpen = false; + } else { + stream() << m_indent << "\n"; + } + m_tags.pop_back(); + return *this; + } + + XmlWriter& writeAttribute(std::string const& name, std::string const& attribute) { + if (!name.empty() && !attribute.empty()) + stream() << " " << name << "=\"" << XmlEncode(attribute, XmlEncode::ForAttributes) << "\""; + return *this; + } + + XmlWriter& writeAttribute(std::string const& name, bool attribute) { + stream() << " " << name << "=\"" << (attribute ? "true" : "false") << "\""; + return *this; + } + + template + XmlWriter& writeAttribute(std::string const& name, T const& attribute) { + std::ostringstream oss; + oss << attribute; + return writeAttribute(name, oss.str()); + } + + XmlWriter& writeText(std::string const& text, bool indent = true) { + if (!text.empty()) { + bool tagWasOpen = m_tagIsOpen; + ensureTagClosed(); + if (tagWasOpen && indent) + stream() << m_indent; + stream() << XmlEncode(text); + m_needsNewline = true; + } + return *this; + } + + XmlWriter& writeComment(std::string const& text) { + ensureTagClosed(); + stream() << m_indent << ""; + m_needsNewline = true; + return *this; + } + + XmlWriter& writeBlankLine() { + ensureTagClosed(); + stream() << "\n"; + return *this; + } + + void setStream(std::ostream& os) { + m_os = &os; + } + +private: + XmlWriter(XmlWriter const&); + void operator=(XmlWriter const&); + + std::ostream& stream() { + return *m_os; + } + + void ensureTagClosed() { + if (m_tagIsOpen) { + stream() << ">\n"; + m_tagIsOpen = false; + } + } + + void newlineIfNecessary() { + if (m_needsNewline) { + stream() << "\n"; + m_needsNewline = false; + } + } + + bool m_tagIsOpen; + bool m_needsNewline; + std::vector m_tags; + std::string m_indent; + std::ostream* m_os; +}; +} +// #included from: catch_reenable_warnings.h + +#define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED + +#ifdef __clang__ +#ifdef __ICC // icpc defines the __clang__ macro +#pragma warning(pop) +#else +#pragma clang diagnostic pop +#endif +#elif defined __GNUC__ +#pragma GCC diagnostic pop +#endif + +namespace Catch { +class XmlReporter : public StreamingReporterBase { +public: + XmlReporter(ReporterConfig const& _config) + : StreamingReporterBase(_config) + , m_sectionDepth(0) { + m_reporterPrefs.shouldRedirectStdOut = true; + } + + virtual ~XmlReporter() CATCH_OVERRIDE; + + static std::string getDescription() { + return "Reports test results as an XML document"; + } + +public: // StreamingReporterBase + virtual void noMatchingTestCases(std::string const& s) CATCH_OVERRIDE { + StreamingReporterBase::noMatchingTestCases(s); + } + + virtual void testRunStarting(TestRunInfo const& testInfo) CATCH_OVERRIDE { + StreamingReporterBase::testRunStarting(testInfo); + m_xml.setStream(stream); + m_xml.startElement("Catch"); + if (!m_config->name().empty()) + m_xml.writeAttribute("name", m_config->name()); + } + + virtual void testGroupStarting(GroupInfo const& groupInfo) CATCH_OVERRIDE { + StreamingReporterBase::testGroupStarting(groupInfo); + m_xml.startElement("Group") + .writeAttribute("name", groupInfo.name); + } + + virtual void testCaseStarting(TestCaseInfo const& testInfo) CATCH_OVERRIDE { + StreamingReporterBase::testCaseStarting(testInfo); + m_xml.startElement("TestCase").writeAttribute("name", trim(testInfo.name)); + + if (m_config->showDurations() == ShowDurations::Always) + m_testCaseTimer.start(); + } + + virtual void sectionStarting(SectionInfo const& sectionInfo) CATCH_OVERRIDE { + StreamingReporterBase::sectionStarting(sectionInfo); + if (m_sectionDepth++ > 0) { + m_xml.startElement("Section") + .writeAttribute("name", trim(sectionInfo.name)) + .writeAttribute("description", sectionInfo.description); + } + } + + virtual void assertionStarting(AssertionInfo const&) CATCH_OVERRIDE {} + + virtual bool assertionEnded(AssertionStats const& assertionStats) CATCH_OVERRIDE { + const AssertionResult& assertionResult = assertionStats.assertionResult; + + // Print any info messages in tags. + if (assertionStats.assertionResult.getResultType() != ResultWas::Ok) { + for (std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); + it != itEnd; + ++it) { + if (it->type == ResultWas::Info) { + m_xml.scopedElement("Info") + .writeText(it->message); + } else if (it->type == ResultWas::Warning) { + m_xml.scopedElement("Warning") + .writeText(it->message); + } + } + } + + // Drop out if result was successful but we're not printing them. + if (!m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType())) + return true; + + // Print the expression if there is one. + if (assertionResult.hasExpression()) { + m_xml.startElement("Expression") + .writeAttribute("success", assertionResult.succeeded()) + .writeAttribute("type", assertionResult.getTestMacroName()) + .writeAttribute("filename", assertionResult.getSourceInfo().file) + .writeAttribute("line", assertionResult.getSourceInfo().line); + + m_xml.scopedElement("Original") + .writeText(assertionResult.getExpression()); + m_xml.scopedElement("Expanded") + .writeText(assertionResult.getExpandedExpression()); + } + + // And... Print a result applicable to each result type. + switch (assertionResult.getResultType()) { + case ResultWas::ThrewException: + m_xml.scopedElement("Exception") + .writeAttribute("filename", assertionResult.getSourceInfo().file) + .writeAttribute("line", assertionResult.getSourceInfo().line) + .writeText(assertionResult.getMessage()); + break; + case ResultWas::FatalErrorCondition: + m_xml.scopedElement("Fatal Error Condition") + .writeAttribute("filename", assertionResult.getSourceInfo().file) + .writeAttribute("line", assertionResult.getSourceInfo().line) + .writeText(assertionResult.getMessage()); + break; + case ResultWas::Info: + m_xml.scopedElement("Info") + .writeText(assertionResult.getMessage()); + break; + case ResultWas::Warning: + // Warning will already have been written + break; + case ResultWas::ExplicitFailure: + m_xml.scopedElement("Failure") + .writeText(assertionResult.getMessage()); + break; + default: + break; + } + + if (assertionResult.hasExpression()) + m_xml.endElement(); + + return true; + } + + virtual void sectionEnded(SectionStats const& sectionStats) CATCH_OVERRIDE { + StreamingReporterBase::sectionEnded(sectionStats); + if (--m_sectionDepth > 0) { + XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResults"); + e.writeAttribute("successes", sectionStats.assertions.passed); + e.writeAttribute("failures", sectionStats.assertions.failed); + e.writeAttribute("expectedFailures", sectionStats.assertions.failedButOk); + + if (m_config->showDurations() == ShowDurations::Always) + e.writeAttribute("durationInSeconds", sectionStats.durationInSeconds); + + m_xml.endElement(); + } + } + + virtual void testCaseEnded(TestCaseStats const& testCaseStats) CATCH_OVERRIDE { + StreamingReporterBase::testCaseEnded(testCaseStats); + XmlWriter::ScopedElement e = m_xml.scopedElement("OverallResult"); + e.writeAttribute("success", testCaseStats.totals.assertions.allOk()); + + if (m_config->showDurations() == ShowDurations::Always) + e.writeAttribute("durationInSeconds", m_testCaseTimer.getElapsedSeconds()); + + m_xml.endElement(); + } + + virtual void testGroupEnded(TestGroupStats const& testGroupStats) CATCH_OVERRIDE { + StreamingReporterBase::testGroupEnded(testGroupStats); + // TODO: Check testGroupStats.aborting and act accordingly. + m_xml.scopedElement("OverallResults") + .writeAttribute("successes", testGroupStats.totals.assertions.passed) + .writeAttribute("failures", testGroupStats.totals.assertions.failed) + .writeAttribute("expectedFailures", testGroupStats.totals.assertions.failedButOk); + m_xml.endElement(); + } + + virtual void testRunEnded(TestRunStats const& testRunStats) CATCH_OVERRIDE { + StreamingReporterBase::testRunEnded(testRunStats); + m_xml.scopedElement("OverallResults") + .writeAttribute("successes", testRunStats.totals.assertions.passed) + .writeAttribute("failures", testRunStats.totals.assertions.failed) + .writeAttribute("expectedFailures", testRunStats.totals.assertions.failedButOk); + m_xml.endElement(); + } + +private: + Timer m_testCaseTimer; + XmlWriter m_xml; + int m_sectionDepth; +}; + +INTERNAL_CATCH_REGISTER_REPORTER("xml", XmlReporter) + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_junit.hpp +#define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED + +#include + +namespace Catch { + +class JunitReporter : public CumulativeReporterBase { +public: + JunitReporter(ReporterConfig const& _config) + : CumulativeReporterBase(_config) + , xml(_config.stream()) { + m_reporterPrefs.shouldRedirectStdOut = true; + } + + virtual ~JunitReporter() CATCH_OVERRIDE; + + static std::string getDescription() { + return "Reports test results in an XML format that looks like Ant's junitreport target"; + } + + virtual void noMatchingTestCases(std::string const& /*spec*/) CATCH_OVERRIDE {} + + virtual void testRunStarting(TestRunInfo const& runInfo) CATCH_OVERRIDE { + CumulativeReporterBase::testRunStarting(runInfo); + xml.startElement("testsuites"); + } + + virtual void testGroupStarting(GroupInfo const& groupInfo) CATCH_OVERRIDE { + suiteTimer.start(); + stdOutForSuite.str(""); + stdErrForSuite.str(""); + unexpectedExceptions = 0; + CumulativeReporterBase::testGroupStarting(groupInfo); + } + + virtual bool assertionEnded(AssertionStats const& assertionStats) CATCH_OVERRIDE { + if (assertionStats.assertionResult.getResultType() == ResultWas::ThrewException) + unexpectedExceptions++; + return CumulativeReporterBase::assertionEnded(assertionStats); + } + + virtual void testCaseEnded(TestCaseStats const& testCaseStats) CATCH_OVERRIDE { + stdOutForSuite << testCaseStats.stdOut; + stdErrForSuite << testCaseStats.stdErr; + CumulativeReporterBase::testCaseEnded(testCaseStats); + } + + virtual void testGroupEnded(TestGroupStats const& testGroupStats) CATCH_OVERRIDE { + double suiteTime = suiteTimer.getElapsedSeconds(); + CumulativeReporterBase::testGroupEnded(testGroupStats); + writeGroup(*m_testGroups.back(), suiteTime); + } + + virtual void testRunEndedCumulative() CATCH_OVERRIDE { + xml.endElement(); + } + + void writeGroup(TestGroupNode const& groupNode, double suiteTime) { + XmlWriter::ScopedElement e = xml.scopedElement("testsuite"); + TestGroupStats const& stats = groupNode.value; + xml.writeAttribute("name", stats.groupInfo.name); + xml.writeAttribute("errors", unexpectedExceptions); + xml.writeAttribute("failures", stats.totals.assertions.failed - unexpectedExceptions); + xml.writeAttribute("tests", stats.totals.assertions.total()); + xml.writeAttribute("hostname", "tbd"); // !TBD + if (m_config->showDurations() == ShowDurations::Never) + xml.writeAttribute("time", ""); + else + xml.writeAttribute("time", suiteTime); + xml.writeAttribute("timestamp", "tbd"); // !TBD + + // Write test cases + for (TestGroupNode::ChildNodes::const_iterator + it + = groupNode.children.begin(), + itEnd = groupNode.children.end(); + it != itEnd; + ++it) + writeTestCase(**it); + + xml.scopedElement("system-out").writeText(trim(stdOutForSuite.str()), false); + xml.scopedElement("system-err").writeText(trim(stdErrForSuite.str()), false); + } + + void writeTestCase(TestCaseNode const& testCaseNode) { + TestCaseStats const& stats = testCaseNode.value; + + // All test cases have exactly one section - which represents the + // test case itself. That section may have 0-n nested sections + assert(testCaseNode.children.size() == 1); + SectionNode const& rootSection = *testCaseNode.children.front(); + + std::string className = stats.testInfo.className; + + if (className.empty()) { + if (rootSection.childSections.empty()) + className = "global"; + } + writeSection(className, "", rootSection); + } + + void writeSection(std::string const& className, + std::string const& rootName, + SectionNode const& sectionNode) { + std::string name = trim(sectionNode.stats.sectionInfo.name); + if (!rootName.empty()) + name = rootName + "/" + name; + + if (!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty()) { + XmlWriter::ScopedElement e = xml.scopedElement("testcase"); + if (className.empty()) { + xml.writeAttribute("classname", name); + xml.writeAttribute("name", "root"); + } else { + xml.writeAttribute("classname", className); + xml.writeAttribute("name", name); + } + xml.writeAttribute("time", Catch::toString(sectionNode.stats.durationInSeconds)); + + writeAssertions(sectionNode); + + if (!sectionNode.stdOut.empty()) + xml.scopedElement("system-out").writeText(trim(sectionNode.stdOut), false); + if (!sectionNode.stdErr.empty()) + xml.scopedElement("system-err").writeText(trim(sectionNode.stdErr), false); + } + for (SectionNode::ChildSections::const_iterator + it + = sectionNode.childSections.begin(), + itEnd = sectionNode.childSections.end(); + it != itEnd; + ++it) + if (className.empty()) + writeSection(name, "", **it); + else + writeSection(className, name, **it); + } + + void writeAssertions(SectionNode const& sectionNode) { + for (SectionNode::Assertions::const_iterator + it + = sectionNode.assertions.begin(), + itEnd = sectionNode.assertions.end(); + it != itEnd; + ++it) + writeAssertion(*it); + } + void writeAssertion(AssertionStats const& stats) { + AssertionResult const& result = stats.assertionResult; + if (!result.isOk()) { + std::string elementName; + switch (result.getResultType()) { + case ResultWas::ThrewException: + case ResultWas::FatalErrorCondition: + elementName = "error"; + break; + case ResultWas::ExplicitFailure: + elementName = "failure"; + break; + case ResultWas::ExpressionFailed: + elementName = "failure"; + break; + case ResultWas::DidntThrowException: + elementName = "failure"; + break; + + // We should never see these here: + case ResultWas::Info: + case ResultWas::Warning: + case ResultWas::Ok: + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + elementName = "internalError"; + break; + } + + XmlWriter::ScopedElement e = xml.scopedElement(elementName); + + xml.writeAttribute("message", result.getExpandedExpression()); + xml.writeAttribute("type", result.getTestMacroName()); + + std::ostringstream oss; + if (!result.getMessage().empty()) + oss << result.getMessage() << "\n"; + for (std::vector::const_iterator + it + = stats.infoMessages.begin(), + itEnd = stats.infoMessages.end(); + it != itEnd; + ++it) + if (it->type == ResultWas::Info) + oss << it->message << "\n"; + + oss << "at " << result.getSourceInfo(); + xml.writeText(oss.str(), false); + } + } + + XmlWriter xml; + Timer suiteTimer; + std::ostringstream stdOutForSuite; + std::ostringstream stdErrForSuite; + unsigned int unexpectedExceptions; +}; + +INTERNAL_CATCH_REGISTER_REPORTER("junit", JunitReporter) + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_console.hpp +#define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED + +namespace Catch { + +struct ConsoleReporter : StreamingReporterBase { + ConsoleReporter(ReporterConfig const& _config) + : StreamingReporterBase(_config) + , m_headerPrinted(false) {} + + virtual ~ConsoleReporter() CATCH_OVERRIDE; + static std::string getDescription() { + return "Reports test results as plain lines of text"; + } + + virtual void noMatchingTestCases(std::string const& spec) CATCH_OVERRIDE { + stream << "No test cases matched '" << spec << "'" << std::endl; + } + + virtual void assertionStarting(AssertionInfo const&) CATCH_OVERRIDE { + } + + virtual bool assertionEnded(AssertionStats const& _assertionStats) CATCH_OVERRIDE { + AssertionResult const& result = _assertionStats.assertionResult; + + bool printInfoMessages = true; + + // Drop out if result was successful and we're not printing those + if (!m_config->includeSuccessfulResults() && result.isOk()) { + if (result.getResultType() != ResultWas::Warning) + return false; + printInfoMessages = false; + } + + lazyPrint(); + + AssertionPrinter printer(stream, _assertionStats, printInfoMessages); + printer.print(); + stream << std::endl; + return true; + } + + virtual void sectionStarting(SectionInfo const& _sectionInfo) CATCH_OVERRIDE { + m_headerPrinted = false; + StreamingReporterBase::sectionStarting(_sectionInfo); + } + virtual void sectionEnded(SectionStats const& _sectionStats) CATCH_OVERRIDE { + if (_sectionStats.missingAssertions) { + lazyPrint(); + Colour colour(Colour::ResultError); + if (m_sectionStack.size() > 1) + stream << "\nNo assertions in section"; + else + stream << "\nNo assertions in test case"; + stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; + } + if (m_headerPrinted) { + if (m_config->showDurations() == ShowDurations::Always) + stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl; + m_headerPrinted = false; + } else { + if (m_config->showDurations() == ShowDurations::Always) + stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl; + } + StreamingReporterBase::sectionEnded(_sectionStats); + } + + virtual void testCaseEnded(TestCaseStats const& _testCaseStats) CATCH_OVERRIDE { + StreamingReporterBase::testCaseEnded(_testCaseStats); + m_headerPrinted = false; + } + virtual void testGroupEnded(TestGroupStats const& _testGroupStats) CATCH_OVERRIDE { + if (currentGroupInfo.used) { + printSummaryDivider(); + stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; + printTotals(_testGroupStats.totals); + stream << "\n" << std::endl; + } + StreamingReporterBase::testGroupEnded(_testGroupStats); + } + virtual void testRunEnded(TestRunStats const& _testRunStats) CATCH_OVERRIDE { + printTotalsDivider(_testRunStats.totals); + printTotals(_testRunStats.totals); + stream << std::endl; + StreamingReporterBase::testRunEnded(_testRunStats); + } + +private: + class AssertionPrinter { + void operator=(AssertionPrinter const&); + + public: + AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) + : stream(_stream) + , stats(_stats) + , result(_stats.assertionResult) + , colour(Colour::None) + , message(result.getMessage()) + , messages(_stats.infoMessages) + , printInfoMessages(_printInfoMessages) { + switch (result.getResultType()) { + case ResultWas::Ok: + colour = Colour::Success; + passOrFail = "PASSED"; + //if( result.hasMessage() ) + if (_stats.infoMessages.size() == 1) + messageLabel = "with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "with messages"; + break; + case ResultWas::ExpressionFailed: + if (result.isOk()) { + colour = Colour::Success; + passOrFail = "FAILED - but was ok"; + } else { + colour = Colour::Error; + passOrFail = "FAILED"; + } + if (_stats.infoMessages.size() == 1) + messageLabel = "with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "with messages"; + break; + case ResultWas::ThrewException: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "due to unexpected exception with message"; + break; + case ResultWas::FatalErrorCondition: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "due to a fatal error condition"; + break; + case ResultWas::DidntThrowException: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "because no exception was thrown where one was expected"; + break; + case ResultWas::Info: + messageLabel = "info"; + break; + case ResultWas::Warning: + messageLabel = "warning"; + break; + case ResultWas::ExplicitFailure: + passOrFail = "FAILED"; + colour = Colour::Error; + if (_stats.infoMessages.size() == 1) + messageLabel = "explicitly with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "explicitly with messages"; + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + passOrFail = "** internal error **"; + colour = Colour::Error; + break; + } + } + + void print() const { + printSourceInfo(); + if (stats.totals.assertions.total() > 0) { + if (result.isOk()) + stream << "\n"; + printResultType(); + printOriginalExpression(); + printReconstructedExpression(); + } else { + stream << "\n"; + } + printMessage(); + } + + private: + void printResultType() const { + if (!passOrFail.empty()) { + Colour colourGuard(colour); + stream << passOrFail << ":\n"; + } + } + void printOriginalExpression() const { + if (result.hasExpression()) { + Colour colourGuard(Colour::OriginalExpression); + stream << " "; + stream << result.getExpressionInMacro(); + stream << "\n"; + } + } + void printReconstructedExpression() const { + if (result.hasExpandedExpression()) { + stream << "with expansion:\n"; + Colour colourGuard(Colour::ReconstructedExpression); + stream << Text(result.getExpandedExpression(), TextAttributes().setIndent(2)) << "\n"; + } + } + void printMessage() const { + if (!messageLabel.empty()) + stream << messageLabel << ":" + << "\n"; + for (std::vector::const_iterator it = messages.begin(), itEnd = messages.end(); + it != itEnd; + ++it) { + // If this assertion is a warning ignore any INFO messages + if (printInfoMessages || it->type != ResultWas::Info) + stream << Text(it->message, TextAttributes().setIndent(2)) << "\n"; + } + } + void printSourceInfo() const { + Colour colourGuard(Colour::FileName); + stream << result.getSourceInfo() << ": "; + } + + std::ostream& stream; + AssertionStats const& stats; + AssertionResult const& result; + Colour::Code colour; + std::string passOrFail; + std::string messageLabel; + std::string message; + std::vector messages; + bool printInfoMessages; + }; + + void lazyPrint() { + + if (!currentTestRunInfo.used) + lazyPrintRunInfo(); + if (!currentGroupInfo.used) + lazyPrintGroupInfo(); + + if (!m_headerPrinted) { + printTestCaseAndSectionHeader(); + m_headerPrinted = true; + } + } + void lazyPrintRunInfo() { + stream << "\n" << getLineOfChars<'~'>() << "\n"; + Colour colour(Colour::SecondaryText); + stream << currentTestRunInfo->name + << " is a Catch v" << libraryVersion << " host application.\n" + << "Run with -? for options\n\n"; + + if (m_config->rngSeed() != 0) + stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; + + currentTestRunInfo.used = true; + } + void lazyPrintGroupInfo() { + if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) { + printClosedHeader("Group: " + currentGroupInfo->name); + currentGroupInfo.used = true; + } + } + void printTestCaseAndSectionHeader() { + assert(!m_sectionStack.empty()); + printOpenHeader(currentTestCaseInfo->name); + + if (m_sectionStack.size() > 1) { + Colour colourGuard(Colour::Headers); + + std::vector::const_iterator + it + = m_sectionStack.begin() + 1, // Skip first section (test case) + itEnd = m_sectionStack.end(); + for (; it != itEnd; ++it) + printHeaderString(it->name, 2); + } + + SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; + + if (!lineInfo.empty()) { + stream << getLineOfChars<'-'>() << "\n"; + Colour colourGuard(Colour::FileName); + stream << lineInfo << "\n"; + } + stream << getLineOfChars<'.'>() << "\n" << std::endl; + } + + void printClosedHeader(std::string const& _name) { + printOpenHeader(_name); + stream << getLineOfChars<'.'>() << "\n"; + } + void printOpenHeader(std::string const& _name) { + stream << getLineOfChars<'-'>() << "\n"; + { + Colour colourGuard(Colour::Headers); + printHeaderString(_name); + } + } + + // if string has a : in first line will set indent to follow it on + // subsequent lines + void printHeaderString(std::string const& _string, std::size_t indent = 0) { + std::size_t i = _string.find(": "); + if (i != std::string::npos) + i += 2; + else + i = 0; + stream << Text(_string, TextAttributes() + .setIndent(indent + i) + .setInitialIndent(indent)) + << "\n"; + } + + struct SummaryColumn { + + SummaryColumn(std::string const& _label, Colour::Code _colour) + : label(_label) + , colour(_colour) {} + SummaryColumn addRow(std::size_t count) { + std::ostringstream oss; + oss << count; + std::string row = oss.str(); + for (std::vector::iterator it = rows.begin(); it != rows.end(); ++it) { + while (it->size() < row.size()) + *it = " " + *it; + while (it->size() > row.size()) + row = " " + row; + } + rows.push_back(row); + return *this; + } + + std::string label; + Colour::Code colour; + std::vector rows; + }; + + void printTotals(Totals const& totals) { + if (totals.testCases.total() == 0) { + stream << Colour(Colour::Warning) << "No tests ran\n"; + } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) { + stream << Colour(Colour::ResultSuccess) << "All tests passed"; + stream << " (" + << pluralise(totals.assertions.passed, "assertion") << " in " + << pluralise(totals.testCases.passed, "test case") << ")" + << "\n"; + } else { + + std::vector columns; + columns.push_back(SummaryColumn("", Colour::None) + .addRow(totals.testCases.total()) + .addRow(totals.assertions.total())); + columns.push_back(SummaryColumn("passed", Colour::Success) + .addRow(totals.testCases.passed) + .addRow(totals.assertions.passed)); + columns.push_back(SummaryColumn("failed", Colour::ResultError) + .addRow(totals.testCases.failed) + .addRow(totals.assertions.failed)); + columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure) + .addRow(totals.testCases.failedButOk) + .addRow(totals.assertions.failedButOk)); + + printSummaryRow("test cases", columns, 0); + printSummaryRow("assertions", columns, 1); + } + } + void printSummaryRow(std::string const& label, std::vector const& cols, std::size_t row) { + for (std::vector::const_iterator it = cols.begin(); it != cols.end(); ++it) { + std::string value = it->rows[row]; + if (it->label.empty()) { + stream << label << ": "; + if (value != "0") + stream << value; + else + stream << Colour(Colour::Warning) << "- none -"; + } else if (value != "0") { + stream << Colour(Colour::LightGrey) << " | "; + stream << Colour(it->colour) + << value << " " << it->label; + } + } + stream << "\n"; + } + + static std::size_t makeRatio(std::size_t number, std::size_t total) { + std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0; + return (ratio == 0 && number > 0) ? 1 : ratio; + } + static std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) { + if (i > j && i > k) + return i; + else if (j > k) + return j; + else + return k; + } + + void printTotalsDivider(Totals const& totals) { + if (totals.testCases.total() > 0) { + std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total()); + std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total()); + std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total()); + while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1) + findMax(failedRatio, failedButOkRatio, passedRatio)++; + while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1) + findMax(failedRatio, failedButOkRatio, passedRatio)--; + + stream << Colour(Colour::Error) << std::string(failedRatio, '='); + stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '='); + if (totals.testCases.allPassed()) + stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '='); + else + stream << Colour(Colour::Success) << std::string(passedRatio, '='); + } else { + stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '='); + } + stream << "\n"; + } + void printSummaryDivider() { + stream << getLineOfChars<'-'>() << "\n"; + } + +private: + bool m_headerPrinted; +}; + +INTERNAL_CATCH_REGISTER_REPORTER("console", ConsoleReporter) + +} // end namespace Catch + +// #included from: ../reporters/catch_reporter_compact.hpp +#define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED + +namespace Catch { + +struct CompactReporter : StreamingReporterBase { + + CompactReporter(ReporterConfig const& _config) + : StreamingReporterBase(_config) {} + + virtual ~CompactReporter(); + + static std::string getDescription() { + return "Reports test results on a single line, suitable for IDEs"; + } + + virtual ReporterPreferences getPreferences() const { + ReporterPreferences prefs; + prefs.shouldRedirectStdOut = false; + return prefs; + } + + virtual void noMatchingTestCases(std::string const& spec) { + stream << "No test cases matched '" << spec << "'" << std::endl; + } + + virtual void assertionStarting(AssertionInfo const&) { + } + + virtual bool assertionEnded(AssertionStats const& _assertionStats) { + AssertionResult const& result = _assertionStats.assertionResult; + + bool printInfoMessages = true; + + // Drop out if result was successful and we're not printing those + if (!m_config->includeSuccessfulResults() && result.isOk()) { + if (result.getResultType() != ResultWas::Warning) + return false; + printInfoMessages = false; + } + + AssertionPrinter printer(stream, _assertionStats, printInfoMessages); + printer.print(); + + stream << std::endl; + return true; + } + + virtual void testRunEnded(TestRunStats const& _testRunStats) { + printTotals(_testRunStats.totals); + stream << "\n" << std::endl; + StreamingReporterBase::testRunEnded(_testRunStats); + } + +private: + class AssertionPrinter { + void operator=(AssertionPrinter const&); + + public: + AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) + : stream(_stream) + , stats(_stats) + , result(_stats.assertionResult) + , messages(_stats.infoMessages) + , itMessage(_stats.infoMessages.begin()) + , printInfoMessages(_printInfoMessages) {} + + void print() { + printSourceInfo(); + + itMessage = messages.begin(); + + switch (result.getResultType()) { + case ResultWas::Ok: + printResultType(Colour::ResultSuccess, passedString()); + printOriginalExpression(); + printReconstructedExpression(); + if (!result.hasExpression()) + printRemainingMessages(Colour::None); + else + printRemainingMessages(); + break; + case ResultWas::ExpressionFailed: + if (result.isOk()) + printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok")); + else + printResultType(Colour::Error, failedString()); + printOriginalExpression(); + printReconstructedExpression(); + printRemainingMessages(); + break; + case ResultWas::ThrewException: + printResultType(Colour::Error, failedString()); + printIssue("unexpected exception with message:"); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::FatalErrorCondition: + printResultType(Colour::Error, failedString()); + printIssue("fatal error condition with message:"); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::DidntThrowException: + printResultType(Colour::Error, failedString()); + printIssue("expected exception, got none"); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::Info: + printResultType(Colour::None, "info"); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::Warning: + printResultType(Colour::None, "warning"); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::ExplicitFailure: + printResultType(Colour::Error, failedString()); + printIssue("explicitly"); + printRemainingMessages(Colour::None); + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + printResultType(Colour::Error, "** internal error **"); + break; + } + } + + private: + // Colour::LightGrey + + static Colour::Code dimColour() { return Colour::FileName; } + +#ifdef CATCH_PLATFORM_MAC + static const char* failedString() { return "FAILED"; } + static const char* passedString() { return "PASSED"; } +#else + static const char* failedString() { return "failed"; } + static const char* passedString() { return "passed"; } +#endif + + void printSourceInfo() const { + Colour colourGuard(Colour::FileName); + stream << result.getSourceInfo() << ":"; + } + + void printResultType(Colour::Code colour, std::string passOrFail) const { + if (!passOrFail.empty()) { + { + Colour colourGuard(colour); + stream << " " << passOrFail; + } + stream << ":"; + } + } + + void printIssue(std::string issue) const { + stream << " " << issue; + } + + void printExpressionWas() { + if (result.hasExpression()) { + stream << ";"; + { + Colour colour(dimColour()); + stream << " expression was:"; + } + printOriginalExpression(); + } + } + + void printOriginalExpression() const { + if (result.hasExpression()) { + stream << " " << result.getExpression(); + } + } + + void printReconstructedExpression() const { + if (result.hasExpandedExpression()) { + { + Colour colour(dimColour()); + stream << " for: "; + } + stream << result.getExpandedExpression(); + } + } + + void printMessage() { + if (itMessage != messages.end()) { + stream << " '" << itMessage->message << "'"; + ++itMessage; + } + } + + void printRemainingMessages(Colour::Code colour = dimColour()) { + if (itMessage == messages.end()) + return; + + // using messages.end() directly yields compilation error: + std::vector::const_iterator itEnd = messages.end(); + const std::size_t N = static_cast(std::distance(itMessage, itEnd)); + + { + Colour colourGuard(colour); + stream << " with " << pluralise(N, "message") << ":"; + } + + for (; itMessage != itEnd;) { + // If this assertion is a warning ignore any INFO messages + if (printInfoMessages || itMessage->type != ResultWas::Info) { + stream << " '" << itMessage->message << "'"; + if (++itMessage != itEnd) { + Colour colourGuard(dimColour()); + stream << " and"; + } + } + } + } + + private: + std::ostream& stream; + AssertionStats const& stats; + AssertionResult const& result; + std::vector messages; + std::vector::const_iterator itMessage; + bool printInfoMessages; + }; + + // Colour, message variants: + // - white: No tests ran. + // - red: Failed [both/all] N test cases, failed [both/all] M assertions. + // - white: Passed [both/all] N test cases (no assertions). + // - red: Failed N tests cases, failed M assertions. + // - green: Passed [both/all] N tests cases with M assertions. + + std::string bothOrAll(std::size_t count) const { + return count == 1 ? "" : count == 2 ? "both " : "all "; + } + + void printTotals(const Totals& totals) const { + if (totals.testCases.total() == 0) { + stream << "No tests ran."; + } else if (totals.testCases.failed == totals.testCases.total()) { + Colour colour(Colour::ResultError); + const std::string qualify_assertions_failed = totals.assertions.failed == totals.assertions.total() ? bothOrAll(totals.assertions.failed) : ""; + stream << "Failed " << bothOrAll(totals.testCases.failed) + << pluralise(totals.testCases.failed, "test case") << ", " + "failed " + << qualify_assertions_failed << pluralise(totals.assertions.failed, "assertion") << "."; + } else if (totals.assertions.total() == 0) { + stream << "Passed " << bothOrAll(totals.testCases.total()) + << pluralise(totals.testCases.total(), "test case") + << " (no assertions)."; + } else if (totals.assertions.failed) { + Colour colour(Colour::ResultError); + stream << "Failed " << pluralise(totals.testCases.failed, "test case") << ", " + "failed " + << pluralise(totals.assertions.failed, "assertion") << "."; + } else { + Colour colour(Colour::ResultSuccess); + stream << "Passed " << bothOrAll(totals.testCases.passed) + << pluralise(totals.testCases.passed, "test case") << " with " << pluralise(totals.assertions.passed, "assertion") << "."; + } + } +}; + +INTERNAL_CATCH_REGISTER_REPORTER("compact", CompactReporter) + +} // end namespace Catch + +namespace Catch { +// These are all here to avoid warnings about not having any out of line +// virtual methods +NonCopyable::~NonCopyable() {} +IShared::~IShared() {} +IStream::~IStream() CATCH_NOEXCEPT {} +FileStream::~FileStream() CATCH_NOEXCEPT {} +CoutStream::~CoutStream() CATCH_NOEXCEPT {} +DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {} +StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {} +IContext::~IContext() {} +IResultCapture::~IResultCapture() {} +ITestCase::~ITestCase() {} +ITestCaseRegistry::~ITestCaseRegistry() {} +IRegistryHub::~IRegistryHub() {} +IMutableRegistryHub::~IMutableRegistryHub() {} +IExceptionTranslator::~IExceptionTranslator() {} +IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {} +IReporter::~IReporter() {} +IReporterFactory::~IReporterFactory() {} +IReporterRegistry::~IReporterRegistry() {} +IStreamingReporter::~IStreamingReporter() {} +AssertionStats::~AssertionStats() {} +SectionStats::~SectionStats() {} +TestCaseStats::~TestCaseStats() {} +TestGroupStats::~TestGroupStats() {} +TestRunStats::~TestRunStats() {} +CumulativeReporterBase::SectionNode::~SectionNode() {} +CumulativeReporterBase::~CumulativeReporterBase() {} + +StreamingReporterBase::~StreamingReporterBase() {} +ConsoleReporter::~ConsoleReporter() {} +CompactReporter::~CompactReporter() {} +IRunner::~IRunner() {} +IMutableContext::~IMutableContext() {} +IConfig::~IConfig() {} +XmlReporter::~XmlReporter() {} +JunitReporter::~JunitReporter() {} +TestRegistry::~TestRegistry() {} +FreeFunctionTestCase::~FreeFunctionTestCase() {} +IGeneratorInfo::~IGeneratorInfo() {} +IGeneratorsForTest::~IGeneratorsForTest() {} +WildcardPattern::~WildcardPattern() {} +TestSpec::Pattern::~Pattern() {} +TestSpec::NamePattern::~NamePattern() {} +TestSpec::TagPattern::~TagPattern() {} +TestSpec::ExcludedPattern::~ExcludedPattern() {} + +Matchers::Impl::StdString::Equals::~Equals() {} +Matchers::Impl::StdString::Contains::~Contains() {} +Matchers::Impl::StdString::StartsWith::~StartsWith() {} +Matchers::Impl::StdString::EndsWith::~EndsWith() {} + +void Config::dummy() {} + +namespace TestCaseTracking { + ITracker::~ITracker() {} + TrackerBase::~TrackerBase() {} + SectionTracker::~SectionTracker() {} + IndexTracker::~IndexTracker() {} +} +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#endif + +#ifdef CATCH_CONFIG_MAIN +// #included from: internal/catch_default_main.hpp +#define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED + +#ifndef __OBJC__ + +// Standard C/C++ main entry point +int main(int argc, char* argv[]) { + return Catch::Session().run(argc, argv); +} + +#else // __OBJC__ + +// Objective-C entry point +int main(int argc, char* const argv[]) { +#if !CATCH_ARC_ENABLED + NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; +#endif + + Catch::registerTestMethods(); + int result = Catch::Session().run(argc, (char* const*)argv); + +#if !CATCH_ARC_ENABLED + [pool drain]; +#endif + + return result; +} + +#endif // __OBJC__ + +#endif + +#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED +#undef CLARA_CONFIG_MAIN +#endif + +////// + +// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ +#ifdef CATCH_CONFIG_PREFIX_ALL + +#define CATCH_REQUIRE(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE") +#define CATCH_REQUIRE_FALSE(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE") + +#define CATCH_REQUIRE_THROWS(expr) INTERNAL_CATCH_THROWS(expr, Catch::ResultDisposition::Normal, "", "CATCH_REQUIRE_THROWS") +#define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) INTERNAL_CATCH_THROWS_AS(expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS") +#define CATCH_REQUIRE_THROWS_WITH(expr, matcher) INTERNAL_CATCH_THROWS(expr, Catch::ResultDisposition::Normal, matcher, "CATCH_REQUIRE_THROWS_WITH") +#define CATCH_REQUIRE_NOTHROW(expr) INTERNAL_CATCH_NO_THROW(expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW") + +#define CATCH_CHECK(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK") +#define CATCH_CHECK_FALSE(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE") +#define CATCH_CHECKED_IF(expr) INTERNAL_CATCH_IF(expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF") +#define CATCH_CHECKED_ELSE(expr) INTERNAL_CATCH_ELSE(expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE") +#define CATCH_CHECK_NOFAIL(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL") + +#define CATCH_CHECK_THROWS(expr) INTERNAL_CATCH_THROWS(expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS") +#define CATCH_CHECK_THROWS_AS(expr, exceptionType) INTERNAL_CATCH_THROWS_AS(expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS") +#define CATCH_CHECK_THROWS_WITH(expr, matcher) INTERNAL_CATCH_THROWS(expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CATCH_CHECK_THROWS_WITH") +#define CATCH_CHECK_NOTHROW(expr) INTERNAL_CATCH_NO_THROW(expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW") + +#define CHECK_THAT(arg, matcher) INTERNAL_CHECK_THAT(arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT") +#define CATCH_REQUIRE_THAT(arg, matcher) INTERNAL_CHECK_THAT(arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT") + +#define CATCH_INFO(msg) INTERNAL_CATCH_INFO(msg, "CATCH_INFO") +#define CATCH_WARN(msg) INTERNAL_CATCH_MSG(Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg) +#define CATCH_SCOPED_INFO(msg) INTERNAL_CATCH_INFO(msg, "CATCH_INFO") +#define CATCH_CAPTURE(msg) INTERNAL_CATCH_INFO(#msg " := " << msg, "CATCH_CAPTURE") +#define CATCH_SCOPED_CAPTURE(msg) INTERNAL_CATCH_INFO(#msg " := " << msg, "CATCH_CAPTURE") + +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define CATCH_TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__) +#define CATCH_TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__) +#define CATCH_METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__) +#define CATCH_REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__) +#define CATCH_SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__) +#define CATCH_FAIL(...) INTERNAL_CATCH_MSG(Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__) +#define CATCH_SUCCEED(...) INTERNAL_CATCH_MSG(Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__) +#else +#define CATCH_TEST_CASE(name, description) INTERNAL_CATCH_TESTCASE(name, description) +#define CATCH_TEST_CASE_METHOD(className, name, description) INTERNAL_CATCH_TEST_CASE_METHOD(className, name, description) +#define CATCH_METHOD_AS_TEST_CASE(method, name, description) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, name, description) +#define CATCH_REGISTER_TEST_CASE(function, name, description) INTERNAL_CATCH_REGISTER_TESTCASE(function, name, description) +#define CATCH_SECTION(name, description) INTERNAL_CATCH_SECTION(name, description) +#define CATCH_FAIL(msg) INTERNAL_CATCH_MSG(Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg) +#define CATCH_SUCCEED(msg) INTERNAL_CATCH_MSG(Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg) +#endif +#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE("", "") + +#define CATCH_REGISTER_REPORTER(name, reporterType) INTERNAL_CATCH_REGISTER_REPORTER(name, reporterType) +#define CATCH_REGISTER_LEGACY_REPORTER(name, reporterType) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER(name, reporterType) + +#define CATCH_GENERATE(expr) INTERNAL_CATCH_GENERATE(expr) + +// "BDD-style" convenience wrappers +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define CATCH_SCENARIO(...) CATCH_TEST_CASE("Scenario: " __VA_ARGS__) +#define CATCH_SCENARIO_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__) +#else +#define CATCH_SCENARIO(name, tags) CATCH_TEST_CASE("Scenario: " name, tags) +#define CATCH_SCENARIO_METHOD(className, name, tags) INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " name, tags) +#endif +#define CATCH_GIVEN(desc) CATCH_SECTION(std::string("Given: ") + desc, "") +#define CATCH_WHEN(desc) CATCH_SECTION(std::string(" When: ") + desc, "") +#define CATCH_AND_WHEN(desc) CATCH_SECTION(std::string(" And: ") + desc, "") +#define CATCH_THEN(desc) CATCH_SECTION(std::string(" Then: ") + desc, "") +#define CATCH_AND_THEN(desc) CATCH_SECTION(std::string(" And: ") + desc, "") + +// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required +#else + +#define REQUIRE(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::Normal, "REQUIRE") +#define REQUIRE_FALSE(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE") + +#define REQUIRE_THROWS(expr) INTERNAL_CATCH_THROWS(expr, Catch::ResultDisposition::Normal, "", "REQUIRE_THROWS") +#define REQUIRE_THROWS_AS(expr, exceptionType) INTERNAL_CATCH_THROWS_AS(expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS") +#define REQUIRE_THROWS_WITH(expr, matcher) INTERNAL_CATCH_THROWS(expr, Catch::ResultDisposition::Normal, matcher, "REQUIRE_THROWS_WITH") +#define REQUIRE_NOTHROW(expr) INTERNAL_CATCH_NO_THROW(expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW") + +#define CHECK(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK") +#define CHECK_FALSE(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE") +#define CHECKED_IF(expr) INTERNAL_CATCH_IF(expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF") +#define CHECKED_ELSE(expr) INTERNAL_CATCH_ELSE(expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE") +#define CHECK_NOFAIL(expr) INTERNAL_CATCH_TEST(expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL") + +#define CHECK_THROWS(expr) INTERNAL_CATCH_THROWS(expr, Catch::ResultDisposition::ContinueOnFailure, "", "CHECK_THROWS") +#define CHECK_THROWS_AS(expr, exceptionType) INTERNAL_CATCH_THROWS_AS(expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS") +#define CHECK_THROWS_WITH(expr, matcher) INTERNAL_CATCH_THROWS(expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CHECK_THROWS_WITH") +#define CHECK_NOTHROW(expr) INTERNAL_CATCH_NO_THROW(expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW") + +#define CHECK_THAT(arg, matcher) INTERNAL_CHECK_THAT(arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT") +#define REQUIRE_THAT(arg, matcher) INTERNAL_CHECK_THAT(arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT") + +#define INFO(msg) INTERNAL_CATCH_INFO(msg, "INFO") +#define WARN(msg) INTERNAL_CATCH_MSG(Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg) +#define SCOPED_INFO(msg) INTERNAL_CATCH_INFO(msg, "INFO") +#define CAPTURE(msg) INTERNAL_CATCH_INFO(#msg " := " << msg, "CAPTURE") +#define SCOPED_CAPTURE(msg) INTERNAL_CATCH_INFO(#msg " := " << msg, "CAPTURE") + +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__) +#define TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__) +#define METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__) +#define REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__) +#define SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__) +#define FAIL(...) INTERNAL_CATCH_MSG(Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__) +#define SUCCEED(...) INTERNAL_CATCH_MSG(Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__) +#else +#define TEST_CASE(name, description) INTERNAL_CATCH_TESTCASE(name, description) +#define TEST_CASE_METHOD(className, name, description) INTERNAL_CATCH_TEST_CASE_METHOD(className, name, description) +#define METHOD_AS_TEST_CASE(method, name, description) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, name, description) +#define REGISTER_TEST_CASE(method, name, description) INTERNAL_CATCH_REGISTER_TESTCASE(method, name, description) +#define SECTION(name, description) INTERNAL_CATCH_SECTION(name, description) +#define FAIL(msg) INTERNAL_CATCH_MSG(Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg) +#define SUCCEED(msg) INTERNAL_CATCH_MSG(Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg) +#endif +#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE("", "") + +#define REGISTER_REPORTER(name, reporterType) INTERNAL_CATCH_REGISTER_REPORTER(name, reporterType) +#define REGISTER_LEGACY_REPORTER(name, reporterType) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER(name, reporterType) + +#define GENERATE(expr) INTERNAL_CATCH_GENERATE(expr) + +#endif + +#define CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) + +// "BDD-style" convenience wrappers +#ifdef CATCH_CONFIG_VARIADIC_MACROS +#define SCENARIO(...) TEST_CASE("Scenario: " __VA_ARGS__) +#define SCENARIO_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__) +#else +#define SCENARIO(name, tags) TEST_CASE("Scenario: " name, tags) +#define SCENARIO_METHOD(className, name, tags) INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " name, tags) +#endif +#define GIVEN(desc) SECTION(std::string(" Given: ") + desc, "") +#define WHEN(desc) SECTION(std::string(" When: ") + desc, "") +#define AND_WHEN(desc) SECTION(std::string("And when: ") + desc, "") +#define THEN(desc) SECTION(std::string(" Then: ") + desc, "") +#define AND_THEN(desc) SECTION(std::string(" And: ") + desc, "") + +using Catch::Detail::Approx; + +#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED diff --git a/externals/easyloggingpp/LICENCE b/externals/easyloggingpp/LICENCE new file mode 100644 index 0000000..6baa0e2 --- /dev/null +++ b/externals/easyloggingpp/LICENCE @@ -0,0 +1,24 @@ +The MIT License (MIT) + +Copyright (c) 2015 muflihun.com + +http://github.com/easylogging/ +http://easylogging.muflihun.com +http://muflihun.com + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/externals/easyloggingpp/easylogging++.h b/externals/easyloggingpp/easylogging++.h new file mode 100644 index 0000000..f9a67fe --- /dev/null +++ b/externals/easyloggingpp/easylogging++.h @@ -0,0 +1,6663 @@ +// +// Easylogging++ v9.80 +// Single-header only, cross-platform logging library for C++ applications +// +// Copyright (c) 2015 muflihun.com +// +// This library is released under the MIT Licence. +// http://easylogging.muflihun.com/licence.php +// +// easylogging@muflihun.com +// +// https://github.com/easylogging/easyloggingpp +// http://easylogging.muflihun.com +// http://muflihun.com +// +#ifndef EASYLOGGINGPP_H +#define EASYLOGGINGPP_H +// Compilers and C++0x/C++11 Evaluation +#if defined(__GNUC__) +# define ELPP_COMPILER_GCC 1 +# define ELPP_GCC_VERSION (__GNUC__ * 10000 \ + + __GNUC_MINOR__ * 100 \ + + __GNUC_PATCHLEVEL__) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ELPP_CXX0X 1 +# elif(ELPP_GCC_VERSION >= 40801) +# define ELPP_CXX11 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +#endif // defined(__GNUC__) +// Visual C++ +#if defined(_MSC_VER) +# define ELPP_COMPILER_MSVC 1 +# define ELPP_CRT_DBG_WARNINGS 1 +# if (_MSC_VER == 1600) +# define ELPP_CXX0X 1 +# elif(_MSC_VER >= 1700) +# define ELPP_CXX11 1 +# endif // (_MSC_VER == 1600) +#endif // defined(_MSC_VER) +// Clang++ +#if defined(__clang__) && (__clang__ == 1) +# define ELPP_COMPILER_CLANG 1 +# define ELPP_CLANG_VERSION (__clang_major__ * 10000 \ + + __clang_minor__ * 100 \ + + __clang_patchlevel__) +# if (ELPP_CLANG_VERSION >= 30300) +# define ELPP_CXX11 1 +# endif // (ELPP_CLANG_VERSION >= 30300) +#endif // defined(__clang__) && (__clang__ == 1) +// MinGW +#if defined(__MINGW32__) || defined(__MINGW64__) +# define ELPP_MINGW 1 +#endif // defined(__MINGW32__) || defined(__MINGW64__) +// Cygwin +#if defined(__CYGWIN__) && (__CYGWIN__ == 1) +# define ELPP_CYGWIN 1 +#endif // defined(__CYGWIN__) && (__CYGWIN__ == 1) +// Intel C++ +#if defined(__INTEL_COMPILER) +# define ELPP_COMPILER_INTEL 1 +#endif +// Operating System Evaluation +// Windows +#if defined(_WIN32) || defined(_WIN64) +# define ELPP_OS_WINDOWS 1 +#endif // defined(_WIN32) || defined(_WIN64) +// Linux +#if (defined(__linux) || defined(__linux__)) +# define ELPP_OS_LINUX 1 +#endif // (defined(__linux) || defined(__linux__)) +// Mac +#if defined(__APPLE__) +# define ELPP_OS_MAC 1 +#endif // defined(__APPLE__) +// FreeBSD +#if defined(__FreeBSD__) +# define ELPP_OS_FREEBSD 1 +#endif +// Solaris +#if defined(__sun) +# define ELPP_OS_SOLARIS 1 +#endif +// Unix +#if ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_SOLARIS) && (!ELPP_OS_WINDOWS)) +# define ELPP_OS_UNIX 1 +#endif // ((ELPP_OS_LINUX || ELPP_OS_MAC || ELPP_OS_FREEBSD || ELPP_OS_SOLARIS) && (!ELPP_OS_WINDOWS)) +// Android +#if defined(__ANDROID__) +# define ELPP_OS_ANDROID 1 +#endif // defined(__ANDROID__) +// Evaluating Cygwin as *nix OS +#if !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN +# undef ELPP_OS_UNIX +# undef ELPP_OS_LINUX +# define ELPP_OS_UNIX 1 +# define ELPP_OS_LINUX 1 +#endif // !ELPP_OS_UNIX && !ELPP_OS_WINDOWS && ELPP_CYGWIN +#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_INFO) +# define ELPP_INTERNAL_DEBUGGING_OUT_INFO std::cout +#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) +#if !defined(ELPP_INTERNAL_DEBUGGING_OUT_ERROR) +# define ELPP_INTERNAL_DEBUGGING_OUT_ERROR std::cerr +#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) +#if !defined(ELPP_INTERNAL_DEBUGGING_ENDL) +# define ELPP_INTERNAL_DEBUGGING_ENDL std::endl +#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) +#if !defined(ELPP_INTERNAL_DEBUGGING_MSG) +# define ELPP_INTERNAL_DEBUGGING_MSG(msg) msg +#endif // !defined(ELPP_INTERNAL_DEBUGGING_OUT) +// Internal Assertions and errors +#if !defined(ELPP_DISABLE_ASSERT) +# if (defined(ELPP_DEBUG_ASSERT_FAILURE)) +# define ELPP_ASSERT(expr, msg) if (!(expr)) { \ + std::stringstream internalInfoStream; internalInfoStream << msg; \ + ELPP_INTERNAL_DEBUGGING_OUT_ERROR \ + << "EASYLOGGING++ ASSERTION FAILED (LINE: " << __LINE__ << ") [" #expr << "] WITH MESSAGE \"" \ + << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" << ELPP_INTERNAL_DEBUGGING_ENDL; base::utils::abort(1, \ + "ELPP Assertion failure, please define ELPP_DEBUG_ASSERT_FAILURE"); } +# else +# define ELPP_ASSERT(expr, msg) if (!(expr)) { \ + std::stringstream internalInfoStream; internalInfoStream << msg; \ + ELPP_INTERNAL_DEBUGGING_OUT_ERROR\ + << "ASSERTION FAILURE FROM EASYLOGGING++ (LINE: " \ + << __LINE__ << ") [" #expr << "] WITH MESSAGE \"" << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << "\"" \ + << ELPP_INTERNAL_DEBUGGING_ENDL; } +# endif // (defined(ELPP_DEBUG_ASSERT_FAILURE)) +#else +# define ELPP_ASSERT(x, y) +#endif //(!defined(ELPP_DISABLE_ASSERT) +#if ELPP_COMPILER_MSVC +# define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \ + { char buff[256]; strerror_s(buff, 256, errno); \ + ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << buff << " [" << errno << "]";} (void)0 +#else +# define ELPP_INTERNAL_DEBUGGING_WRITE_PERROR \ + ELPP_INTERNAL_DEBUGGING_OUT_ERROR << ": " << strerror(errno) << " [" << errno << "]"; (void)0 +#endif // ELPP_COMPILER_MSVC +#if defined(ELPP_DEBUG_ERRORS) +# if !defined(ELPP_INTERNAL_ERROR) +# define ELPP_INTERNAL_ERROR(msg, pe) { \ + std::stringstream internalInfoStream; internalInfoStream << " " << msg; \ + ELPP_INTERNAL_DEBUGGING_OUT_ERROR \ + << "ERROR FROM EASYLOGGING++ (LINE: " << __LINE__ << ") " \ + << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) << ELPP_INTERNAL_DEBUGGING_ENDL; \ + if (pe) { ELPP_INTERNAL_DEBUGGING_OUT_ERROR << " "; ELPP_INTERNAL_DEBUGGING_WRITE_PERROR; }} (void)0 +# endif +#else +# undef ELPP_INTERNAL_INFO +# define ELPP_INTERNAL_ERROR(msg, pe) +#endif // defined(ELPP_DEBUG_ERRORS) +#if (defined(ELPP_DEBUG_INFO)) +# if !(defined(ELPP_INTERNAL_INFO_LEVEL)) +# define ELPP_INTERNAL_INFO_LEVEL 9 +# endif // !(defined(ELPP_INTERNAL_INFO_LEVEL)) +# if !defined(ELPP_INTERNAL_INFO) +# define ELPP_INTERNAL_INFO(lvl, msg) { if (lvl <= ELPP_INTERNAL_INFO_LEVEL) { \ + std::stringstream internalInfoStream; internalInfoStream << " " << msg; \ + ELPP_INTERNAL_DEBUGGING_OUT_INFO << ELPP_INTERNAL_DEBUGGING_MSG(internalInfoStream.str()) \ + << ELPP_INTERNAL_DEBUGGING_ENDL; }} +# endif +#else +# undef ELPP_INTERNAL_INFO +# define ELPP_INTERNAL_INFO(lvl, msg) +#endif // (defined(ELPP_DEBUG_INFO)) +#if defined(ELPP_STACKTRACE_ON_CRASH) +# if (ELPP_COMPILER_GCC && !ELPP_MINGW) +# define ELPP_STACKTRACE 1 +# else +# if ELPP_COMPILER_MSVC +# pragma message("Stack trace not available for this compiler") +# else +# warning "Stack trace not available for this compiler"; +# endif // ELPP_COMPILER_MSVC +# endif // ELPP_COMPILER_GCC +#endif // (defined(ELPP_STACKTRACE_ON_CRASH)) +// Miscellaneous macros +#define ELPP_UNUSED(x) (void)x +#if ELPP_OS_UNIX +// Log file permissions for unix-based systems +# define ELPP_LOG_PERMS S_IRUSR | S_IWUSR | S_IXUSR | S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IXOTH +#endif // ELPP_OS_UNIX +#if defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC +# if defined(ELPP_EXPORT_SYMBOLS) +# define ELPP_EXPORT __declspec(dllexport) +# else +# define ELPP_EXPORT __declspec(dllimport) +# endif // defined(ELPP_EXPORT_SYMBOLS) +#else +# define ELPP_EXPORT +#endif // defined(ELPP_AS_DLL) && ELPP_COMPILER_MSVC +// Some special functions that are VC++ specific +#undef STRTOK +#undef STRERROR +#undef STRCAT +#undef STRCPY +#if ELPP_CRT_DBG_WARNINGS +# define STRTOK(a, b, c) strtok_s(a, b, c) +# define STRERROR(a, b, c) strerror_s(a, b, c) +# define STRCAT(a, b, len) strcat_s(a, len, b) +# define STRCPY(a, b, len) strcpy_s(a, len, b) +#else +# define STRTOK(a, b, c) strtok(a, b) +# define STRERROR(a, b, c) strerror(c) +# define STRCAT(a, b, len) strcat(a, b) +# define STRCPY(a, b, len) strcpy(a, b) +#endif +// Compiler specific support evaluations +#if (!ELPP_MINGW && !ELPP_COMPILER_CLANG) || defined(ELPP_FORCE_USE_STD_THREAD) +# define ELPP_USE_STD_THREADING 1 +#endif // (!ELPP_MINGW && !ELPP_COMPILER_CLANG) || defined(ELPP_FORCE_USE_STD_THREAD) +#undef ELPP_FINAL +#if ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702) +# define ELPP_FINAL +#else +# define ELPP_FINAL final +#endif // ELPP_COMPILER_INTEL || (ELPP_GCC_VERSION < 40702) +#if defined(ELPP_EXPERIMENTAL_ASYNC) +# define ELPP_ASYNC_LOGGING 1 +#else +# define ELPP_ASYNC_LOGGING 0 +#endif // defined(ELPP_EXPERIMENTAL_ASYNC) +#if defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING +# define ELPP_THREADING_ENABLED 1 +#endif // defined(ELPP_THREAD_SAFE) || ELPP_ASYNC_LOGGING +// Function macro ELPP_FUNC +#undef ELPP_FUNC +#if ELPP_COMPILER_MSVC // Visual C++ +# define ELPP_FUNC __FUNCSIG__ +#elif ELPP_COMPILER_GCC // GCC +# define ELPP_FUNC __PRETTY_FUNCTION__ +#elif ELPP_COMPILER_INTEL // Intel C++ +# define ELPP_FUNC __PRETTY_FUNCTION__ +#elif ELPP_COMPILER_CLANG // Clang++ +# define ELPP_FUNC __PRETTY_FUNCTION__ +#else +# if defined(__func__) +# define ELPP_FUNC __func__ +# else +# define ELPP_FUNC "" +# endif // defined(__func__) +#endif // defined(_MSC_VER) +#undef ELPP_VARIADIC_TEMPLATES_SUPPORTED +// Keep following line commented until features are fixed +#if ELPP_COMPILER_GCC || ELPP_COMPILER_CLANG || ELPP_COMPILER_INTEL || (ELPP_COMPILER_MSVC && _MSC_VER >= 1800) +# define ELPP_VARIADIC_TEMPLATES_SUPPORTED 1 +#endif // ELPP_COMPILER_GCC || ELPP_COMPILER_CLANG || ELPP_COMPILER_INTEL || (ELPP_COMPILER_MSVC && _MSC_VER >= 1800) +// Logging Enable/Disable macros +#if (!defined(ELPP_DISABLE_LOGS)) +# define ELPP_LOGGING_ENABLED 1 +#endif // (!defined(ELPP_DISABLE_LOGS)) +#if (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED) && ((defined(_DEBUG)) || (!defined(NDEBUG)))) +# define ELPP_DEBUG_LOG 1 +#else +# define ELPP_DEBUG_LOG 0 +#endif // (!defined(ELPP_DISABLE_DEBUG_LOGS) && (ELPP_LOGGING_ENABLED) && ((defined(_DEBUG)) || (!defined(NDEBUG)))) +#if (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED)) +# define ELPP_INFO_LOG 1 +#else +# define ELPP_INFO_LOG 0 +#endif // (!defined(ELPP_DISABLE_INFO_LOGS) && (ELPP_LOGGING_ENABLED)) +#if (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED)) +# define ELPP_WARNING_LOG 1 +#else +# define ELPP_WARNING_LOG 0 +#endif // (!defined(ELPP_DISABLE_WARNING_LOGS) && (ELPP_LOGGING_ENABLED)) +#if (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED)) +# define ELPP_ERROR_LOG 1 +#else +# define ELPP_ERROR_LOG 0 +#endif // (!defined(ELPP_DISABLE_ERROR_LOGS) && (ELPP_LOGGING_ENABLED)) +#if (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED)) +# define ELPP_FATAL_LOG 1 +#else +# define ELPP_FATAL_LOG 0 +#endif // (!defined(ELPP_DISABLE_FATAL_LOGS) && (ELPP_LOGGING_ENABLED)) +#if (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED)) +# define ELPP_TRACE_LOG 1 +#else +# define ELPP_TRACE_LOG 0 +#endif // (!defined(ELPP_DISABLE_TRACE_LOGS) && (ELPP_LOGGING_ENABLED)) +#if (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED)) +# define ELPP_VERBOSE_LOG 1 +#else +# define ELPP_VERBOSE_LOG 0 +#endif // (!defined(ELPP_DISABLE_VERBOSE_LOGS) && (ELPP_LOGGING_ENABLED)) +#if (!(ELPP_CXX0X || ELPP_CXX11)) +# error "Easylogging++ 9.0+ is only compatible with C++0x (or higher) compliant compiler" +#endif // (!(ELPP_CXX0X || ELPP_CXX11)) +// Headers +#if defined(ELPP_SYSLOG) +# include +#endif // defined(ELPP_SYSLOG) +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(ELPP_UNICODE) +# include +# if ELPP_OS_WINDOWS +# include +# endif // ELPP_OS_WINDOWS +#endif // defined(ELPP_UNICODE) +#if ELPP_STACKTRACE +# include +# include +#endif // ELPP_STACKTRACE +#if ELPP_OS_ANDROID +# include +#endif // ELPP_OS_ANDROID +#if ELPP_OS_UNIX +# include +# include +#elif ELPP_OS_WINDOWS +# include +# include +# if defined(WIN32_LEAN_AND_MEAN) +# if defined(ELPP_WINSOCK2) +# include +# else +# include +# endif // defined(ELPP_WINSOCK2) +# endif // defined(WIN32_LEAN_AND_MEAN) +#endif // ELPP_OS_UNIX +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if ELPP_THREADING_ENABLED +# if ELPP_USE_STD_THREADING +# include +# include +# else +# if ELPP_OS_UNIX +# include +# endif // ELPP_OS_UNIX +# endif // ELPP_USE_STD_THREADING +#endif // ELPP_THREADING_ENABLED +#if ELPP_ASYNC_LOGGING +# include +# include +# include +#endif // ELPP_ASYNC_LOGGING +#if defined(ELPP_STL_LOGGING) +// For logging STL based templates +# include +# include +# include +# include +# include +# include +# if defined(ELPP_LOG_STD_ARRAY) +# include +# endif // defined(ELPP_LOG_STD_ARRAY) +# if defined(ELPP_LOG_UNORDERED_MAP) +# include +# endif // defined(ELPP_LOG_UNORDERED_MAP) +# if defined(ELPP_LOG_UNORDERED_SET) +# include +# endif // defined(ELPP_UNORDERED_SET) +#endif // defined(ELPP_STL_LOGGING) +#if defined(ELPP_QT_LOGGING) +// For logging Qt based classes & templates +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +#endif // defined(ELPP_QT_LOGGING) +#if defined(ELPP_BOOST_LOGGING) +// For logging boost based classes & templates +# include +# include +# include +# include +# include +# include +# include +# include +#endif // defined(ELPP_BOOST_LOGGING) +#if defined(ELPP_WXWIDGETS_LOGGING) +// For logging wxWidgets based classes & templates +# include +#endif // defined(ELPP_WXWIDGETS_LOGGING) +// Forward declarations +namespace el { +class Logger; +class LogMessage; +class PerformanceTrackingData; +class Loggers; +class Helpers; +template class Callback; +class LogDispatchCallback; +class PerformanceTrackingCallback; +class LogDispatchData; +namespace base { +class Storage; +class RegisteredLoggers; +class PerformanceTracker; +class MessageBuilder; +class Writer; +class PErrorWriter; +class LogDispatcher; +class DefaultLogBuilder; +class DefaultLogDispatchCallback; +#if ELPP_ASYNC_LOGGING +class AsyncLogDispatchCallback; +class AsyncDispatchWorker; +#endif // ELPP_ASYNC_LOGGING +class DefaultPerformanceTrackingCallback; +} // namespace base +} // namespace el +/// @brief Easylogging++ entry namespace +namespace el { +/// @brief Namespace containing base/internal functionality used by Easylogging++ +namespace base { +/// @brief Data types used by Easylogging++ +namespace type { +#undef ELPP_LITERAL +#undef ELPP_STRLEN +#undef ELPP_COUT +#if defined(ELPP_UNICODE) +# define ELPP_LITERAL(txt) L##txt +# define ELPP_STRLEN wcslen +# if defined ELPP_CUSTOM_COUT +# define ELPP_COUT ELPP_CUSTOM_COUT +# else +# define ELPP_COUT std::wcout +# endif // defined ELPP_CUSTOM_COUT +typedef wchar_t char_t; +typedef std::wstring string_t; +typedef std::wstringstream stringstream_t; +typedef std::wfstream fstream_t; +typedef std::wostream ostream_t; +#else +# define ELPP_LITERAL(txt) txt +# define ELPP_STRLEN strlen +# if defined ELPP_CUSTOM_COUT +# define ELPP_COUT ELPP_CUSTOM_COUT +# else +# define ELPP_COUT std::cout +# endif // defined ELPP_CUSTOM_COUT +typedef char char_t; +typedef std::string string_t; +typedef std::stringstream stringstream_t; +typedef std::fstream fstream_t; +typedef std::ostream ostream_t; +#endif // defined(ELPP_UNICODE) +#if defined(ELPP_CUSTOM_COUT_LINE) +# define ELPP_COUT_LINE(logLine) ELPP_CUSTOM_COUT_LINE(logLine) +#else +# define ELPP_COUT_LINE(logLine) logLine << std::flush +#endif // defined(ELPP_CUSTOM_COUT_LINE) +typedef unsigned short EnumType; +typedef std::shared_ptr StoragePointer; +typedef int VerboseLevel; +typedef std::shared_ptr LogDispatchCallbackPtr; +typedef std::shared_ptr PerformanceTrackingCallbackPtr; +} // namespace type +/// @brief Internal helper class that prevent copy constructor for class +/// +/// @detail When using this class simply inherit it privately +class NoCopy { +protected: + NoCopy(void) {} +private: + NoCopy(const NoCopy&); + NoCopy& operator=(const NoCopy&); +}; +/// @brief Internal helper class that makes all default constructors private. +/// +/// @detail This prevents initializing class making it static unless an explicit constructor is declared. +/// When using this class simply inherit it privately +class StaticClass { +private: + StaticClass(void); + StaticClass(const StaticClass&); + StaticClass& operator=(const StaticClass&); +}; +} // namespace base +/// @brief Represents enumeration for severity level used to determine level of logging +/// +/// @detail With Easylogging++, developers may disable or enable any level regardless of +/// what the severity is. Or they can choose to log using hierarchical logging flag +enum class Level : base::type::EnumType { + /// @brief Generic level that represents all the levels. Useful when setting global configuration for all levels + Global = 1, + /// @brief Information that can be useful to back-trace certain events - mostly useful than debug logs. + Trace = 2, + /// @brief Informational events most useful for developers to debug application + Debug = 4, + /// @brief Severe error information that will presumably abort application + Fatal = 8, + /// @brief Information representing errors in application but application will keep running + Error = 16, + /// @brief Useful when application has potentially harmful situtaions + Warning = 32, + /// @brief Information that can be highly useful and vary with verbose logging level. + Verbose = 64, + /// @brief Mainly useful to represent current progress of application + Info = 128, + /// @brief Represents unknown level + Unknown = 1010 +}; +/// @brief Static class that contains helper functions for el::Level +class LevelHelper : base::StaticClass { +public: + /// @brief Represents minimum valid level. Useful when iterating through enum. + static const base::type::EnumType kMinValid = static_cast(Level::Trace); + /// @brief Represents maximum valid level. This is used internally and you should not need it. + static const base::type::EnumType kMaxValid = static_cast(Level::Info); + /// @brief Casts level to int, useful for iterating through enum. + static base::type::EnumType castToInt(Level level) { + return static_cast(level); + } + /// @brief Casts int(ushort) to level, useful for iterating through enum. + static Level castFromInt(base::type::EnumType l) { + return static_cast(l); + } + /// @brief Converts level to associated const char* + /// @return Upper case string based level. + static const char* convertToString(Level level) { + // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. + if (level == Level::Global) return "GLOBAL"; + if (level == Level::Debug) return "DEBUG"; + if (level == Level::Info) return "INFO"; + if (level == Level::Warning) return "WARNING"; + if (level == Level::Error) return "ERROR"; + if (level == Level::Fatal) return "FATAL"; + if (level == Level::Verbose) return "VERBOSE"; + if (level == Level::Trace) return "TRACE"; + return "UNKNOWN"; + } + /// @brief Converts from levelStr to Level + /// @param levelStr Upper case string based level. + /// Lower case is also valid but providing upper case is recommended. + static Level convertFromString(const char* levelStr) { + if ((strcmp(levelStr, "GLOBAL") == 0) || (strcmp(levelStr, "global") == 0)) + return Level::Global; + if ((strcmp(levelStr, "DEBUG") == 0) || (strcmp(levelStr, "debug") == 0)) + return Level::Debug; + if ((strcmp(levelStr, "INFO") == 0) || (strcmp(levelStr, "info") == 0)) + return Level::Info; + if ((strcmp(levelStr, "WARNING") == 0) || (strcmp(levelStr, "warning") == 0)) + return Level::Warning; + if ((strcmp(levelStr, "ERROR") == 0) || (strcmp(levelStr, "error") == 0)) + return Level::Error; + if ((strcmp(levelStr, "FATAL") == 0) || (strcmp(levelStr, "fatal") == 0)) + return Level::Fatal; + if ((strcmp(levelStr, "VERBOSE") == 0) || (strcmp(levelStr, "verbose") == 0)) + return Level::Verbose; + if ((strcmp(levelStr, "TRACE") == 0) || (strcmp(levelStr, "trace") == 0)) + return Level::Trace; + return Level::Unknown; + } + /// @brief Applies specified function to each level starting from startIndex + /// @param startIndex initial value to start the iteration from. This is passed as pointer and + /// is left-shifted so this can be used inside function (fn) to represent current level. + /// @param fn function to apply with each level. This bool represent whether or not to stop iterating through levels. + static inline void forEachLevel(base::type::EnumType* startIndex, const std::function& fn) { + base::type::EnumType lIndexMax = LevelHelper::kMaxValid; + do { + if (fn()) { + break; + } + *startIndex = static_cast(*startIndex << 1); + } while (*startIndex <= lIndexMax); + } +}; +/// @brief Represents enumeration of ConfigurationType used to configure or access certain aspect +/// of logging +enum class ConfigurationType : base::type::EnumType { + /// @brief Determines whether or not corresponding level and logger of logging is enabled + /// You may disable all logs by using el::Level::Global + Enabled = 1, + /// @brief Whether or not to write corresponding log to log file + ToFile = 2, + /// @brief Whether or not to write corresponding level and logger log to standard output. + /// By standard output meaning termnal, command prompt etc + ToStandardOutput = 4, + /// @brief Determines format of logging corresponding level and logger. + Format = 8, + /// @brief Determines log file (full path) to write logs to for correponding level and logger + Filename = 16, + /// @brief Specifies milliseconds width. Width can be within range (1-6) + MillisecondsWidth = 32, + /// @brief Determines whether or not performance tracking is enabled. + /// + /// @detail This does not depend on logger or level. Performance tracking always uses 'performance' logger + PerformanceTracking = 64, + /// @brief Specifies log file max size. + /// + /// @detail If file size of corresponding log file (for corresponding level) is >= specified size, log file will + /// be truncated and re-initiated. + MaxLogFileSize = 128, + /// @brief Specifies number of log entries to hold until we flush pending log data + LogFlushThreshold = 256, + /// @brief Represents unknown configuration + Unknown = 1010 +}; +/// @brief Static class that contains helper functions for el::ConfigurationType +class ConfigurationTypeHelper : base::StaticClass { +public: + /// @brief Represents minimum valid configuration type. Useful when iterating through enum. + static const base::type::EnumType kMinValid = static_cast(ConfigurationType::Enabled); + /// @brief Represents maximum valid configuration type. This is used internally and you should not need it. + static const base::type::EnumType kMaxValid = static_cast(ConfigurationType::MaxLogFileSize); + /// @brief Casts configuration type to int, useful for iterating through enum. + static base::type::EnumType castToInt(ConfigurationType configurationType) { + return static_cast(configurationType); + } + /// @brief Casts int(ushort) to configurationt type, useful for iterating through enum. + static ConfigurationType castFromInt(base::type::EnumType c) { + return static_cast(c); + } + /// @brief Converts configuration type to associated const char* + /// @returns Upper case string based configuration type. + static const char* convertToString(ConfigurationType configurationType) { + // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. + if (configurationType == ConfigurationType::Enabled) return "ENABLED"; + if (configurationType == ConfigurationType::Filename) return "FILENAME"; + if (configurationType == ConfigurationType::Format) return "FORMAT"; + if (configurationType == ConfigurationType::ToFile) return "TO_FILE"; + if (configurationType == ConfigurationType::ToStandardOutput) return "TO_STANDARD_OUTPUT"; + if (configurationType == ConfigurationType::MillisecondsWidth) return "MILLISECONDS_WIDTH"; + if (configurationType == ConfigurationType::PerformanceTracking) return "PERFORMANCE_TRACKING"; + if (configurationType == ConfigurationType::MaxLogFileSize) return "MAX_LOG_FILE_SIZE"; + if (configurationType == ConfigurationType::LogFlushThreshold) return "LOG_FLUSH_THRESHOLD"; + return "UNKNOWN"; + } + /// @brief Converts from configStr to ConfigurationType + /// @param configStr Upper case string based configuration type. + /// Lower case is also valid but providing upper case is recommended. + static ConfigurationType convertFromString(const char* configStr) { + if ((strcmp(configStr, "ENABLED") == 0) || (strcmp(configStr, "enabled") == 0)) + return ConfigurationType::Enabled; + if ((strcmp(configStr, "TO_FILE") == 0) || (strcmp(configStr, "to_file") == 0)) + return ConfigurationType::ToFile; + if ((strcmp(configStr, "TO_STANDARD_OUTPUT") == 0) || (strcmp(configStr, "to_standard_output") == 0)) + return ConfigurationType::ToStandardOutput; + if ((strcmp(configStr, "FORMAT") == 0) || (strcmp(configStr, "format") == 0)) + return ConfigurationType::Format; + if ((strcmp(configStr, "FILENAME") == 0) || (strcmp(configStr, "filename") == 0)) + return ConfigurationType::Filename; + if ((strcmp(configStr, "MILLISECONDS_WIDTH") == 0) || (strcmp(configStr, "milliseconds_width") == 0)) + return ConfigurationType::MillisecondsWidth; + if ((strcmp(configStr, "PERFORMANCE_TRACKING") == 0) || (strcmp(configStr, "performance_tracking") == 0)) + return ConfigurationType::PerformanceTracking; + if ((strcmp(configStr, "MAX_LOG_FILE_SIZE") == 0) || (strcmp(configStr, "max_log_file_size") == 0)) + return ConfigurationType::MaxLogFileSize; + if ((strcmp(configStr, "LOG_FLUSH_THRESHOLD") == 0) || (strcmp(configStr, "log_flush_threshold") == 0)) + return ConfigurationType::LogFlushThreshold; + return ConfigurationType::Unknown; + } + /// @brief Applies specified function to each configuration type starting from startIndex + /// @param startIndex initial value to start the iteration from. This is passed by pointer and is left-shifted + /// so this can be used inside function (fn) to represent current configuration type. + /// @param fn function to apply with each configuration type. + /// This bool represent whether or not to stop iterating through configurations. + static inline void forEachConfigType(base::type::EnumType* startIndex, const std::function& fn) { + base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid; + do { + if (fn()) { + break; + } + *startIndex = static_cast(*startIndex << 1); + } while (*startIndex <= cIndexMax); + } +}; +/// @brief Flags used while writing logs. This flags are set by user +enum class LoggingFlag : base::type::EnumType { + /// @brief Makes sure we have new line for each container log entry + NewLineForContainer = 1, + /// @brief Makes sure if -vmodule is used and does not specifies a module, then verbose + /// logging is allowed via that module. + AllowVerboseIfModuleNotSpecified = 2, + /// @brief When handling crashes by default, detailed crash reason will be logged as well + LogDetailedCrashReason = 4, + /// @brief Allows to disable application abortion when logged using FATAL level + DisableApplicationAbortOnFatalLog = 8, + /// @brief Flushes log with every log-entry (performance sensative) - Disabled by default + ImmediateFlush = 16, + /// @brief Enables strict file rolling + StrictLogFileSizeCheck = 32, + /// @brief Make terminal output colorful for supported terminals + ColoredTerminalOutput = 64, + /// @brief Supports use of multiple logging in same macro, e.g, CLOG(INFO, "default", "network") + MultiLoggerSupport = 128, + /// @brief Disables comparing performance tracker's checkpoints + DisablePerformanceTrackingCheckpointComparison = 256, + /// @brief Disable VModules + DisableVModules = 512, + /// @brief Disable VModules extensions + DisableVModulesExtensions = 1024, + /// @brief Enables hierarchical logging + HierarchicalLogging = 2048, + /// @brief Creates logger automatically when not available + CreateLoggerAutomatically = 4096, + /// @brief Adds spaces b/w logs that separated by left-shift operator + AutoSpacing = 8192, + /// @brief Preserves time format and does not convert it to sec, hour etc (performance tracking only) + FixedTimeFormat = 16384 +}; +namespace base { +/// @brief Namespace containing constants used internally. +namespace consts { + // Level log values - These are values that are replaced in place of %level format specifier + static const base::type::char_t* kInfoLevelLogValue = ELPP_LITERAL("INFO "); + static const base::type::char_t* kDebugLevelLogValue = ELPP_LITERAL("DEBUG"); + static const base::type::char_t* kWarningLevelLogValue = ELPP_LITERAL("WARN "); + static const base::type::char_t* kErrorLevelLogValue = ELPP_LITERAL("ERROR"); + static const base::type::char_t* kFatalLevelLogValue = ELPP_LITERAL("FATAL"); + static const base::type::char_t* kVerboseLevelLogValue = ELPP_LITERAL("VER"); + static const base::type::char_t* kTraceLevelLogValue = ELPP_LITERAL("TRACE"); + static const base::type::char_t* kInfoLevelShortLogValue = ELPP_LITERAL("I"); + static const base::type::char_t* kDebugLevelShortLogValue = ELPP_LITERAL("D"); + static const base::type::char_t* kWarningLevelShortLogValue = ELPP_LITERAL("W"); + static const base::type::char_t* kErrorLevelShortLogValue = ELPP_LITERAL("E"); + static const base::type::char_t* kFatalLevelShortLogValue = ELPP_LITERAL("F"); + static const base::type::char_t* kVerboseLevelShortLogValue = ELPP_LITERAL("V"); + static const base::type::char_t* kTraceLevelShortLogValue = ELPP_LITERAL("T"); + // Format specifiers - These are used to define log format + static const base::type::char_t* kAppNameFormatSpecifier = ELPP_LITERAL("%app"); + static const base::type::char_t* kLoggerIdFormatSpecifier = ELPP_LITERAL("%logger"); + static const base::type::char_t* kThreadIdFormatSpecifier = ELPP_LITERAL("%thread"); + static const base::type::char_t* kSeverityLevelFormatSpecifier = ELPP_LITERAL("%level"); + static const base::type::char_t* kSeverityLevelShortFormatSpecifier = ELPP_LITERAL("%levshort"); + static const base::type::char_t* kDateTimeFormatSpecifier = ELPP_LITERAL("%datetime"); + static const base::type::char_t* kLogFileFormatSpecifier = ELPP_LITERAL("%file"); + static const base::type::char_t* kLogFileBaseFormatSpecifier = ELPP_LITERAL("%fbase"); + static const base::type::char_t* kLogLineFormatSpecifier = ELPP_LITERAL("%line"); + static const base::type::char_t* kLogLocationFormatSpecifier = ELPP_LITERAL("%loc"); + static const base::type::char_t* kLogFunctionFormatSpecifier = ELPP_LITERAL("%func"); + static const base::type::char_t* kCurrentUserFormatSpecifier = ELPP_LITERAL("%user"); + static const base::type::char_t* kCurrentHostFormatSpecifier = ELPP_LITERAL("%host"); + static const base::type::char_t* kMessageFormatSpecifier = ELPP_LITERAL("%msg"); + static const base::type::char_t* kVerboseLevelFormatSpecifier = ELPP_LITERAL("%vlevel"); + static const char* kDateTimeFormatSpecifierForFilename = "%datetime"; + // Date/time + static const char* kDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; + static const char* kDaysAbbrev[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; + static const char* kMonths[12] = { "January", "February", "March", "Apri", "May", "June", "July", "August", + "September", "October", "November", "December" }; + static const char* kMonthsAbbrev[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; + static const char* kDefaultDateTimeFormat = "%Y-%M-%d %H:%m:%s,%g"; + static const char* kDefaultDateTimeFormatInFilename = "%Y-%M-%d_%H-%m"; + static const int kYearBase = 1900; + static const char* kAm = "AM"; + static const char* kPm = "PM"; + // Miscellaneous constants + static const char* kDefaultLoggerId = "default"; + static const char* kPerformanceLoggerId = "performance"; + static const char* kSysLogLoggerId = "syslog"; + static const char* kNullPointer = "nullptr"; + static const char kFormatSpecifierChar = '%'; +#if ELPP_VARIADIC_TEMPLATES_SUPPORTED + static const char kFormatSpecifierCharValue = 'v'; +#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED + static const unsigned int kMaxLogPerContainer = 100; + static const unsigned int kMaxLogPerCounter = 100000; + static const unsigned int kDefaultMillisecondsWidth = 3; + static const base::type::VerboseLevel kMaxVerboseLevel = 9; + static const char* kUnknownUser = "user"; + static const char* kUnknownHost = "unknown-host"; +#if defined(ELPP_DEFAULT_LOG_FILE) + static const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE; +#else +# if ELPP_OS_UNIX +# if ELPP_OS_ANDROID + static const char* kDefaultLogFile = "logs/myeasylog.log"; +# else + static const char* kDefaultLogFile = "logs/myeasylog.log"; +# endif // ELPP_OS_ANDROID +# elif ELPP_OS_WINDOWS + static const char* kDefaultLogFile = "logs\\myeasylog.log"; +# endif // ELPP_OS_UNIX +#endif // defined(ELPP_DEFAULT_LOG_FILE) +#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) + static const char* kDefaultLogFileParam = "--default-log-file"; +#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) +#if defined(ELPP_LOGGING_FLAGS_FROM_ARG) + static const char* kLoggingFlagsParam = "--logging-flags"; +#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG) +#if ELPP_OS_WINDOWS + static const char* kFilePathSeperator = "\\"; +#else + static const char* kFilePathSeperator = "/"; +#endif // ELPP_OS_WINDOWS + static const char* kValidLoggerIdSymbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._"; + static const char* kConfigurationComment = "##"; + static const char* kConfigurationLevel = "*"; + static const char* kConfigurationLoggerId = "--"; + static const std::size_t kSourceFilenameMaxLength = 100; + static const std::size_t kSourceLineMaxLength = 10; + static const Level kPerformanceTrackerDefaultLevel = Level::Info; + const struct { + double value; + const base::type::char_t* unit; + } kTimeFormats[] = { + { 1000.0f, ELPP_LITERAL("mis") }, + { 1000.0f, ELPP_LITERAL("ms") }, + { 60.0f, ELPP_LITERAL("seconds") }, + { 60.0f, ELPP_LITERAL("minutes") }, + { 24.0f, ELPP_LITERAL("hours") }, + { 7.0f, ELPP_LITERAL("days") } + }; + static const int kTimeFormatsCount = sizeof(kTimeFormats) / sizeof(kTimeFormats[0]); + const struct { + int numb; + const char* name; + const char* brief; + const char* detail; + } kCrashSignals[] = { + // NOTE: Do not re-order, if you do please check CrashHandler(bool) constructor and CrashHandler::setHandler(..) + { SIGABRT, "SIGABRT", "Abnormal termination", + "Program was abnormally terminated." }, + { SIGFPE, "SIGFPE", "Erroneous arithmetic operation", + "Arithemetic operation issue such as division by zero or operation resulting in overflow." }, + { SIGILL, "SIGILL", "Illegal instruction", + "Generally due to a corruption in the code or to an attempt to execute data."}, + { SIGSEGV, "SIGSEGV", "Invalid access to memory", + "Program is trying to read an invalid (unallocated, deleted or corrupted) or inaccessible memory." }, + { SIGINT, "SIGINT", "Interactive attention signal", + "Interruption generated (generally) by user or operating system." }, + }; + static const int kCrashSignalsCount = sizeof(kCrashSignals) / sizeof(kCrashSignals[0]); +} // namespace consts +} // namespace base +typedef std::function PreRollOutCallback; +namespace base { +static inline void defaultPreRollOutCallback(const char*, std::size_t) {} +/// @brief Enum to represent timestamp unit +enum class TimestampUnit : base::type::EnumType { + Microsecond = 0, Millisecond = 1, Second = 2, Minute = 3, Hour = 4, Day = 5 +}; +/// @brief Format flags used to determine specifiers that are active for performance improvements. +enum class FormatFlags : base::type::EnumType { + DateTime = 1<<1, LoggerId = 1<<2, File = 1<<3, Line = 1<<4, Location = 1<<5, Function = 1<<6, + User = 1<<7, Host = 1<<8, LogMessage = 1<<9, VerboseLevel = 1<<10, AppName = 1<<11, ThreadId = 1<<12, + Level = 1<<13, FileBase = 1<<14, LevelShort = 1<<15 +}; +/// @brief A milliseconds width class containing actual width and offset for date/time +class MillisecondsWidth { +public: + MillisecondsWidth(void) { init(base::consts::kDefaultMillisecondsWidth); } + explicit MillisecondsWidth(int width) { init(width); } + bool operator==(const MillisecondsWidth& msWidth) { return m_width == msWidth.m_width && m_offset == msWidth.m_offset; } + int m_width; unsigned int m_offset; +private: + void init(int width) { + if (width < 1 || width > 6) { + width = base::consts::kDefaultMillisecondsWidth; + } + m_width = width; + switch (m_width) { + case 3: m_offset = 1000; break; + case 4: m_offset = 100; break; + case 5: m_offset = 10; break; + case 6: m_offset = 1; break; + default: m_offset = 1000; break; + } + } +}; +/// @brief Namespace containing utility functions/static classes used internally +namespace utils { +/// @brief Deletes memory safely and points to null +template +static inline +typename std::enable_if::value, void>::type +safeDelete(T*& pointer) { + if (pointer == nullptr) + return; + delete pointer; + pointer = nullptr; +} +/// @brief Gets value of const char* but if it is nullptr, a string nullptr is returned +static inline const char* charPtrVal(const char* pointer) { + return pointer == nullptr ? base::consts::kNullPointer : pointer; +} +/// @brief Aborts application due with user-defined status +static inline void abort(int status, const std::string& reason = std::string()) { + // Both status and reason params are there for debugging with tools like gdb etc + ELPP_UNUSED(status); + ELPP_UNUSED(reason); +#if defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG) + // Ignore msvc critical error dialog - break instead (on debug mode) + _asm int 3 +#else + ::abort(); +#endif // defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG) +} +/// @brief Bitwise operations for C++11 strong enum class. This casts e into Flag_T and returns value after bitwise operation +/// Use these function as
flag = bitwise::Or(MyEnum::val1, flag);
+namespace bitwise { +template +static inline base::type::EnumType And(Enum e, base::type::EnumType flag) { + return static_cast(flag) & static_cast(e); +} +template +static inline base::type::EnumType Not(Enum e, base::type::EnumType flag) { + return static_cast(flag) & ~(static_cast(e)); +} +template +static inline base::type::EnumType Or(Enum e, base::type::EnumType flag) { + return static_cast(flag) | static_cast(e); +} +} // namespace bitwise +template +static inline void addFlag(Enum e, base::type::EnumType* flag) { + *flag = base::utils::bitwise::Or(e, *flag); +} +template +static inline void removeFlag(Enum e, base::type::EnumType* flag) { + *flag = base::utils::bitwise::Not(e, *flag); +} +template +static inline bool hasFlag(Enum e, base::type::EnumType flag) { + return base::utils::bitwise::And(e, flag) > 0x0; +} +} // namespace utils +namespace threading { +#if ELPP_THREADING_ENABLED +# if !ELPP_USE_STD_THREADING +namespace internal { +/// @brief A mutex wrapper for compiler that dont yet support std::mutex +class Mutex : base::NoCopy { +public: + Mutex(void) { +# if ELPP_OS_UNIX + pthread_mutex_init(&m_underlyingMutex, nullptr); +# elif ELPP_OS_WINDOWS + InitializeCriticalSection(&m_underlyingMutex); +# endif // ELPP_OS_UNIX + } + + virtual ~Mutex(void) { +# if ELPP_OS_UNIX + pthread_mutex_destroy(&m_underlyingMutex); +# elif ELPP_OS_WINDOWS + DeleteCriticalSection(&m_underlyingMutex); +# endif // ELPP_OS_UNIX + } + + inline void lock(void) { +# if ELPP_OS_UNIX + pthread_mutex_lock(&m_underlyingMutex); +# elif ELPP_OS_WINDOWS + EnterCriticalSection(&m_underlyingMutex); +# endif // ELPP_OS_UNIX + } + + inline bool try_lock(void) { +# if ELPP_OS_UNIX + return (pthread_mutex_trylock(&m_underlyingMutex) == 0); +# elif ELPP_OS_WINDOWS + return TryEnterCriticalSection(&m_underlyingMutex); +# endif // ELPP_OS_UNIX + } + + inline void unlock(void) { +# if ELPP_OS_UNIX + pthread_mutex_unlock(&m_underlyingMutex); +# elif ELPP_OS_WINDOWS + LeaveCriticalSection(&m_underlyingMutex); +# endif // ELPP_OS_UNIX + } + +private: +# if ELPP_OS_UNIX + pthread_mutex_t m_underlyingMutex; +# elif ELPP_OS_WINDOWS + CRITICAL_SECTION m_underlyingMutex; +# endif // ELPP_OS_UNIX +}; +/// @brief Scoped lock for compiler that dont yet support std::lock_guard +template +class ScopedLock : base::NoCopy { +public: + explicit ScopedLock(M& mutex) { + m_mutex = &mutex; + m_mutex->lock(); + } + + virtual ~ScopedLock(void) { + m_mutex->unlock(); + } +private: + M* m_mutex; + ScopedLock(void); +}; +} // namespace internal +/// @brief Gets ID of currently running threading in windows systems. On unix, nothing is returned. +static inline std::string getCurrentThreadId(void) { + std::stringstream ss; +# if (ELPP_OS_WINDOWS) + ss << GetCurrentThreadId(); +# endif // (ELPP_OS_WINDOWS) + return ss.str(); +} +static inline void msleep(int) { + // No implementation for non std::thread version +} +typedef base::threading::internal::Mutex Mutex; +typedef base::threading::internal::ScopedLock ScopedLock; +# else +/// @brief Gets ID of currently running threading using std::this_thread::get_id() +static inline std::string getCurrentThreadId(void) { + std::stringstream ss; + ss << std::this_thread::get_id(); + return ss.str(); +} +static inline void msleep(int ms) { + // Only when async logging enabled - this is because async is strict on compiler +#if ELPP_ASYNC_LOGGING + std::this_thread::sleep_for(std::chrono::milliseconds(ms)); +#endif // ELPP_ASYNC_LOGGING +} +typedef std::mutex Mutex; +typedef std::lock_guard ScopedLock; +# endif // !ELPP_USE_STD_THREADING +#else +namespace internal { +/// @brief Mutex wrapper used when multi-threading is disabled. +class NoMutex : base::NoCopy { +public: + NoMutex(void) {} + inline void lock(void) {} + inline bool try_lock(void) { return true; } + inline void unlock(void) {} +}; +/// @brief Lock guard wrapper used when multi-threading is disabled. +template +class NoScopedLock : base::NoCopy { +public: + explicit NoScopedLock(Mutex&) { + } + virtual ~NoScopedLock(void) { + } +private: + NoScopedLock(void); +}; +} // namespace internal +static inline std::string getCurrentThreadId(void) { + return std::string(); +} +static inline void msleep(int) { + // No custom implementation +} +typedef base::threading::internal::NoMutex Mutex; +typedef base::threading::internal::NoScopedLock ScopedLock; +#endif // ELPP_THREADING_ENABLED +/// @brief Base of thread safe class, this class is inheritable-only +class ThreadSafe { +public: + virtual inline void acquireLock(void) ELPP_FINAL { m_mutex.lock(); } + virtual inline void releaseLock(void) ELPP_FINAL { m_mutex.unlock(); } + virtual inline base::threading::Mutex& lock(void) ELPP_FINAL { return m_mutex; } +protected: + ThreadSafe(void) {} + virtual ~ThreadSafe(void) {} +private: + base::threading::Mutex m_mutex; +}; +} // namespace threading +namespace utils { +class File : base::StaticClass { +public: + /// @brief Creates new out file stream for specified filename. + /// @return Pointer to newly created fstream or nullptr + static base::type::fstream_t* newFileStream(const std::string& filename) { + base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(), + base::type::fstream_t::out | base::type::fstream_t::app); +#if defined(ELPP_UNICODE) + std::locale elppUnicodeLocale(""); +#if ELPP_OS_WINDOWS + std::locale elppUnicodeLocaleWindows(elppUnicodeLocale, new std::codecvt_utf8_utf16); + elppUnicodeLocale = elppUnicodeLocaleWindows; +#endif + fs->imbue(elppUnicodeLocale); +#endif // defined(ELPP_UNICODE) + if (fs->is_open()) { + fs->flush(); + } else { + base::utils::safeDelete(fs); + ELPP_INTERNAL_ERROR("Bad file [" << filename << "]", true); + } + return fs; + } + + /// @brief Gets size of file provided in stream + static std::size_t getSizeOfFile(base::type::fstream_t* fs) { + if (fs == nullptr) { + return 0; + } + std::streampos currPos = fs->tellg(); + fs->seekg(0, fs->end); + std::size_t size = static_cast(fs->tellg()); + fs->seekg(currPos); + return size; + } + + /// @brief Determines whether or not provided path exist in current file system + static inline bool pathExists(const char* path, bool considerFile = false) { + if (path == nullptr) { + return false; + } +#if ELPP_OS_UNIX + ELPP_UNUSED(considerFile); + struct stat st; + return (stat(path, &st) == 0); +#elif ELPP_OS_WINDOWS + DWORD fileType = GetFileAttributesA(path); + if (fileType == INVALID_FILE_ATTRIBUTES) { + return false; + } + return considerFile ? true : ((fileType & FILE_ATTRIBUTE_DIRECTORY) == 0 ? false : true); +#endif // ELPP_OS_UNIX + } + + /// @brief Creates specified path on file system + /// @param path Path to create. + static bool createPath(const std::string& path) { + if (path.empty()) { + return false; + } + if (base::utils::File::pathExists(path.c_str())) { + return true; + } + int status = -1; + + char* currPath = const_cast(path.c_str()); + std::string builtPath = std::string(); +#if ELPP_OS_UNIX + if (path[0] == '/') { + builtPath = "/"; + } + currPath = STRTOK(currPath, base::consts::kFilePathSeperator, 0); +#elif ELPP_OS_WINDOWS + // Use secure functions API + char* nextTok_ = nullptr; + currPath = STRTOK(currPath, base::consts::kFilePathSeperator, &nextTok_); + ELPP_UNUSED(nextTok_); +#endif // ELPP_OS_UNIX + while (currPath != nullptr) { + builtPath.append(currPath); + builtPath.append(base::consts::kFilePathSeperator); +#if ELPP_OS_UNIX + status = mkdir(builtPath.c_str(), ELPP_LOG_PERMS); + currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, 0); +#elif ELPP_OS_WINDOWS + status = _mkdir(builtPath.c_str()); + currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, &nextTok_); +#endif // ELPP_OS_UNIX + } + if (status == -1) { + ELPP_INTERNAL_ERROR("Error while creating path [" << path << "]", true); + return false; + } + return true; + } + /// @brief Extracts path of filename with leading slash + static std::string extractPathFromFilename(const std::string& fullPath, + const char* seperator = base::consts::kFilePathSeperator) { + if ((fullPath == "") || (fullPath.find(seperator) == std::string::npos)) { + return fullPath; + } + std::size_t lastSlashAt = fullPath.find_last_of(seperator); + if (lastSlashAt == 0) { + return std::string(seperator); + } + return fullPath.substr(0, lastSlashAt + 1); + } + /// @brief builds stripped filename and puts it in buff + static void buildStrippedFilename(const char* filename, char buff[], + std::size_t limit = base::consts::kSourceFilenameMaxLength) { + std::size_t sizeOfFilename = strlen(filename); + if (sizeOfFilename >= limit) { + filename += (sizeOfFilename - limit); + if (filename[0] != '.' && filename[1] != '.') { // prepend if not already + filename += 3; // 3 = '..' + STRCAT(buff, "..", limit); + } + } + STRCAT(buff, filename, limit); + } + /// @brief builds base filename and puts it in buff + static void buildBaseFilename(const std::string& fullPath, char buff[], + std::size_t limit = base::consts::kSourceFilenameMaxLength, + const char* seperator = base::consts::kFilePathSeperator) { + const char *filename = fullPath.c_str(); + std::size_t lastSlashAt = fullPath.find_last_of(seperator); + filename += lastSlashAt ? lastSlashAt+1 : 0; + std::size_t sizeOfFilename = strlen(filename); + if (sizeOfFilename >= limit) { + filename += (sizeOfFilename - limit); + if (filename[0] != '.' && filename[1] != '.') { // prepend if not already + filename += 3; // 3 = '..' + STRCAT(buff, "..", limit); + } + } + STRCAT(buff, filename, limit); + } +}; +/// @brief String utilities helper class used internally. You should not use it. +class Str : base::StaticClass { +public: + /// @brief Checks if character is digit. Dont use libc implementation of it to prevent locale issues. + static inline bool isDigit(char c) { + return c >= '0' && c <= '9'; + } + + /// @brief Matches wildcards, '*' and '?' only supported. + static bool wildCardMatch(const char* str, const char* pattern) { + while (*pattern) { + switch (*pattern) { + case '?': + if (!*str) + return false; + ++str; + ++pattern; + break; + case '*': + if (wildCardMatch(str, pattern + 1)) + return true; + if (*str && wildCardMatch(str + 1, pattern)) + return true; + return false; + break; + default: + if (*str++ != *pattern++) + return false; + break; + } + } + return !*str && !*pattern; + } + + /// @brief Trims string from start + /// @param [in,out] str String to trim + static inline std::string& ltrim(std::string& str) { + str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::not1(std::ptr_fun(&std::isspace)))); + return str; + } + + /// @brief Trim string from end + /// @param [in,out] str String to trim + static inline std::string& rtrim(std::string& str) { + str.erase(std::find_if(str.rbegin(), str.rend(), std::not1(std::ptr_fun(&std::isspace))).base(), str.end()); + return str; + } + + /// @brief Trims string from left and right + /// @param [in,out] str String to trim + static inline std::string& trim(std::string& str) { + return ltrim(rtrim(str)); + } + + /// @brief Determines whether or not str starts with specified string + /// @param str String to check + /// @param start String to check against + /// @return Returns true if starts with specified string, false otherwise + static inline bool startsWith(const std::string& str, const std::string& start) { + return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0); + } + + /// @brief Determines whether or not str ends with specified string + /// @param str String to check + /// @param end String to check against + /// @return Returns true if ends with specified string, false otherwise + static inline bool endsWith(const std::string& str, const std::string& end) { + return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0); + } + + /// @brief Replaces all instances of replaceWhat with 'replaceWith'. Original variable is changed for performance. + /// @param [in,out] str String to replace from + /// @param replaceWhat Character to replace + /// @param replaceWith Character to replace with + /// @return Modified version of str + static inline std::string& replaceAll(std::string& str, char replaceWhat, char replaceWith) { + std::replace(str.begin(), str.end(), replaceWhat, replaceWith); + return str; + } + + /// @brief Replaces all instances of 'replaceWhat' with 'replaceWith'. (String version) Replaces in place + /// @param str String to replace from + /// @param replaceWhat Character to replace + /// @param replaceWith Character to replace with + /// @return Modified (original) str + static inline std::string& replaceAll(std::string& str, const std::string& replaceWhat, // NOLINT + const std::string& replaceWith) { + if (replaceWhat == replaceWith) + return str; + std::size_t foundAt = std::string::npos; + while ((foundAt = str.find(replaceWhat, foundAt + 1)) != std::string::npos) { + str.replace(foundAt, replaceWhat.length(), replaceWith); + } + return str; + } + + static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, // NOLINT + const base::type::string_t& replaceWith) { + std::size_t foundAt = base::type::string_t::npos; + while ((foundAt = str.find(replaceWhat, foundAt + 1)) != base::type::string_t::npos) { + if (foundAt > 0 && str[foundAt - 1] == base::consts::kFormatSpecifierChar) { + str.erase(foundAt > 0 ? foundAt - 1 : 0, 1); + ++foundAt; + } else { + str.replace(foundAt, replaceWhat.length(), replaceWith); + return; + } + } + } +#if defined(ELPP_UNICODE) + static void replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, // NOLINT + const std::string& replaceWith) { + replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end())); + } +#endif // defined(ELPP_UNICODE) + /// @brief Converts string to uppercase + /// @param str String to convert + /// @return Uppercase string + static inline std::string& toUpper(std::string& str) { + std::transform(str.begin(), str.end(), str.begin(), ::toupper); + return str; + } + + /// @brief Compares cstring equality - uses strcmp + static inline bool cStringEq(const char* s1, const char* s2) { + if (s1 == nullptr && s2 == nullptr) return true; + if (s1 == nullptr || s2 == nullptr) return false; + return strcmp(s1, s2) == 0; + } + + /// @brief Compares cstring equality (case-insensitive) - uses toupper(char) + /// Dont use strcasecmp because of CRT (VC++) + static bool cStringCaseEq(const char* s1, const char* s2) { + if (s1 == nullptr && s2 == nullptr) return true; + if (s1 == nullptr || s2 == nullptr) return false; + if (strlen(s1) != strlen(s2)) return false; + while (*s1 != '\0' && *s2 != '\0') { + if (::toupper(*s1) != ::toupper(*s2)) return false; + ++s1; + ++s2; + } + return true; + } + + /// @brief Returns true if c exist in str + static inline bool contains(const char* str, char c) { + for (; *str; ++str) { + if (*str == c) + return true; + } + return false; + } + + static inline char* convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded = true) { + char localBuff[10] = ""; + char* p = localBuff + sizeof(localBuff) - 2; + if (n > 0) { + for (; n > 0 && p > localBuff && len > 0; n /= 10, --len) + *--p = static_cast(n % 10 + '0'); + } else { + *--p = '0'; + --len; + } + if (zeroPadded) + while (p > localBuff && len-- > 0) *--p = static_cast('0'); + return addToBuff(p, buf, bufLim); + } + + static inline char* addToBuff(const char* str, char* buf, const char* bufLim) { + while ((buf < bufLim) && ((*buf = *str++) != '\0')) + ++buf; + return buf; + } + + static inline char* clearBuff(char buff[], std::size_t lim) { + STRCPY(buff, "", lim); + ELPP_UNUSED(lim); // For *nix we dont have anything using lim in above STRCPY macro + return buff; + } + + /// @brief Converst wchar* to char* + /// NOTE: Need to free return value after use! + static char* wcharPtrToCharPtr(const wchar_t* line) { + std::size_t len_ = wcslen(line) + 1; + char* buff_ = static_cast(malloc(len_ + 1)); +# if ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS) + std::wcstombs(buff_, line, len_); +# elif ELPP_OS_WINDOWS + std::size_t convCount_ = 0; + mbstate_t mbState_; + ::memset(static_cast(&mbState_), 0, sizeof(mbState_)); + wcsrtombs_s(&convCount_, buff_, len_, &line, len_, &mbState_); +# endif // ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS) + return buff_; + } +}; +/// @brief Operating System helper static class used internally. You should not use it. +class OS : base::StaticClass { +public: +#if ELPP_OS_WINDOWS + /// @brief Gets environment variables for Windows based OS. + /// We are not using getenv(const char*) because of CRT deprecation + /// @param varname Variable name to get environment variable value for + /// @return If variable exist the value of it otherwise nullptr + static const char* getWindowsEnvironmentVariable(const char* varname) { + const DWORD bufferLen = 50; + static char buffer[bufferLen]; + if (GetEnvironmentVariableA(varname, buffer, bufferLen)) { + return buffer; + } + return nullptr; + } +#endif // ELPP_OS_WINDOWS +#if ELPP_OS_ANDROID + /// @brief Reads android property value + static inline std::string getProperty(const char* prop) { + char propVal[PROP_VALUE_MAX + 1]; + int ret = __system_property_get(prop, propVal); + return ret == 0 ? std::string() : std::string(propVal); + } + + /// @brief Reads android device name + static std::string getDeviceName(void) { + std::stringstream ss; + std::string manufacturer = getProperty("ro.product.manufacturer"); + std::string model = getProperty("ro.product.model"); + if (manufacturer.empty() || model.empty()) { + return std::string(); + } + ss << manufacturer << "-" << model; + return ss.str(); + } +#endif // ELPP_OS_ANDROID + + /// @brief Runs command on terminal and returns the output. + /// + /// @detail This is applicable only on unix based systems, for all other OS, an empty string is returned. + /// @param command Bash command + /// @return Result of bash output or empty string if no result found. + static const std::string getBashOutput(const char* command) { +#if (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN) + if (command == nullptr) { + return std::string(); + } + FILE* proc = nullptr; + if ((proc = popen(command, "r")) == nullptr) { + ELPP_INTERNAL_ERROR("\nUnable to run command [" << command << "]", true); + return std::string(); + } + char hBuff[4096]; + if (fgets(hBuff, sizeof(hBuff), proc) != nullptr) { + pclose(proc); + if (hBuff[strlen(hBuff) - 1] == '\n') { + hBuff[strlen(hBuff) - 1] = '\0'; + } + return std::string(hBuff); + } + return std::string(); +#else + ELPP_UNUSED(command); + return std::string(); +#endif // (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN) + } + + /// @brief Gets environment variable. This is cross-platform and CRT safe (for VC++) + /// @param variableName Environment variable name + /// @param defaultVal If no environment variable or value found the value to return by default + /// @param alternativeBashCommand If environment variable not found what would be alternative bash command + /// in order to look for value user is looking for. E.g, for 'user' alternative command will 'whoami' + static std::string getEnvironmentVariable(const char* variableName, const char* defaultVal, const char* alternativeBashCommand = nullptr) { +#if ELPP_OS_UNIX + const char* val = getenv(variableName); +#elif ELPP_OS_WINDOWS + const char* val = getWindowsEnvironmentVariable(variableName); +#endif // ELPP_OS_UNIX + if ((val == nullptr) || ((strcmp(val, "") == 0))) { +#if ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH) + // Try harder on unix-based systems + std::string valBash = base::utils::OS::getBashOutput(alternativeBashCommand); + if (valBash.empty()) { + return std::string(defaultVal); + } else { + return valBash; + } +#elif ELPP_OS_WINDOWS || ELPP_OS_UNIX + ELPP_UNUSED(alternativeBashCommand); + return std::string(defaultVal); +#endif // ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH) + } + return std::string(val); + } + /// @brief Gets current username. + static inline std::string currentUser(void) { +#if ELPP_OS_UNIX && !ELPP_OS_ANDROID + return getEnvironmentVariable("USER", base::consts::kUnknownUser, "whoami"); +#elif ELPP_OS_WINDOWS + return getEnvironmentVariable("USERNAME", base::consts::kUnknownUser); +#elif ELPP_OS_ANDROID + ELPP_UNUSED(base::consts::kUnknownUser); + return std::string("android"); +#else + return std::string(); +#endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID + } + + /// @brief Gets current host name or computer name. + /// + /// @detail For android systems this is device name with its manufacturer and model seperated by hyphen + static inline std::string currentHost(void) { +#if ELPP_OS_UNIX && !ELPP_OS_ANDROID + return getEnvironmentVariable("HOSTNAME", base::consts::kUnknownHost, "hostname"); +#elif ELPP_OS_WINDOWS + return getEnvironmentVariable("COMPUTERNAME", base::consts::kUnknownHost); +#elif ELPP_OS_ANDROID + ELPP_UNUSED(base::consts::kUnknownHost); + return getDeviceName(); +#else + return std::string(); +#endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID + } + /// @brief Whether or not terminal supports colors + static inline bool termSupportsColor(void) { + std::string term = getEnvironmentVariable("TERM", ""); + return term == "xterm" || term == "xterm-color" || term == "xterm-256color" || + term == "screen" || term == "linux" || term == "cygwin"; + } +}; +extern std::string s_currentUser; +extern std::string s_currentHost; +extern bool s_termSupportsColor; +#define ELPP_INITI_BASIC_DECLR \ + namespace el {\ + namespace base {\ + namespace utils {\ + std::string s_currentUser = el::base::utils::OS::currentUser(); \ + std::string s_currentHost = el::base::utils::OS::currentHost(); \ + bool s_termSupportsColor = el::base::utils::OS::termSupportsColor(); \ + }\ + }\ + } +/// @brief Contains utilities for cross-platform date/time. This class make use of el::base::utils::Str +class DateTime : base::StaticClass { +public: + /// @brief Cross platform gettimeofday for Windows and unix platform. This can be used to determine current millisecond. + /// + /// @detail For unix system it uses gettimeofday(timeval*, timezone*) and for Windows, a seperate implementation is provided + /// @param [in,out] tv Pointer that gets updated + static void gettimeofday(struct timeval* tv) { +#if ELPP_OS_WINDOWS + if (tv != nullptr) { +# if ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS) + const unsigned __int64 delta_ = 11644473600000000Ui64; +# else + const unsigned __int64 delta_ = 11644473600000000ULL; +# endif // ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS) + const double secOffSet = 0.000001; + const unsigned long usecOffSet = 1000000; + FILETIME fileTime; + GetSystemTimeAsFileTime(&fileTime); + unsigned __int64 present = 0; + present |= fileTime.dwHighDateTime; + present = present << 32; + present |= fileTime.dwLowDateTime; + present /= 10; // mic-sec + // Subtract the difference + present -= delta_; + tv->tv_sec = static_cast(present * secOffSet); + tv->tv_usec = static_cast(present % usecOffSet); + } +#else + ::gettimeofday(tv, nullptr); +#endif // ELPP_OS_WINDOWS + } + + /// @brief Gets current date and time with milliseconds. + /// @param format User provided date/time format + /// @param msWidth A pointer to base::MillisecondsWidth from configuration (non-null) + /// @returns string based date time in specified format. + static inline std::string getDateTime(const char* format, const base::MillisecondsWidth* msWidth) { + struct timeval currTime; + gettimeofday(&currTime); + struct ::tm timeInfo; + buildTimeInfo(&currTime, &timeInfo); + const int kBuffSize = 30; + char buff_[kBuffSize] = ""; + parseFormat(buff_, kBuffSize, format, &timeInfo, static_cast(currTime.tv_usec / msWidth->m_offset), msWidth); + return std::string(buff_); + } + + /// @brief Formats time to get unit accordingly, units like second if > 1000 or minutes if > 60000 etc + static base::type::string_t formatTime(unsigned long long time, base::TimestampUnit timestampUnit) { + double result = static_cast(time); + base::type::EnumType start = static_cast(timestampUnit); + const base::type::char_t* unit = base::consts::kTimeFormats[start].unit; + for (base::type::EnumType i = start; i < base::consts::kTimeFormatsCount - 1; ++i) { + if (result <= base::consts::kTimeFormats[i].value) { + break; + } + result /= base::consts::kTimeFormats[i].value; + unit = base::consts::kTimeFormats[i + 1].unit; + } + base::type::stringstream_t ss; + ss << result << " " << unit; + return ss.str(); + } + + /// @brief Gets time difference in milli/micro second depending on timestampUnit + static inline unsigned long long getTimeDifference(const struct timeval& endTime, const struct timeval& startTime, base::TimestampUnit timestampUnit) { + if (timestampUnit == base::TimestampUnit::Microsecond) { + return static_cast(static_cast(1000000 * endTime.tv_sec + endTime.tv_usec) - + static_cast(1000000 * startTime.tv_sec + startTime.tv_usec)); + } else { + return static_cast((((endTime.tv_sec - startTime.tv_sec) * 1000000) + (endTime.tv_usec - startTime.tv_usec)) / 1000); + } + } + +private: + static inline struct ::tm* buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo) { +#if ELPP_OS_UNIX + time_t rawTime = currTime->tv_sec; + ::localtime_r(&rawTime, timeInfo); + return timeInfo; +#else +# if ELPP_COMPILER_MSVC + ELPP_UNUSED(currTime); + time_t t; + _time64(&t); + localtime_s(timeInfo, &t); + return timeInfo; +# else + // For any other compilers that don't have CRT warnings issue e.g, MinGW or TDM GCC- we use different method + time_t rawTime = currTime->tv_sec; + struct tm* tmInf = localtime(&rawTime); + *timeInfo = *tmInf; + return timeInfo; +# endif // ELPP_COMPILER_MSVC +#endif // ELPP_OS_UNIX + } + static char* parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo, + std::size_t msec, const base::MillisecondsWidth* msWidth) { + const char* bufLim = buf + bufSz; + for (; *format; ++format) { + if (*format == base::consts::kFormatSpecifierChar) { + switch (*++format) { + case base::consts::kFormatSpecifierChar: // Escape + break; + case '\0': // End + --format; + break; + case 'd': // Day + buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mday, 2, buf, bufLim); + continue; + case 'a': // Day of week (short) + buf = base::utils::Str::addToBuff(base::consts::kDaysAbbrev[tInfo->tm_wday], buf, bufLim); + continue; + case 'A': // Day of week (long) + buf = base::utils::Str::addToBuff(base::consts::kDays[tInfo->tm_wday], buf, bufLim); + continue; + case 'M': // month + buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mon + 1, 2, buf, bufLim); + continue; + case 'b': // month (short) + buf = base::utils::Str::addToBuff(base::consts::kMonthsAbbrev[tInfo->tm_mon], buf, bufLim); + continue; + case 'B': // month (long) + buf = base::utils::Str::addToBuff(base::consts::kMonths[tInfo->tm_mon], buf, bufLim); + continue; + case 'y': // year (two digits) + buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 2, buf, bufLim); + continue; + case 'Y': // year (four digits) + buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 4, buf, bufLim); + continue; + case 'h': // hour (12-hour) + buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour % 12, 2, buf, bufLim); + continue; + case 'H': // hour (24-hour) + buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour, 2, buf, bufLim); + continue; + case 'm': // minute + buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_min, 2, buf, bufLim); + continue; + case 's': // second + buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_sec, 2, buf, bufLim); + continue; + case 'z': // milliseconds + case 'g': + buf = base::utils::Str::convertAndAddToBuff(msec, msWidth->m_width, buf, bufLim); + continue; + case 'F': // AM/PM + buf = base::utils::Str::addToBuff((tInfo->tm_hour >= 12) ? base::consts::kPm : base::consts::kAm, buf, bufLim); + continue; + default: + continue; + } + } + if (buf == bufLim) break; + *buf++ = *format; + } + return buf; + } +}; +/// @brief Command line arguments for application if specified using el::Helpers::setArgs(..) or START_EASYLOGGINGPP(..) +class CommandLineArgs { +public: + CommandLineArgs(void) { + setArgs(0, static_cast(nullptr)); + } + CommandLineArgs(int argc, const char** argv) { + setArgs(argc, argv); + } + CommandLineArgs(int argc, char** argv) { + setArgs(argc, argv); + } + virtual ~CommandLineArgs(void) {} + /// @brief Sets arguments and parses them + inline void setArgs(int argc, const char** argv) { + setArgs(argc, const_cast(argv)); + } + /// @brief Sets arguments and parses them + inline void setArgs(int argc, char** argv) { + m_params.clear(); + m_paramsWithValue.clear(); + if (argc == 0 || argv == nullptr) { + return; + } + m_argc = argc; + m_argv = argv; + for (int i = 1; i < m_argc; ++i) { + const char* v = (strstr(m_argv[i], "=")); + if (v != nullptr && strlen(v) > 0) { + std::string key = std::string(m_argv[i]); + key = key.substr(0, key.find_first_of('=')); + if (hasParamWithValue(key.c_str())) { + ELPP_INTERNAL_INFO(1, "Skipping [" << key << "] arg since it already has value [" + << getParamValue(key.c_str()) << "]"); + } else { + m_paramsWithValue.insert(std::make_pair(key, std::string(v + 1))); + } + } + if (v == nullptr) { + if (hasParam(m_argv[i])) { + ELPP_INTERNAL_INFO(1, "Skipping [" << m_argv[i] << "] arg since it already exists"); + } else { + m_params.push_back(std::string(m_argv[i])); + } + } + } + } + /// @brief Returns true if arguments contain paramKey with a value (seperated by '=') + inline bool hasParamWithValue(const char* paramKey) const { + return m_paramsWithValue.find(std::string(paramKey)) != m_paramsWithValue.end(); + } + /// @brief Returns value of arguments + /// @see hasParamWithValue(const char*) + inline const char* getParamValue(const char* paramKey) const { + return m_paramsWithValue.find(std::string(paramKey))->second.c_str(); + } + /// @brief Return true if arguments has a param (not having a value) i,e without '=' + inline bool hasParam(const char* paramKey) const { + return std::find(m_params.begin(), m_params.end(), std::string(paramKey)) != m_params.end(); + } + /// @brief Returns true if no params available. This exclude argv[0] + inline bool empty(void) const { + return m_params.empty() && m_paramsWithValue.empty(); + } + /// @brief Returns total number of arguments. This exclude argv[0] + inline std::size_t size(void) const { + return m_params.size() + m_paramsWithValue.size(); + } + inline friend base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c) { + for (int i = 1; i < c.m_argc; ++i) { + os << ELPP_LITERAL("[") << c.m_argv[i] << ELPP_LITERAL("]"); + if (i < c.m_argc - 1) { + os << ELPP_LITERAL(" "); + } + } + return os; + } + +private: + int m_argc; + char** m_argv; + std::map m_paramsWithValue; + std::vector m_params; +}; +/// @brief Abstract registry (aka repository) that provides basic interface for pointer repository specified by T_Ptr type. +/// +/// @detail Most of the functions are virtual final methods but anything implementing this abstract class should implement +/// unregisterAll() and deepCopy(const AbstractRegistry&) and write registerNew() method according to container +/// and few more methods; get() to find element, unregister() to unregister single entry. +/// Please note that this is thread-unsafe and should also implement thread-safety mechanisms in implementation. +template +class AbstractRegistry : public base::threading::ThreadSafe { +public: + typedef typename Container::iterator iterator; + typedef typename Container::const_iterator const_iterator; + + /// @brief Default constructor + AbstractRegistry(void) {} + + /// @brief Move constructor that is useful for base classes + AbstractRegistry(AbstractRegistry&& sr) { + if (this == &sr) { + return; + } + unregisterAll(); + m_list = std::move(sr.m_list); + } + + bool operator==(const AbstractRegistry& other) { + if (size() != other.size()) { + return false; + } + for (std::size_t i = 0; i < m_list.size(); ++i) { + if (m_list.at(i) != other.m_list.at(i)) { + return false; + } + } + return true; + } + + bool operator!=(const AbstractRegistry& other) { + if (size() != other.size()) { + return true; + } + for (std::size_t i = 0; i < m_list.size(); ++i) { + if (m_list.at(i) != other.m_list.at(i)) { + return true; + } + } + return false; + } + + /// @brief Assignment move operator + AbstractRegistry& operator=(AbstractRegistry&& sr) { + if (this == &sr) { + return *this; + } + unregisterAll(); + m_list = std::move(sr.m_list); + return *this; + } + + virtual ~AbstractRegistry(void) { + } + + /// @return Iterator pointer from start of repository + virtual inline iterator begin(void) ELPP_FINAL { + return m_list.begin(); + } + + /// @return Iterator pointer from end of repository + virtual inline iterator end(void) ELPP_FINAL { + return m_list.end(); + } + + + /// @return Constant iterator pointer from start of repository + virtual inline const_iterator cbegin(void) const ELPP_FINAL { + return m_list.cbegin(); + } + + /// @return End of repository + virtual inline const_iterator cend(void) const ELPP_FINAL { + return m_list.cend(); + } + + /// @return Whether or not repository is empty + virtual inline bool empty(void) const ELPP_FINAL { + return m_list.empty(); + } + + /// @return Size of repository + virtual inline std::size_t size(void) const ELPP_FINAL { + return m_list.size(); + } + + /// @brief Returns underlying container by reference + virtual inline Container& list(void) ELPP_FINAL { + return m_list; + } + + /// @brief Returns underlying container by constant reference. + virtual inline const Container& list(void) const ELPP_FINAL { + return m_list; + } + + /// @brief Unregisters all the pointers from current repository. + virtual void unregisterAll(void) = 0; + +protected: + virtual void deepCopy(const AbstractRegistry&) = 0; + void reinitDeepCopy(const AbstractRegistry& sr) { + unregisterAll(); + deepCopy(sr); + } + +private: + Container m_list; +}; + +/// @brief A pointer registry mechanism to manage memory and provide search functionalities. (non-predicate version) +/// +/// @detail NOTE: This is thread-unsafe implementation (although it contains lock function, it does not use these functions) +/// of AbstractRegistry. Any implementation of this class should be +/// explicitly (by using lock functions) +template +class Registry : public AbstractRegistry> { +public: + typedef typename Registry::iterator iterator; + typedef typename Registry::const_iterator const_iterator; + + Registry(void) {} + + /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor. + Registry(const Registry& sr) : AbstractRegistry>() { + if (this == &sr) { + return; + } + this->reinitDeepCopy(sr); + } + + /// @brief Assignment operator that unregisters all the existing registeries and deeply copies each of repo element + /// @see unregisterAll() + /// @see deepCopy(const AbstractRegistry&) + Registry& operator=(const Registry& sr) { + if (this == &sr) { + return *this; + } + this->reinitDeepCopy(sr); + return *this; + } + + virtual ~Registry(void) { + unregisterAll(); + } + +protected: + virtual inline void unregisterAll(void) ELPP_FINAL { + if (!this->empty()) { + for (auto&& curr : this->list()) { + base::utils::safeDelete(curr.second); + } + this->list().clear(); + } + } + + /// @brief Registers new registry to repository. + virtual inline void registerNew(const T_Key& uniqKey, T_Ptr* ptr) ELPP_FINAL { + unregister(uniqKey); + this->list().insert(std::make_pair(uniqKey, ptr)); + } + + /// @brief Unregisters single entry mapped to specified unique key + inline void unregister(const T_Key& uniqKey) { + T_Ptr* existing = get(uniqKey); + if (existing != nullptr) { + base::utils::safeDelete(existing); + this->list().erase(uniqKey); + } + } + + /// @brief Gets pointer from repository. If none found, nullptr is returned. + inline T_Ptr* get(const T_Key& uniqKey) { + iterator it = this->list().find(uniqKey); + return it == this->list().end() + ? nullptr + : it->second; + } + +private: + virtual inline void deepCopy(const AbstractRegistry>& sr) ELPP_FINAL { + for (const_iterator it = sr.cbegin(); it != sr.cend(); ++it) { + registerNew(it->first, new T_Ptr(*it->second)); + } + } +}; + +/// @brief A pointer registry mechanism to manage memory and provide search functionalities. (predicate version) +/// +/// @detail NOTE: This is thread-unsafe implementation of AbstractRegistry. Any implementation of this class +/// should be made thread-safe explicitly +template +class RegistryWithPred : public AbstractRegistry> { +public: + typedef typename RegistryWithPred::iterator iterator; + typedef typename RegistryWithPred::const_iterator const_iterator; + + RegistryWithPred(void) { + } + + virtual ~RegistryWithPred(void) { + unregisterAll(); + } + + /// @brief Copy constructor that is useful for base classes. Try to avoid this constructor, use move constructor. + RegistryWithPred(const RegistryWithPred& sr) : AbstractRegistry>() { + if (this == &sr) { + return; + } + this->reinitDeepCopy(sr); + } + + /// @brief Assignment operator that unregisters all the existing registeries and deeply copies each of repo element + /// @see unregisterAll() + /// @see deepCopy(const AbstractRegistry&) + RegistryWithPred& operator=(const RegistryWithPred& sr) { + if (this == &sr) { + return *this; + } + this->reinitDeepCopy(sr); + return *this; + } + + friend inline base::type::ostream_t& operator<<(base::type::ostream_t& os, const RegistryWithPred& sr) { + for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) { + os << ELPP_LITERAL(" ") << **it << ELPP_LITERAL("\n"); + } + return os; + } + +protected: + virtual inline void unregisterAll(void) ELPP_FINAL { + if (!this->empty()) { + for (auto&& curr : this->list()) { + base::utils::safeDelete(curr); + } + this->list().clear(); + } + } + + virtual void unregister(T_Ptr*& ptr) ELPP_FINAL { + if (ptr) { + iterator iter = this->begin(); + for (; iter != this->end(); ++iter) { + if (ptr == *iter) { + break; + } + } + if (iter != this->end() && *iter != nullptr) { + this->list().erase(iter); + base::utils::safeDelete(*iter); + } + } + } + + virtual inline void registerNew(T_Ptr* ptr) ELPP_FINAL { + this->list().push_back(ptr); + } + + /// @brief Gets pointer from repository with speicifed arguments. Arguments are passed to predicate + /// in order to validate pointer. + template + inline T_Ptr* get(const T& arg1, const T2 arg2) { + iterator iter = std::find_if(this->list().begin(), this->list().end(), Pred(arg1, arg2)); + if (iter != this->list().end() && *iter != nullptr) { + return *iter; + } + return nullptr; + } + +private: + virtual inline void deepCopy(const AbstractRegistry>& sr) { + for (const_iterator it = sr.list().begin(); it != sr.list().end(); ++it) { + registerNew(new T_Ptr(**it)); + } + } +}; + +} // namespace utils +} // namespace base +/// @brief Base of Easylogging++ friendly class +/// +/// @detail After inheriting this class publicly, implement pure-virtual function `void log(std::ostream&) const` +class Loggable { +public: + virtual ~Loggable(void) {} + virtual void log(el::base::type::ostream_t&) const = 0; +private: + friend inline el::base::type::ostream_t& operator<<(el::base::type::ostream_t& os, const Loggable& loggable) { + loggable.log(os); + return os; + } +}; +namespace base { +/// @brief Represents log format containing flags and date format. This is used internally to start initial log +class LogFormat : public Loggable { +public: + LogFormat(void) : + m_level(Level::Unknown), + m_userFormat(base::type::string_t()), + m_format(base::type::string_t()), + m_dateTimeFormat(std::string()), + m_flags(0x0) { + } + + LogFormat(Level level, const base::type::string_t& format) + : m_level(level), m_userFormat(format) { + parseFromFormat(m_userFormat); + } + + LogFormat(const LogFormat& logFormat) { + m_level = logFormat.m_level; + m_userFormat = logFormat.m_userFormat; + m_format = logFormat.m_format; + m_dateTimeFormat = logFormat.m_dateTimeFormat; + m_flags = logFormat.m_flags; + } + + LogFormat(LogFormat&& logFormat) { + m_level = std::move(logFormat.m_level); + m_userFormat = std::move(logFormat.m_userFormat); + m_format = std::move(logFormat.m_format); + m_dateTimeFormat = std::move(logFormat.m_dateTimeFormat); + m_flags = std::move(logFormat.m_flags); + } + + LogFormat& operator=(const LogFormat& logFormat) { + m_level = logFormat.m_level; + m_userFormat = logFormat.m_userFormat; + m_dateTimeFormat = logFormat.m_dateTimeFormat; + m_flags = logFormat.m_flags; + return *this; + } + + virtual ~LogFormat(void) { + } + + inline bool operator==(const LogFormat& other) { + return m_level == other.m_level && m_userFormat == other.m_userFormat && m_format == other.m_format && + m_dateTimeFormat == other.m_dateTimeFormat && m_flags == other.m_flags; + } + + /// @brief Updates format to be used while logging. + /// @param userFormat User provided format + void parseFromFormat(const base::type::string_t& userFormat) { + // We make copy because we will be changing the format + // i.e, removing user provided date format from original format + // and then storing it. + base::type::string_t formatCopy = userFormat; + m_flags = 0x0; + auto conditionalAddFlag = [&](const base::type::char_t* specifier, base::FormatFlags flag) { + std::size_t foundAt = base::type::string_t::npos; + while ((foundAt = formatCopy.find(specifier, foundAt + 1)) != base::type::string_t::npos){ + if (foundAt > 0 && formatCopy[foundAt - 1] == base::consts::kFormatSpecifierChar) { + if (hasFlag(flag)) { + // If we already have flag we remove the escape chars so that '%%' is turned to '%' + // even after specifier resolution - this is because we only replaceFirst specifier + formatCopy.erase(foundAt > 0 ? foundAt - 1 : 0, 1); + ++foundAt; + } + } else { + if (!hasFlag(flag)) addFlag(flag); + } + } + }; + conditionalAddFlag(base::consts::kAppNameFormatSpecifier, base::FormatFlags::AppName); + conditionalAddFlag(base::consts::kSeverityLevelFormatSpecifier, base::FormatFlags::Level); + conditionalAddFlag(base::consts::kSeverityLevelShortFormatSpecifier, base::FormatFlags::LevelShort); + conditionalAddFlag(base::consts::kLoggerIdFormatSpecifier, base::FormatFlags::LoggerId); + conditionalAddFlag(base::consts::kThreadIdFormatSpecifier, base::FormatFlags::ThreadId); + conditionalAddFlag(base::consts::kLogFileFormatSpecifier, base::FormatFlags::File); + conditionalAddFlag(base::consts::kLogFileBaseFormatSpecifier, base::FormatFlags::FileBase); + conditionalAddFlag(base::consts::kLogLineFormatSpecifier, base::FormatFlags::Line); + conditionalAddFlag(base::consts::kLogLocationFormatSpecifier, base::FormatFlags::Location); + conditionalAddFlag(base::consts::kLogFunctionFormatSpecifier, base::FormatFlags::Function); + conditionalAddFlag(base::consts::kCurrentUserFormatSpecifier, base::FormatFlags::User); + conditionalAddFlag(base::consts::kCurrentHostFormatSpecifier, base::FormatFlags::Host); + conditionalAddFlag(base::consts::kMessageFormatSpecifier, base::FormatFlags::LogMessage); + conditionalAddFlag(base::consts::kVerboseLevelFormatSpecifier, base::FormatFlags::VerboseLevel); + // For date/time we need to extract user's date format first + std::size_t dateIndex = std::string::npos; + if ((dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier)) != std::string::npos) { + while (dateIndex > 0 && formatCopy[dateIndex - 1] == base::consts::kFormatSpecifierChar) { + dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier, dateIndex + 1); + } + if (dateIndex != std::string::npos) { + addFlag(base::FormatFlags::DateTime); + updateDateFormat(dateIndex, formatCopy); + } + } + m_format = formatCopy; + updateFormatSpec(); + } + + inline Level level(void) const { + return m_level; + } + + inline const base::type::string_t& userFormat(void) const { + return m_userFormat; + } + + inline const base::type::string_t& format(void) const { + return m_format; + } + + inline const std::string& dateTimeFormat(void) const { + return m_dateTimeFormat; + } + + inline base::type::EnumType flags(void) const { + return m_flags; + } + + inline bool hasFlag(base::FormatFlags flag) const { + return base::utils::hasFlag(flag, m_flags); + } + + virtual void log(el::base::type::ostream_t& os) const { + os << m_format; + } + +protected: + /// @brief Updates date time format if available in currFormat. + /// @param index Index where %datetime, %date or %time was found + /// @param [in,out] currFormat current format that is being used to format + virtual void updateDateFormat(std::size_t index, base::type::string_t& currFormat) ELPP_FINAL { + if (hasFlag(base::FormatFlags::DateTime)) { + index += ELPP_STRLEN(base::consts::kDateTimeFormatSpecifier); + } + const base::type::char_t* ptr = currFormat.c_str() + index; + if ((currFormat.size() > index) && (ptr[0] == '{')) { + // User has provided format for date/time + ++ptr; + int count = 1; // Start by 1 in order to remove starting brace + std::stringstream ss; + for (; *ptr; ++ptr, ++count) { + if (*ptr == '}') { + ++count; // In order to remove ending brace + break; + } + ss << *ptr; + } + currFormat.erase(index, count); + m_dateTimeFormat = ss.str(); + } else { + // No format provided, use default + if (hasFlag(base::FormatFlags::DateTime)) { + m_dateTimeFormat = std::string(base::consts::kDefaultDateTimeFormat); + } + } + } + + /// @brief Updates %level from format. This is so that we dont have to do it at log-writing-time. It uses m_format and m_level + virtual void updateFormatSpec(void) ELPP_FINAL { + // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. + if (m_level == Level::Debug) { + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, + base::consts::kDebugLevelLogValue); + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, + base::consts::kDebugLevelShortLogValue); + } else if (m_level == Level::Info) { + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, + base::consts::kInfoLevelLogValue); + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, + base::consts::kInfoLevelShortLogValue); + } else if (m_level == Level::Warning) { + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, + base::consts::kWarningLevelLogValue); + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, + base::consts::kWarningLevelShortLogValue); + } else if (m_level == Level::Error) { + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, + base::consts::kErrorLevelLogValue); + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, + base::consts::kErrorLevelShortLogValue); + } else if (m_level == Level::Fatal) { + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, + base::consts::kFatalLevelLogValue); + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, + base::consts::kFatalLevelShortLogValue); + } else if (m_level == Level::Verbose) { + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, + base::consts::kVerboseLevelLogValue); + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, + base::consts::kVerboseLevelShortLogValue); + } else if (m_level == Level::Trace) { + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, + base::consts::kTraceLevelLogValue); + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, + base::consts::kTraceLevelShortLogValue); + } + if (hasFlag(base::FormatFlags::User)) { + std::string s = base::utils::s_currentUser; + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentUserFormatSpecifier, + base::utils::s_currentUser); + } + if (hasFlag(base::FormatFlags::Host)) { + base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentHostFormatSpecifier, + base::utils::s_currentHost); + } + // Ignore Level::Global and Level::Unknown + } + + inline void addFlag(base::FormatFlags flag) { + base::utils::addFlag(flag, &m_flags); + } + +private: + Level m_level; + base::type::string_t m_userFormat; + base::type::string_t m_format; + std::string m_dateTimeFormat; + base::type::EnumType m_flags; + friend class el::Logger; // To resolve loggerId format specifier easily +}; +} // namespace base +/// @brief Resolving function for format specifier +typedef std::function FormatSpecifierValueResolver; +/// @brief User-provided custom format specifier +/// @see el::Helpers::installCustomFormatSpecifier +/// @see FormatSpecifierValueResolver +class CustomFormatSpecifier { +public: + CustomFormatSpecifier(const char* formatSpecifier, const FormatSpecifierValueResolver& resolver) : + m_formatSpecifier(formatSpecifier), m_resolver(resolver) {} + inline const char* formatSpecifier(void) const { return m_formatSpecifier; } + inline const FormatSpecifierValueResolver& resolver(void) const { return m_resolver; } + inline bool operator==(const char* formatSpecifier) { + return strcmp(m_formatSpecifier, formatSpecifier) == 0; + } + +private: + const char* m_formatSpecifier; + FormatSpecifierValueResolver m_resolver; +}; +/// @brief Represents single configuration that has representing level, configuration type and a string based value. +/// +/// @detail String based value means any value either its boolean, integer or string itself, it will be embedded inside quotes +/// and will be parsed later. +/// +/// Consider some examples below: +/// * el::Configuration confEnabledInfo(el::Level::Info, el::ConfigurationType::Enabled, "true"); +/// * el::Configuration confMaxLogFileSizeInfo(el::Level::Info, el::ConfigurationType::MaxLogFileSize, "2048"); +/// * el::Configuration confFilenameInfo(el::Level::Info, el::ConfigurationType::Filename, "/var/log/my.log"); +class Configuration : public Loggable { +public: + Configuration(const Configuration& c) : + m_level(c.m_level), + m_configurationType(c.m_configurationType), + m_value(c.m_value) { + } + + Configuration& operator=(const Configuration& c) { + m_level = c.m_level; + m_configurationType = c.m_configurationType; + m_value = c.m_value; + return *this; + } + + virtual ~Configuration(void) { + } + + /// @brief Full constructor used to sets value of configuration + Configuration(Level level, ConfigurationType configurationType, const std::string& value) : + m_level(level), + m_configurationType(configurationType), + m_value(value) { + } + + /// @brief Gets level of current configuration + inline Level level(void) const { + return m_level; + } + + /// @brief Gets configuration type of current configuration + inline ConfigurationType configurationType(void) const { + return m_configurationType; + } + + /// @brief Gets string based configuration value + inline const std::string& value(void) const { + return m_value; + } + + /// @brief Set string based configuration value + /// @param value Value to set. Values have to be std::string; For boolean values use "true", "false", for any integral values + /// use them in quotes. They will be parsed when configuring + inline void setValue(const std::string& value) { + m_value = value; + } + + virtual inline void log(el::base::type::ostream_t& os) const { + os << LevelHelper::convertToString(m_level) + << ELPP_LITERAL(" ") << ConfigurationTypeHelper::convertToString(m_configurationType) + << ELPP_LITERAL(" = ") << m_value.c_str(); + } + + /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it. + class Predicate { + public: + Predicate(Level level, ConfigurationType configurationType) : + m_level(level), + m_configurationType(configurationType) { + } + + inline bool operator()(const Configuration* conf) const { + return ((conf != nullptr) && (conf->level() == m_level) && (conf->configurationType() == m_configurationType)); + } + + private: + Level m_level; + ConfigurationType m_configurationType; + }; + +private: + Level m_level; + ConfigurationType m_configurationType; + std::string m_value; +}; + +/// @brief Thread-safe Configuration repository +/// +/// @detail This repository represents configurations for all the levels and configuration type mapped to a value. +class Configurations : public base::utils::RegistryWithPred { +public: + /// @brief Default constructor with empty repository + Configurations(void) : + m_configurationFile(std::string()), + m_isFromFile(false) { + } + + /// @brief Constructor used to set configurations using configuration file. + /// @param configurationFile Full path to configuration file + /// @param useDefaultsForRemaining Lets you set the remaining configurations to default. + /// @param base If provided, this configuration will be based off existing repository that this argument is pointing to. + /// @see parseFromFile(const std::string&, Configurations* base) + /// @see setRemainingToDefault() + Configurations(const std::string& configurationFile, bool useDefaultsForRemaining = true, Configurations* base = nullptr) : + m_configurationFile(configurationFile), + m_isFromFile(false) { + parseFromFile(configurationFile, base); + if (useDefaultsForRemaining) { + setRemainingToDefault(); + } + } + + virtual ~Configurations(void) { + } + + /// @brief Parses configuration from file. + /// @param configurationFile Full path to configuration file + /// @param base Configurations to base new configuration repository off. This value is used when you want to use + /// existing Configurations to base all the values and then set rest of configuration via configuration file. + /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you + /// do not proceed without successful parse. + inline bool parseFromFile(const std::string& configurationFile, Configurations* base = nullptr) { + // We initial assertion with true because if we have assertion diabled, we want to pass this + // check and if assertion is enabled we will have values re-assigned any way. + bool assertionPassed = true; + ELPP_ASSERT((assertionPassed = base::utils::File::pathExists(configurationFile.c_str(), true)), + "Configuration file [" << configurationFile << "] does not exist!"); + if (!assertionPassed) { + return false; + } + bool success = Parser::parseFromFile(configurationFile, this, base); + m_isFromFile = success; + return success; + } + + /// @brief Parse configurations from configuration string. + /// + /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary + /// new line characters are provided. + /// @param base Configurations to base new configuration repository off. This value is used when you want to use + /// existing Configurations to base all the values and then set rest of configuration via configuration text. + /// @return True if successfully parsed, false otherwise. You may define 'ELPP_DEBUG_ASSERT_FAILURE' to make sure you + /// do not proceed without successful parse. + inline bool parseFromText(const std::string& configurationsString, Configurations* base = nullptr) { + bool success = Parser::parseFromText(configurationsString, this, base); + if (success) { + m_isFromFile = false; + } + return success; + } + + /// @brief Sets configuration based-off an existing configurations. + /// @param base Pointer to existing configurations. + inline void setFromBase(Configurations* base) { + if (base == nullptr || base == this) { + return; + } + base::threading::ScopedLock scopedLock(base->lock()); + for (Configuration*& conf : base->list()) { + set(conf); + } + } + + /// @brief Determines whether or not specified configuration type exists in the repository. + /// + /// @detail Returns as soon as first level is found. + /// @param configurationType Type of configuration to check existence for. + bool hasConfiguration(ConfigurationType configurationType) { + base::type::EnumType lIndex = LevelHelper::kMinValid; + bool result = false; + LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { + if (hasConfiguration(LevelHelper::castFromInt(lIndex), configurationType)) { + result = true; + } + return result; + }); + return result; + } + + /// @brief Determines whether or not specified configuration type exists for specified level + /// @param level Level to check + /// @param configurationType Type of configuration to check existence for. + inline bool hasConfiguration(Level level, ConfigurationType configurationType) { + base::threading::ScopedLock scopedLock(lock()); +#if ELPP_COMPILER_INTEL + // We cant specify template types here, Intel C++ throws compilation error + // "error: type name is not allowed" + return RegistryWithPred::get(level, configurationType) != nullptr; +#else + return RegistryWithPred::get(level, configurationType) != nullptr; +#endif // ELPP_COMPILER_INTEL + } + + /// @brief Sets value of configuration for specified level. + /// + /// @detail Any existing configuration for specified level will be replaced. Also note that configuration types + /// ConfigurationType::MillisecondsWidth and ConfigurationType::PerformanceTracking will be ignored if not set for + /// Level::Global because these configurations are not dependant on level. + /// @param level Level to set configuration for (el::Level). + /// @param configurationType Type of configuration (el::ConfigurationType) + /// @param value A string based value. Regardless of what the data type of configuration is, it will always be string + /// from users' point of view. This is then parsed later to be used internally. + /// @see Configuration::setValue(const std::string& value) + /// @see el::Level + /// @see el::ConfigurationType + inline void set(Level level, ConfigurationType configurationType, const std::string& value) { + base::threading::ScopedLock scopedLock(lock()); + unsafeSet(level, configurationType, value); // This is not unsafe anymore as we have locked mutex + if (level == Level::Global) { + unsafeSetGlobally(configurationType, value, false); // Again this is not unsafe either + } + } + + /// @brief Sets single configuration based on other single configuration. + /// @see set(Level level, ConfigurationType configurationType, const std::string& value) + inline void set(Configuration* conf) { + if (conf == nullptr) { + return; + } + set(conf->level(), conf->configurationType(), conf->value()); + } + + inline Configuration* get(Level level, ConfigurationType configurationType) { + base::threading::ScopedLock scopedLock(lock()); + return RegistryWithPred::get(level, configurationType); + } + + /// @brief Sets configuration for all levels. + /// @param configurationType Type of configuration + /// @param value String based value + /// @see Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) + inline void setGlobally(ConfigurationType configurationType, const std::string& value) { + setGlobally(configurationType, value, false); + } + + /// @brief Clears repository so that all the configurations are unset + inline void clear(void) { + base::threading::ScopedLock scopedLock(lock()); + unregisterAll(); + } + + /// @brief Gets configuration file used in parsing this configurations. + /// + /// @detail If this repository was set manually or by text this returns empty string. + inline const std::string& configurationFile(void) const { + return m_configurationFile; + } + + /// @brief Sets configurations to "factory based" configurations. + void setToDefault(void) { + setGlobally(ConfigurationType::Enabled, std::string("true"), true); +#if !defined(ELPP_NO_DEFAULT_LOG_FILE) + setGlobally(ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile), true); +#else + ELPP_UNUSED(base::consts::kDefaultLogFile); +#endif // !defined(ELPP_NO_DEFAULT_LOG_FILE) + setGlobally(ConfigurationType::ToFile, std::string("true"), true); + setGlobally(ConfigurationType::ToStandardOutput, std::string("true"), true); + setGlobally(ConfigurationType::MillisecondsWidth, std::string("3"), true); + setGlobally(ConfigurationType::PerformanceTracking, std::string("true"), true); + setGlobally(ConfigurationType::MaxLogFileSize, std::string("0"), true); + setGlobally(ConfigurationType::LogFlushThreshold, std::string("0"), true); + + setGlobally(ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"), true); + set(Level::Debug, ConfigurationType::Format, std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg")); + // INFO and WARNING are set to default by Level::Global + set(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); + set(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); + set(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg")); + set(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg")); + } + + /// @brief Lets you set the remaining configurations to default. + /// + /// @detail By remaining, it means that the level/type a configuration does not exist for. + /// This function is useful when you want to minimize chances of failures, e.g, if you have a configuration file that sets + /// configuration for all the configurations except for Enabled or not, we use this so that ENABLED is set to default i.e, + /// true. If you dont do this explicitley (either by calling this function or by using second param in Constructor + /// and try to access a value, an error is thrown + void setRemainingToDefault(void) { + base::threading::ScopedLock scopedLock(lock()); + unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("true")); +#if !defined(ELPP_NO_DEFAULT_LOG_FILE) + unsafeSetIfNotExist(Level::Global, ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile)); +#endif // !defined(ELPP_NO_DEFAULT_LOG_FILE) + unsafeSetIfNotExist(Level::Global, ConfigurationType::ToFile, std::string("true")); + unsafeSetIfNotExist(Level::Global, ConfigurationType::ToStandardOutput, std::string("true")); + unsafeSetIfNotExist(Level::Global, ConfigurationType::MillisecondsWidth, std::string("3")); + unsafeSetIfNotExist(Level::Global, ConfigurationType::PerformanceTracking, std::string("true")); + unsafeSetIfNotExist(Level::Global, ConfigurationType::MaxLogFileSize, std::string("0")); + unsafeSetIfNotExist(Level::Global, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); + unsafeSetIfNotExist(Level::Debug, ConfigurationType::Format, + std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg")); + // INFO and WARNING are set to default by Level::Global + unsafeSetIfNotExist(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); + unsafeSetIfNotExist(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); + unsafeSetIfNotExist(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg")); + unsafeSetIfNotExist(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg")); + } + + /// @brief Parser used internally to parse configurations from file or text. + /// + /// @detail This class makes use of base::utils::Str. + /// You should not need this unless you are working on some tool for Easylogging++ + class Parser : base::StaticClass { + public: + /// @brief Parses configuration from file. + /// @param configurationFile Full path to configuration file + /// @param sender Sender configurations pointer. Usually 'this' is used from calling class + /// @param base Configurations to base new configuration repository off. This value is used when you want to use + /// existing Configurations to base all the values and then set rest of configuration via configuration file. + /// @return True if successfully parsed, false otherwise. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you + /// do not proceed without successful parse. + static bool parseFromFile(const std::string& configurationFile, Configurations* sender, Configurations* base = nullptr) { + sender->setFromBase(base); + std::ifstream fileStream_(configurationFile.c_str(), std::ifstream::in); + ELPP_ASSERT(fileStream_.is_open(), "Unable to open configuration file [" << configurationFile << "] for parsing."); + bool parsedSuccessfully = false; + std::string line = std::string(); + Level currLevel = Level::Unknown; + std::string currConfigStr = std::string(); + std::string currLevelStr = std::string(); + while (fileStream_.good()) { + std::getline(fileStream_, line); + parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender); + ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line); + } + return parsedSuccessfully; + } + + /// @brief Parse configurations from configuration string. + /// + /// @detail This configuration string has same syntax as configuration file contents. Make sure all the necessary + /// new line characters are provided. You may define '_STOP_ON_FIRSTELPP_ASSERTION' to make sure you + /// do not proceed without successful parse (This is recommended) + /// @param configurationsString + /// @param sender Sender configurations pointer. Usually 'this' is used from calling class + /// @param base Configurations to base new configuration repository off. This value is used when you want to use + /// existing Configurations to base all the values and then set rest of configuration via configuration text. + /// @return True if successfully parsed, false otherwise. + static bool parseFromText(const std::string& configurationsString, Configurations* sender, Configurations* base = nullptr) { + sender->setFromBase(base); + bool parsedSuccessfully = false; + std::stringstream ss(configurationsString); + std::string line = std::string(); + Level currLevel = Level::Unknown; + std::string currConfigStr = std::string(); + std::string currLevelStr = std::string(); + while (std::getline(ss, line)) { + parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender); + ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line); + } + return parsedSuccessfully; + } + + private: + friend class el::Loggers; + static void ignoreComments(std::string* line) { + std::size_t foundAt = 0; + std::size_t quotesStart = line->find("\""); + std::size_t quotesEnd = std::string::npos; + if (quotesStart != std::string::npos) { + quotesEnd = line->find("\"", quotesStart + 1); + while (quotesEnd != std::string::npos && line->at(quotesEnd - 1) == '\\') { + // Do not erase slash yet - we will erase it in parseLine(..) while loop + quotesEnd = line->find("\"", quotesEnd + 2); + } + } + if ((foundAt = line->find(base::consts::kConfigurationComment)) != std::string::npos) { + if (foundAt < quotesEnd) { + foundAt = line->find(base::consts::kConfigurationComment, quotesEnd + 1); + } + *line = line->substr(0, foundAt); + } + } + static inline bool isLevel(const std::string& line) { + return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLevel)); + } + + static inline bool isComment(const std::string& line) { + return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationComment)); + } + + static inline bool isConfig(const std::string& line) { + std::size_t assignment = line.find('='); + return line != "" && + (line[0] >= 65 || line[0] <= 90 || line[0] >= 97 || line[0] <= 122) && + (assignment != std::string::npos) && + (line.size() > assignment); + } + + static bool parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, Level* currLevel, Configurations* conf) { + ConfigurationType currConfig = ConfigurationType::Unknown; + std::string currValue = std::string(); + *line = base::utils::Str::trim(*line); + if (isComment(*line)) return true; + ignoreComments(line); + *line = base::utils::Str::trim(*line); + if (line->empty()) { + // Comment ignored + return true; + } + if (isLevel(*line)) { + if (line->size() <= 2) { + return true; + } + *currLevelStr = line->substr(1, line->size() - 2); + *currLevelStr = base::utils::Str::toUpper(*currLevelStr); + *currLevelStr = base::utils::Str::trim(*currLevelStr); + *currLevel = LevelHelper::convertFromString(currLevelStr->c_str()); + return true; + } + if (isConfig(*line)) { + std::size_t assignment = line->find('='); + *currConfigStr = line->substr(0, assignment); + *currConfigStr = base::utils::Str::toUpper(*currConfigStr); + *currConfigStr = base::utils::Str::trim(*currConfigStr); + currConfig = ConfigurationTypeHelper::convertFromString(currConfigStr->c_str()); + currValue = line->substr(assignment + 1); + currValue = base::utils::Str::trim(currValue); + std::size_t quotesStart = currValue.find("\"", 0); + std::size_t quotesEnd = std::string::npos; + if (quotesStart != std::string::npos) { + quotesEnd = currValue.find("\"", quotesStart + 1); + while (quotesEnd != std::string::npos && currValue.at(quotesEnd - 1) == '\\') { + currValue = currValue.erase(quotesEnd - 1, 1); + quotesEnd = currValue.find("\"", quotesEnd + 2); + } + } + if (quotesStart != std::string::npos && quotesEnd != std::string::npos) { + // Quote provided - check and strip if valid + ELPP_ASSERT((quotesStart < quotesEnd), "Configuration error - No ending quote found in [" + << currConfigStr << "]"); + ELPP_ASSERT((quotesStart + 1 != quotesEnd), "Empty configuration value for [" << currConfigStr << "]"); + if ((quotesStart != quotesEnd) && (quotesStart + 1 != quotesEnd)) { + // Explicit check in case if assertion is disabled + currValue = currValue.substr(quotesStart + 1, quotesEnd - 1); + } + } + } + ELPP_ASSERT(*currLevel != Level::Unknown, "Unrecognized severity level [" << *currLevelStr << "]"); + ELPP_ASSERT(currConfig != ConfigurationType::Unknown, "Unrecognized configuration [" << *currConfigStr << "]"); + if (*currLevel == Level::Unknown || currConfig == ConfigurationType::Unknown) { + return false; // unrecognizable level or config + } + conf->set(*currLevel, currConfig, currValue); + return true; + } + }; + +private: + std::string m_configurationFile; + bool m_isFromFile; + friend class el::Loggers; + + /// @brief Unsafely sets configuration if does not already exist + void unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value) { + Configuration* conf = RegistryWithPred::get(level, configurationType); + if (conf == nullptr) { + unsafeSet(level, configurationType, value); + } + } + + /// @brief Thread unsafe set + void unsafeSet(Level level, ConfigurationType configurationType, const std::string& value) { + Configuration* conf = RegistryWithPred::get(level, configurationType); + if (conf == nullptr) { + registerNew(new Configuration(level, configurationType, value)); + } else { + conf->setValue(value); + } + if (level == Level::Global) { + unsafeSetGlobally(configurationType, value, false); + } + } + + /// @brief Sets configurations for all levels including Level::Global if includeGlobalLevel is true + /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value) + void setGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel) { + if (includeGlobalLevel) { + set(Level::Global, configurationType, value); + } + base::type::EnumType lIndex = LevelHelper::kMinValid; + LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { + set(LevelHelper::castFromInt(lIndex), configurationType, value); + return false; // Do not break lambda function yet as we need to set all levels regardless + }); + } + + /// @brief Sets configurations (Unsafely) for all levels including Level::Global if includeGlobalLevel is true + /// @see Configurations::setGlobally(ConfigurationType configurationType, const std::string& value) + void unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel) { + if (includeGlobalLevel) { + unsafeSet(Level::Global, configurationType, value); + } + base::type::EnumType lIndex = LevelHelper::kMinValid; + LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { + unsafeSet(LevelHelper::castFromInt(lIndex), configurationType, value); + return false; // Do not break lambda function yet as we need to set all levels regardless + }); + } +}; + +namespace base { +typedef std::shared_ptr FileStreamPtr; +typedef std::map LogStreamsReferenceMap; +/// @brief Configurations with data types. +/// +/// @detail el::Configurations have string based values. This is whats used internally in order to read correct configurations. +/// This is to perform faster while writing logs using correct configurations. +/// +/// This is thread safe and final class containing non-virtual destructor (means nothing should inherit this class) +class TypedConfigurations : public base::threading::ThreadSafe { +public: + /// @brief Constructor to initialize (construct) the object off el::Configurations + /// @param configurations Configurations pointer/reference to base this typed configurations off. + /// @param logStreamsReference Use ELPP->registeredLoggers()->logStreamsReference() + TypedConfigurations(Configurations* configurations, base::LogStreamsReferenceMap* logStreamsReference) { + m_configurations = configurations; + m_logStreamsReference = logStreamsReference; + build(m_configurations); + } + + TypedConfigurations(const TypedConfigurations& other) { + this->m_configurations = other.m_configurations; + this->m_logStreamsReference = other.m_logStreamsReference; + build(m_configurations); + } + + virtual ~TypedConfigurations(void) { + } + + const Configurations* configurations(void) const { + return m_configurations; + } + + inline bool enabled(Level level) { + return getConfigByVal(level, &m_enabledMap, "enabled"); + } + + inline bool toFile(Level level) { + return getConfigByVal(level, &m_toFileMap, "toFile"); + } + + inline const std::string& filename(Level level) { + return getConfigByRef(level, &m_filenameMap, "filename"); + } + + inline bool toStandardOutput(Level level) { + return getConfigByVal(level, &m_toStandardOutputMap, "toStandardOutput"); + } + + inline const base::LogFormat& logFormat(Level level) { + return getConfigByRef(level, &m_logFormatMap, "logFormat"); + } + + inline const base::MillisecondsWidth& millisecondsWidth(Level level = Level::Global) { + return getConfigByRef(level, &m_millisecondsWidthMap, "millisecondsWidth"); + } + + inline bool performanceTracking(Level level = Level::Global) { + return getConfigByVal(level, &m_performanceTrackingMap, "performanceTracking"); + } + + inline base::type::fstream_t* fileStream(Level level) { + return getConfigByRef(level, &m_fileStreamMap, "fileStream").get(); + } + + inline std::size_t maxLogFileSize(Level level) { + return getConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize"); + } + + inline std::size_t logFlushThreshold(Level level) { + return getConfigByVal(level, &m_logFlushThresholdMap, "logFlushThreshold"); + } + +private: + Configurations* m_configurations; + std::map m_enabledMap; + std::map m_toFileMap; + std::map m_filenameMap; + std::map m_toStandardOutputMap; + std::map m_logFormatMap; + std::map m_millisecondsWidthMap; + std::map m_performanceTrackingMap; + std::map m_fileStreamMap; + std::map m_maxLogFileSizeMap; + std::map m_logFlushThresholdMap; + base::LogStreamsReferenceMap* m_logStreamsReference; + + friend class el::Helpers; + friend class el::base::MessageBuilder; + friend class el::base::Writer; + friend class el::base::DefaultLogDispatchCallback; + friend class el::base::LogDispatcher; + + template + inline Conf_T getConfigByVal(Level level, const std::map* confMap, const char* confName) { + base::threading::ScopedLock scopedLock(lock()); + return unsafeGetConfigByVal(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope + } + + template + inline Conf_T& getConfigByRef(Level level, std::map* confMap, const char* confName) { + base::threading::ScopedLock scopedLock(lock()); + return unsafeGetConfigByRef(level, confMap, confName); // This is not unsafe anymore - mutex locked in scope + } + + template + inline Conf_T unsafeGetConfigByVal(Level level, const std::map* confMap, const char* confName) { + ELPP_UNUSED(confName); + typename std::map::const_iterator it = confMap->find(level); + if (it == confMap->end()) { + try { + return confMap->at(Level::Global); + } catch (...) { + ELPP_INTERNAL_ERROR("Unable to get configuration [" << confName << "] for level [" + << LevelHelper::convertToString(level) << "]" + << std::endl << "Please ensure you have properly configured logger.", false); + return Conf_T(); + } + } + return it->second; + } + + template + inline Conf_T& unsafeGetConfigByRef(Level level, std::map* confMap, const char* confName) { + ELPP_UNUSED(confName); + typename std::map::iterator it = confMap->find(level); + if (it == confMap->end()) { + try { + return confMap->at(Level::Global); + } catch (...) { + ELPP_INTERNAL_ERROR("Unable to get configuration [" << confName << "] for level [" + << LevelHelper::convertToString(level) << "]" + << std::endl << "Please ensure you have properly configured logger.", false); + } + } + return it->second; + } + + template + void setValue(Level level, const Conf_T& value, std::map* confMap, bool includeGlobalLevel = true) { + // If map is empty and we are allowed to add into generic level (Level::Global), do it! + if (confMap->empty() && includeGlobalLevel) { + confMap->insert(std::make_pair(Level::Global, value)); + return; + } + // If same value exist in generic level already, dont add it to explicit level + typename std::map::iterator it = confMap->find(Level::Global); + if (it != confMap->end() && it->second == value) { + return; + } + // Now make sure we dont double up values if we really need to add it to explicit level + it = confMap->find(level); + if (it == confMap->end()) { + // Value not found for level, add new + confMap->insert(std::make_pair(level, value)); + } else { + // Value found, just update value + confMap->at(level) = value; + } + } + + void build(Configurations* configurations) { + base::threading::ScopedLock scopedLock(lock()); + auto getBool = [] (std::string boolStr) -> bool { // Pass by value for trimming + base::utils::Str::trim(boolStr); + return (boolStr == "TRUE" || boolStr == "true" || boolStr == "1"); + }; + std::vector withFileSizeLimit; + for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) { + Configuration* conf = *it; + // We cannot use switch on strong enums because Intel C++ dont support them yet + if (conf->configurationType() == ConfigurationType::Enabled) { + setValue(conf->level(), getBool(conf->value()), &m_enabledMap); + } else if (conf->configurationType() == ConfigurationType::ToFile) { + setValue(conf->level(), getBool(conf->value()), &m_toFileMap); + } else if (conf->configurationType() == ConfigurationType::ToStandardOutput) { + setValue(conf->level(), getBool(conf->value()), &m_toStandardOutputMap); + } else if (conf->configurationType() == ConfigurationType::Filename) { + // We do not yet configure filename but we will configure in another + // loop. This is because if file cannot be created, we will force ToFile + // to be false. Because configuring logger is not necessarily performance + // sensative operation, we can live with another loop; (by the way this loop + // is not very heavy either) + } else if (conf->configurationType() == ConfigurationType::Format) { + setValue(conf->level(), base::LogFormat(conf->level(), + base::type::string_t(conf->value().begin(), conf->value().end())), &m_logFormatMap); + } else if (conf->configurationType() == ConfigurationType::MillisecondsWidth) { + setValue(Level::Global, + base::MillisecondsWidth(static_cast(getULong(conf->value()))), &m_millisecondsWidthMap); + } else if (conf->configurationType() == ConfigurationType::PerformanceTracking) { + setValue(Level::Global, getBool(conf->value()), &m_performanceTrackingMap); + } else if (conf->configurationType() == ConfigurationType::MaxLogFileSize) { + setValue(conf->level(), static_cast(getULong(conf->value())), &m_maxLogFileSizeMap); +#if !defined(ELPP_NO_DEFAULT_LOG_FILE) + withFileSizeLimit.push_back(conf); +#endif // !defined(ELPP_NO_DEFAULT_LOG_FILE) + } else if (conf->configurationType() == ConfigurationType::LogFlushThreshold) { + setValue(conf->level(), static_cast(getULong(conf->value())), &m_logFlushThresholdMap); + } + } + // As mentioned early, we will now set filename configuration in separate loop to deal with non-existent files + for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) { + Configuration* conf = *it; + if (conf->configurationType() == ConfigurationType::Filename) { + insertFile(conf->level(), conf->value()); + } + } + for (std::vector::iterator conf = withFileSizeLimit.begin(); + conf != withFileSizeLimit.end(); ++conf) { + // This is not unsafe as mutex is locked in currect scope + unsafeValidateFileRolling((*conf)->level(), base::defaultPreRollOutCallback); + } + } + + unsigned long getULong(std::string confVal) { + bool valid = true; + base::utils::Str::trim(confVal); + valid = !confVal.empty() && std::find_if(confVal.begin(), confVal.end(), + [](char c) { return !base::utils::Str::isDigit(c); }) == confVal.end(); + if (!valid) { + valid = false; + ELPP_ASSERT(valid, "Configuration value not a valid integer [" << confVal << "]"); + return 0; + } + return atol(confVal.c_str()); + } + + std::string resolveFilename(const std::string& filename) { + std::string resultingFilename = filename; + std::size_t dateIndex = std::string::npos; + std::string dateTimeFormatSpecifierStr = std::string(base::consts::kDateTimeFormatSpecifierForFilename); + if ((dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str())) != std::string::npos) { + while (dateIndex > 0 && resultingFilename[dateIndex - 1] == base::consts::kFormatSpecifierChar) { + dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str(), dateIndex + 1); + } + if (dateIndex != std::string::npos) { + const char* ptr = resultingFilename.c_str() + dateIndex; + // Goto end of specifier + ptr += dateTimeFormatSpecifierStr.size(); + std::string fmt; + if ((resultingFilename.size() > dateIndex) && (ptr[0] == '{')) { + // User has provided format for date/time + ++ptr; + int count = 1; // Start by 1 in order to remove starting brace + std::stringstream ss; + for (; *ptr; ++ptr, ++count) { + if (*ptr == '}') { + ++count; // In order to remove ending brace + break; + } + ss << *ptr; + } + resultingFilename.erase(dateIndex + dateTimeFormatSpecifierStr.size(), count); + fmt = ss.str(); + } else { + fmt = std::string(base::consts::kDefaultDateTimeFormatInFilename); + } + base::MillisecondsWidth msWidth(3); + std::string now = base::utils::DateTime::getDateTime(fmt.c_str(), &msWidth); + base::utils::Str::replaceAll(now, '/', '-'); // Replace path element since we are dealing with filename + base::utils::Str::replaceAll(resultingFilename, dateTimeFormatSpecifierStr, now); + } + } + return resultingFilename; + } + + void insertFile(Level level, const std::string& fullFilename) { + std::string resolvedFilename = resolveFilename(fullFilename); + if (resolvedFilename.empty()) { + std::cerr << "Could not load empty file for logging, please re-check your configurations for level [" + << LevelHelper::convertToString(level) << "]"; + } + std::string filePath = base::utils::File::extractPathFromFilename(resolvedFilename, base::consts::kFilePathSeperator); + if (filePath.size() < resolvedFilename.size()) { + base::utils::File::createPath(filePath); + } + auto create = [&](Level level) { + base::LogStreamsReferenceMap::iterator filestreamIter = m_logStreamsReference->find(resolvedFilename); + base::type::fstream_t* fs = nullptr; + if (filestreamIter == m_logStreamsReference->end()) { + // We need a completely new stream, nothing to share with + fs = base::utils::File::newFileStream(resolvedFilename); + m_filenameMap.insert(std::make_pair(level, resolvedFilename)); + m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(fs))); + m_logStreamsReference->insert(std::make_pair(resolvedFilename, base::FileStreamPtr(m_fileStreamMap.at(level)))); + } else { + // Woops! we have an existing one, share it! + m_filenameMap.insert(std::make_pair(level, filestreamIter->first)); + m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(filestreamIter->second))); + fs = filestreamIter->second.get(); + } + if (fs == nullptr) { + // We display bad file error from newFileStream() + ELPP_INTERNAL_ERROR("Setting [TO_FILE] of [" + << LevelHelper::convertToString(level) << "] to FALSE", false); + setValue(level, false, &m_toFileMap); + } + }; + // If we dont have file conf for any level, create it for Level::Global first + // otherwise create for specified level + create(m_filenameMap.empty() && m_fileStreamMap.empty() ? Level::Global : level); + } + + bool unsafeValidateFileRolling(Level level, const PreRollOutCallback& PreRollOutCallback) { + base::type::fstream_t* fs = unsafeGetConfigByRef(level, &m_fileStreamMap, "fileStream").get(); + if (fs == nullptr) { + return true; + } + std::size_t maxLogFileSize = unsafeGetConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize"); + std::size_t currFileSize = base::utils::File::getSizeOfFile(fs); + if (maxLogFileSize != 0 && currFileSize >= maxLogFileSize) { + std::string fname = unsafeGetConfigByRef(level, &m_filenameMap, "filename"); + ELPP_INTERNAL_INFO(1, "Truncating log file [" << fname << "] as a result of configurations for level [" + << LevelHelper::convertToString(level) << "]"); + fs->close(); + PreRollOutCallback(fname.c_str(), currFileSize); + fs->open(fname, std::fstream::out | std::fstream::trunc); + return true; + } + return false; + } + + bool validateFileRolling(Level level, const PreRollOutCallback& PreRollOutCallback) { + base::threading::ScopedLock scopedLock(lock()); + return unsafeValidateFileRolling(level, PreRollOutCallback); + } +}; +/// @brief Class that keeps record of current line hit for occasional logging +class HitCounter { +public: + HitCounter(void) : + m_filename(""), + m_lineNumber(0), + m_hitCounts(0) { + } + + HitCounter(const char* filename, unsigned long int lineNumber) : + m_filename(filename), + m_lineNumber(lineNumber), + m_hitCounts(0) { + } + + HitCounter(const HitCounter& hitCounter) : + m_filename(hitCounter.m_filename), + m_lineNumber(hitCounter.m_lineNumber), + m_hitCounts(hitCounter.m_hitCounts) { + } + + HitCounter& operator=(const HitCounter& hitCounter) { + m_filename = hitCounter.m_filename; + m_lineNumber = hitCounter.m_lineNumber; + m_hitCounts = hitCounter.m_hitCounts; + return *this; + } + + virtual ~HitCounter(void) { + } + + /// @brief Resets location of current hit counter + inline void resetLocation(const char* filename, unsigned long int lineNumber) { + m_filename = filename; + m_lineNumber = lineNumber; + } + + /// @brief Validates hit counts and resets it if necessary + inline void validateHitCounts(std::size_t n) { + if (m_hitCounts >= base::consts::kMaxLogPerCounter) { + m_hitCounts = (n >= 1 ? base::consts::kMaxLogPerCounter % n : 0); + } + ++m_hitCounts; + } + + inline const char* filename(void) const { + return m_filename; + } + + inline unsigned long int lineNumber(void) const { + return m_lineNumber; + } + + inline std::size_t hitCounts(void) const { + return m_hitCounts; + } + + inline void increment(void) { + ++m_hitCounts; + } + + class Predicate { + public: + Predicate(const char* filename, unsigned long int lineNumber) + : m_filename(filename), + m_lineNumber(lineNumber) { + } + inline bool operator()(const HitCounter* counter) { + return ((counter != nullptr) && + (strcmp(counter->m_filename, m_filename) == 0) && + (counter->m_lineNumber == m_lineNumber)); + } + + private: + const char* m_filename; + unsigned long int m_lineNumber; + }; + +private: + const char* m_filename; + unsigned long int m_lineNumber; + std::size_t m_hitCounts; +}; +/// @brief Repository for hit counters used across the application +class RegisteredHitCounters : public base::utils::RegistryWithPred { +public: + /// @brief Validates counter for every N, i.e, registers new if does not exist otherwise updates original one + /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned + bool validateEveryN(const char* filename, unsigned long int lineNumber, std::size_t n) { + base::threading::ScopedLock scopedLock(lock()); + base::HitCounter* counter = get(filename, lineNumber); + if (counter == nullptr) { + registerNew(counter = new base::HitCounter(filename, lineNumber)); + } + counter->validateHitCounts(n); + bool result = (n >= 1 && counter->hitCounts() != 0 && counter->hitCounts() % n == 0); + return result; + } + + /// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one + /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned + bool validateAfterN(const char* filename, unsigned long int lineNumber, std::size_t n) { + base::threading::ScopedLock scopedLock(lock()); + base::HitCounter* counter = get(filename, lineNumber); + if (counter == nullptr) { + registerNew(counter = new base::HitCounter(filename, lineNumber)); + } + // Do not use validateHitCounts here since we do not want to reset counter here + // Note the >= instead of > because we are incrementing + // after this check + if (counter->hitCounts() >= n) + return true; + counter->increment(); + return false; + } + + /// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one + /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned + bool validateNTimes(const char* filename, unsigned long int lineNumber, std::size_t n) { + base::threading::ScopedLock scopedLock(lock()); + base::HitCounter* counter = get(filename, lineNumber); + if (counter == nullptr) { + registerNew(counter = new base::HitCounter(filename, lineNumber)); + } + counter->increment(); + // Do not use validateHitCounts here since we do not want to reset counter here + if (counter->hitCounts() <= n) + return true; + return false; + } + + /// @brief Gets hit counter registered at specified position + inline const base::HitCounter* getCounter(const char* filename, unsigned long int lineNumber) { + base::threading::ScopedLock scopedLock(lock()); + return get(filename, lineNumber); + } +}; +/// @brief Action to be taken for dispatching +enum class DispatchAction : base::type::EnumType { + None = 1, NormalLog = 2, SysLog = 4 +}; +} // namespace base +template +class Callback : protected base::threading::ThreadSafe { +public: + Callback(void) : m_enabled(true) {} + inline bool enabled(void) const { return m_enabled; } + inline void setEnabled(bool enabled) { + base::threading::ScopedLock scopedLock(lock()); + m_enabled = enabled; + } +protected: + virtual void handle(const T* handlePtr) = 0; +private: + bool m_enabled; +}; +class LogDispatchData { +public: + LogDispatchData() : m_logMessage(nullptr), m_dispatchAction(base::DispatchAction::None) {} + inline const LogMessage* logMessage(void) const { return m_logMessage; } + inline base::DispatchAction dispatchAction(void) const { return m_dispatchAction; } +private: + LogMessage* m_logMessage; + base::DispatchAction m_dispatchAction; + friend class base::LogDispatcher; + + inline void setLogMessage(LogMessage* logMessage) { m_logMessage = logMessage; } + inline void setDispatchAction(base::DispatchAction dispatchAction) { m_dispatchAction = dispatchAction; } +}; +class LogDispatchCallback : public Callback { +private: + friend class base::LogDispatcher; +}; +class PerformanceTrackingCallback : public Callback { +private: + friend class base::PerformanceTracker; +}; +class LogBuilder : base::NoCopy { +public: + virtual ~LogBuilder(void) { ELPP_INTERNAL_INFO(3, "Destroying log builder...")} + virtual base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const = 0; + void convertToColoredOutput(base::type::string_t* logLine, Level level) { + if (!base::utils::s_termSupportsColor) return; + const base::type::char_t* resetColor = ELPP_LITERAL("\x1b[0m"); + if (level == Level::Error || level == Level::Fatal) + *logLine = ELPP_LITERAL("\x1b[31m") + *logLine + resetColor; + else if (level == Level::Warning) + *logLine = ELPP_LITERAL("\x1b[33m") + *logLine + resetColor; + } +private: + friend class el::base::DefaultLogDispatchCallback; +}; +typedef std::shared_ptr LogBuilderPtr; +/// @brief Represents a logger holding ID and configurations we need to write logs +/// +/// @detail This class does not write logs itself instead its used by writer to read configuations from. +class Logger : public base::threading::ThreadSafe, public Loggable { +public: + Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference) : + m_id(id), + m_typedConfigurations(nullptr), + m_parentApplicationName(std::string()), + m_isConfigured(false), + m_logStreamsReference(logStreamsReference) { + initUnflushedCount(); + } + + Logger(const std::string& id, const Configurations& configurations, base::LogStreamsReferenceMap* logStreamsReference) : + m_id(id), + m_typedConfigurations(nullptr), + m_parentApplicationName(std::string()), + m_isConfigured(false), + m_logStreamsReference(logStreamsReference) { + initUnflushedCount(); + configure(configurations); + } + + Logger(const Logger& logger) { + base::utils::safeDelete(m_typedConfigurations); + m_id = logger.m_id; + m_typedConfigurations = logger.m_typedConfigurations; + m_parentApplicationName = logger.m_parentApplicationName; + m_isConfigured = logger.m_isConfigured; + m_configurations = logger.m_configurations; + m_unflushedCount = logger.m_unflushedCount; + m_logStreamsReference = logger.m_logStreamsReference; + } + + Logger& operator=(const Logger& logger) { + base::utils::safeDelete(m_typedConfigurations); + m_id = logger.m_id; + m_typedConfigurations = logger.m_typedConfigurations; + m_parentApplicationName = logger.m_parentApplicationName; + m_isConfigured = logger.m_isConfigured; + m_configurations = logger.m_configurations; + m_unflushedCount = logger.m_unflushedCount; + m_logStreamsReference = logger.m_logStreamsReference; + return *this; + } + + virtual ~Logger(void) { + base::utils::safeDelete(m_typedConfigurations); + } + + virtual inline void log(el::base::type::ostream_t& os) const { + os << m_id.c_str(); + } + + /// @brief Configures the logger using specified configurations. + void configure(const Configurations& configurations) { + m_isConfigured = false; // we set it to false in case if we fail + initUnflushedCount(); + if (m_typedConfigurations != nullptr) { + Configurations* c = const_cast(m_typedConfigurations->configurations()); + if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) { + // This check is definitely needed for cases like ELPP_NO_DEFAULT_LOG_FILE + flush(); + } + } + base::threading::ScopedLock scopedLock(lock()); + if (m_configurations != configurations) { + m_configurations.setFromBase(const_cast(&configurations)); + } + base::utils::safeDelete(m_typedConfigurations); + m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference); + resolveLoggerFormatSpec(); + m_isConfigured = true; + } + + /// @brief Reconfigures logger using existing configurations + inline void reconfigure(void) { + ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]"); + configure(m_configurations); + } + + inline const std::string& id(void) const { + return m_id; + } + + inline const std::string& parentApplicationName(void) const { + return m_parentApplicationName; + } + + inline void setParentApplicationName(const std::string& parentApplicationName) { + m_parentApplicationName = parentApplicationName; + } + + inline Configurations* configurations(void) { + return &m_configurations; + } + + inline base::TypedConfigurations* typedConfigurations(void) { + return m_typedConfigurations; + } + + static inline bool isValidId(const std::string& id) { + for (std::string::const_iterator it = id.begin(); it != id.end(); ++it) { + if (!base::utils::Str::contains(base::consts::kValidLoggerIdSymbols, *it)) { + return false; + } + } + return true; + } + /// @brief Flushes logger to sync all log files for all levels + inline void flush(void) { + ELPP_INTERNAL_INFO(3, "Flushing logger [" << m_id << "] all levels"); + base::threading::ScopedLock scopedLock(lock()); + base::type::EnumType lIndex = LevelHelper::kMinValid; + LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { + flush(LevelHelper::castFromInt(lIndex), nullptr); + return false; + }); + } + + inline void flush(Level level, base::type::fstream_t* fs) { + if (fs == nullptr && m_typedConfigurations->toFile(level)) { + fs = m_typedConfigurations->fileStream(level); + } + if (fs != nullptr) { + fs->flush(); + m_unflushedCount.find(level)->second = 0; + } + } + + inline bool isFlushNeeded(Level level) { + return ++m_unflushedCount.find(level)->second >= m_typedConfigurations->logFlushThreshold(level); + } + + inline LogBuilder* logBuilder(void) const { + return m_logBuilder.get(); + } + + inline void setLogBuilder(const LogBuilderPtr& logBuilder) { + m_logBuilder = logBuilder; + } + + inline bool enabled(Level level) const { + return m_typedConfigurations->enabled(level); + } + +#if ELPP_VARIADIC_TEMPLATES_SUPPORTED +# define LOGGER_LEVEL_WRITERS_SIGNATURES(FUNCTION_NAME)\ + template \ + inline void FUNCTION_NAME(const char*, const T&, const Args&...);\ + template \ + inline void FUNCTION_NAME(const T&); + + template + inline void verbose(int, const char*, const T&, const Args&...); + + template + inline void verbose(int, const T&); + + LOGGER_LEVEL_WRITERS_SIGNATURES(info) + LOGGER_LEVEL_WRITERS_SIGNATURES(debug) + LOGGER_LEVEL_WRITERS_SIGNATURES(warn) + LOGGER_LEVEL_WRITERS_SIGNATURES(error) + LOGGER_LEVEL_WRITERS_SIGNATURES(fatal) + LOGGER_LEVEL_WRITERS_SIGNATURES(trace) +# undef LOGGER_LEVEL_WRITERS_SIGNATURES +#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED +private: + std::string m_id; + base::TypedConfigurations* m_typedConfigurations; + base::type::stringstream_t m_stream; + std::string m_parentApplicationName; + bool m_isConfigured; + Configurations m_configurations; + std::map m_unflushedCount; + base::LogStreamsReferenceMap* m_logStreamsReference; + LogBuilderPtr m_logBuilder; + + friend class el::LogMessage; + friend class el::Loggers; + friend class el::Helpers; + friend class el::base::RegisteredLoggers; + friend class el::base::DefaultLogDispatchCallback; + friend class el::base::MessageBuilder; + friend class el::base::Writer; + friend class el::base::PErrorWriter; + friend class el::base::Storage; + friend class el::base::PerformanceTracker; + friend class el::base::LogDispatcher; + + Logger(void); + +#if ELPP_VARIADIC_TEMPLATES_SUPPORTED + template + void log_(Level, int, const char*, const T&, const Args&...); + + template + inline void log_(Level, int, const T&); + + template + void log(Level, const char*, const T&, const Args&...); + + template + inline void log(Level, const T&); +#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED + + void initUnflushedCount(void) { + m_unflushedCount.clear(); + base::type::EnumType lIndex = LevelHelper::kMinValid; + LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { + m_unflushedCount.insert(std::make_pair(LevelHelper::castFromInt(lIndex), 0)); + return false; + }); + } + + inline base::type::stringstream_t& stream(void) { + return m_stream; + } + + void resolveLoggerFormatSpec(void) const { + base::type::EnumType lIndex = LevelHelper::kMinValid; + LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { + base::LogFormat* logFormat = + const_cast(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex))); + base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id); + return false; + }); + } +}; +namespace base { +/// @brief Loggers repository +class RegisteredLoggers : public base::utils::Registry { +public: + explicit RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder) : + m_defaultLogBuilder(defaultLogBuilder) { + m_defaultConfigurations.setToDefault(); + } + + virtual ~RegisteredLoggers(void) { + flushAll(); + } + + inline void setDefaultConfigurations(const Configurations& configurations) { + base::threading::ScopedLock scopedLock(lock()); + m_defaultConfigurations.setFromBase(const_cast(&configurations)); + } + + inline Configurations* defaultConfigurations(void) { + return &m_defaultConfigurations; + } + + Logger* get(const std::string& id, bool forceCreation = true) { + base::threading::ScopedLock scopedLock(lock()); + Logger* logger_ = base::utils::Registry::get(id); + if (logger_ == nullptr && forceCreation) { + bool validId = Logger::isValidId(id); + if (!validId) { + ELPP_ASSERT(validId, "Invalid logger ID [" << id << "]. Not registering this logger."); + return nullptr; + } + logger_ = new Logger(id, m_defaultConfigurations, &m_logStreamsReference); + logger_->m_logBuilder = m_defaultLogBuilder; + registerNew(id, logger_); + } + return logger_; + } + + bool remove(const std::string& id) { + if (id == "default") { + return false; + } + Logger* logger = base::utils::Registry::get(id); + if (logger != nullptr) { + unregister(logger); + } + return true; + } + + inline bool has(const std::string& id) { + return get(id, false) != nullptr; + } + + inline void unregister(Logger*& logger) { + base::threading::ScopedLock scopedLock(lock()); + base::utils::Registry::unregister(logger->id()); + } + + inline base::LogStreamsReferenceMap* logStreamsReference(void) { + return &m_logStreamsReference; + } + + inline void flushAll(void) { + ELPP_INTERNAL_INFO(1, "Flushing all log files"); + base::threading::ScopedLock scopedLock(lock()); + for (base::LogStreamsReferenceMap::iterator it = m_logStreamsReference.begin(); + it != m_logStreamsReference.end(); ++it) { + if (it->second.get() == nullptr) continue; + it->second->flush(); + } + } + +private: + LogBuilderPtr m_defaultLogBuilder; + Configurations m_defaultConfigurations; + base::LogStreamsReferenceMap m_logStreamsReference; + friend class el::base::Storage; +}; +/// @brief Represents registries for verbose logging +class VRegistry : base::NoCopy, public base::threading::ThreadSafe { +public: + explicit VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags) : m_level(level), m_pFlags(pFlags) { + } + + /// @brief Sets verbose level. Accepted range is 0-9 + inline void setLevel(base::type::VerboseLevel level) { + base::threading::ScopedLock scopedLock(lock()); + if (level < 0) + m_level = 0; + else if (level > 9) + m_level = base::consts::kMaxVerboseLevel; + else + m_level = level; + } + + inline base::type::VerboseLevel level(void) const { + return m_level; + } + + inline void clearModules(void) { + base::threading::ScopedLock scopedLock(lock()); + m_modules.clear(); + } + + void setModules(const char* modules) { + base::threading::ScopedLock scopedLock(lock()); + auto addSuffix = [](std::stringstream& ss, const char* sfx, const char* prev) { + if (prev != nullptr && base::utils::Str::endsWith(ss.str(), std::string(prev))) { + std::string chr(ss.str().substr(0, ss.str().size() - strlen(prev))); + ss.str(std::string("")); + ss << chr; + } + if (base::utils::Str::endsWith(ss.str(), std::string(sfx))) { + std::string chr(ss.str().substr(0, ss.str().size() - strlen(sfx))); + ss.str(std::string("")); + ss << chr; + } + ss << sfx; + }; + auto insert = [&](std::stringstream& ss, base::type::VerboseLevel level) { + if (!base::utils::hasFlag(LoggingFlag::DisableVModulesExtensions, *m_pFlags)) { + addSuffix(ss, ".h", nullptr); + m_modules.insert(std::make_pair(ss.str(), level)); + addSuffix(ss, ".c", ".h"); + m_modules.insert(std::make_pair(ss.str(), level)); + addSuffix(ss, ".cpp", ".c"); + m_modules.insert(std::make_pair(ss.str(), level)); + addSuffix(ss, ".cc", ".cpp"); + m_modules.insert(std::make_pair(ss.str(), level)); + addSuffix(ss, ".cxx", ".cc"); + m_modules.insert(std::make_pair(ss.str(), level)); + addSuffix(ss, ".-inl.h", ".cxx"); + m_modules.insert(std::make_pair(ss.str(), level)); + addSuffix(ss, ".hxx", ".-inl.h"); + m_modules.insert(std::make_pair(ss.str(), level)); + addSuffix(ss, ".hpp", ".hxx"); + m_modules.insert(std::make_pair(ss.str(), level)); + addSuffix(ss, ".hh", ".hpp"); + } + m_modules.insert(std::make_pair(ss.str(), level)); + }; + bool isMod = true; + bool isLevel = false; + std::stringstream ss; + int level = -1; + for (; *modules; ++modules) { + switch (*modules) { + case '=': + isLevel = true; + isMod = false; + break; + case ',': + isLevel = false; + isMod = true; + if (!ss.str().empty() && level != -1) { + insert(ss, level); + ss.str(std::string("")); + level = -1; + } + break; + default: + if (isMod) { + ss << *modules; + } else if (isLevel) { + if (isdigit(*modules)) { + level = static_cast(*modules) - 48; + } + } + break; + } + } + if (!ss.str().empty() && level != -1) { + insert(ss, level); + } + } + + bool allowed(base::type::VerboseLevel vlevel, const char* file) { + base::threading::ScopedLock scopedLock(lock()); + if (m_modules.empty() || file == nullptr) { + return vlevel <= m_level; + } else { + std::map::iterator it = m_modules.begin(); + for (; it != m_modules.end(); ++it) { + if (base::utils::Str::wildCardMatch(file, it->first.c_str())) { + return vlevel <= it->second; + } + } + if (base::utils::hasFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified, *m_pFlags)) { + return true; + } + return false; + } + } + + inline const std::map& modules(void) const { + return m_modules; + } + + void setFromArgs(const base::utils::CommandLineArgs* commandLineArgs) { + if (commandLineArgs->hasParam("-v") || commandLineArgs->hasParam("--verbose") || + commandLineArgs->hasParam("-V") || commandLineArgs->hasParam("--VERBOSE")) { + setLevel(base::consts::kMaxVerboseLevel); + } else if (commandLineArgs->hasParamWithValue("--v")) { + setLevel(atoi(commandLineArgs->getParamValue("--v"))); + } else if (commandLineArgs->hasParamWithValue("--V")) { + setLevel(atoi(commandLineArgs->getParamValue("--V"))); + } else if ((commandLineArgs->hasParamWithValue("-vmodule")) && vModulesEnabled()) { + setModules(commandLineArgs->getParamValue("-vmodule")); + } else if (commandLineArgs->hasParamWithValue("-VMODULE") && vModulesEnabled()) { + setModules(commandLineArgs->getParamValue("-VMODULE")); + } + } + + /// @brief Whether or not vModules enabled + inline bool vModulesEnabled(void) { + return !base::utils::hasFlag(LoggingFlag::DisableVModules, *m_pFlags); + } + +private: + base::type::VerboseLevel m_level; + base::type::EnumType* m_pFlags; + std::map m_modules; +}; +} // namespace base +class LogMessage { +public: + LogMessage(Level level, const std::string& file, unsigned long int line, const std::string& func, + base::type::VerboseLevel verboseLevel, Logger* logger) : + m_level(level), m_file(file), m_line(line), m_func(func), + m_verboseLevel(verboseLevel), m_logger(logger), m_message(std::move(logger->stream().str())) { + } + inline Level level(void) const { return m_level; } + inline const std::string& file(void) const { return m_file; } + inline unsigned long int line(void) const { return m_line; } // NOLINT + inline const std::string& func(void) const { return m_func; } + inline base::type::VerboseLevel verboseLevel(void) const { return m_verboseLevel; } + inline Logger* logger(void) const { return m_logger; } + inline const base::type::string_t& message(void) const { return m_message; } +private: + Level m_level; + std::string m_file; + unsigned long int m_line; + std::string m_func; + base::type::VerboseLevel m_verboseLevel; + Logger* m_logger; + base::type::string_t m_message; +}; +namespace base { +#if ELPP_ASYNC_LOGGING +class AsyncLogItem { +public: + explicit AsyncLogItem(const LogMessage& logMessage, const LogDispatchData& data, const base::type::string_t& logLine) + : m_logMessage(logMessage), m_dispatchData(data), m_logLine(logLine) {} + virtual ~AsyncLogItem() {} + inline LogMessage* logMessage(void) { return &m_logMessage; } + inline LogDispatchData* data(void) { return &m_dispatchData; } + inline base::type::string_t logLine(void) { return m_logLine; } +private: + LogMessage m_logMessage; + LogDispatchData m_dispatchData; + base::type::string_t m_logLine; +}; +class AsyncLogQueue : public base::threading::ThreadSafe { +public: + virtual ~AsyncLogQueue() { + ELPP_INTERNAL_INFO(6, "~AsyncLogQueue"); + } + + inline AsyncLogItem next(void) { + base::threading::ScopedLock scopedLock(lock()); + AsyncLogItem result = m_queue.front(); + m_queue.pop(); + return result; + } + + inline void push(const AsyncLogItem& item) { + base::threading::ScopedLock scopedLock(lock()); + m_queue.push(item); + } + inline void pop(void) { + base::threading::ScopedLock scopedLock(lock()); + m_queue.pop(); + } + inline AsyncLogItem front(void) { + base::threading::ScopedLock scopedLock(lock()); + return m_queue.front(); + } + inline bool empty(void) { + base::threading::ScopedLock scopedLock(lock()); + return m_queue.empty(); + } +private: + std::queue m_queue; +}; +class IWorker { +public: + virtual ~IWorker() {} + virtual void start() = 0; +}; +#endif // ELPP_ASYNC_LOGGING +/// @brief Easylogging++ management storage +class Storage : base::NoCopy, public base::threading::ThreadSafe { +public: +#if ELPP_ASYNC_LOGGING + Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker) : +#else + explicit Storage(const LogBuilderPtr& defaultLogBuilder) : +#endif // ELPP_ASYNC_LOGGING + m_registeredHitCounters(new base::RegisteredHitCounters()), + m_registeredLoggers(new base::RegisteredLoggers(defaultLogBuilder)), + m_flags(0x0), + m_vRegistry(new base::VRegistry(0, &m_flags)), +#if ELPP_ASYNC_LOGGING + m_asyncLogQueue(new base::AsyncLogQueue()), + m_asyncDispatchWorker(asyncDispatchWorker), +#endif // ELPP_ASYNC_LOGGING + m_preRollOutCallback(base::defaultPreRollOutCallback) { + // Register default logger + m_registeredLoggers->get(std::string(base::consts::kDefaultLoggerId)); + // Register performance logger and reconfigure format + Logger* performanceLogger = m_registeredLoggers->get(std::string(base::consts::kPerformanceLoggerId)); + performanceLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%datetime %level %msg")); + performanceLogger->reconfigure(); +#if defined(ELPP_SYSLOG) + // Register syslog logger and reconfigure format + Logger* sysLogLogger = m_registeredLoggers->get(std::string(base::consts::kSysLogLoggerId)); + sysLogLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%level: %msg")); + sysLogLogger->reconfigure(); +#else + ELPP_UNUSED(base::consts::kSysLogLoggerId); +#endif // defined(ELPP_SYSLOG) + addFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified); +#if ELPP_ASYNC_LOGGING + installLogDispatchCallback(std::string("AsyncLogDispatchCallback")); +#else + installLogDispatchCallback(std::string("DefaultLogDispatchCallback")); +#endif // ELPP_ASYNC_LOGGING + installPerformanceTrackingCallback(std::string("DefaultPerformanceTrackingCallback")); + ELPP_INTERNAL_INFO(1, "Easylogging++ has been initialized"); +#if ELPP_ASYNC_LOGGING + m_asyncDispatchWorker->start(); +#endif // ELPP_ASYNC_LOGGING + } + + virtual ~Storage(void) { + ELPP_INTERNAL_INFO(4, "Destroying storage"); +#if ELPP_ASYNC_LOGGING + ELPP_INTERNAL_INFO(5, "Replacing log dispatch callback to synchronous"); + uninstallLogDispatchCallback(std::string("AsyncLogDispatchCallback")); + installLogDispatchCallback(std::string("DefaultLogDispatchCallback")); + ELPP_INTERNAL_INFO(5, "Destroying asyncDispatchWorker"); + base::utils::safeDelete(m_asyncDispatchWorker); + ELPP_INTERNAL_INFO(5, "Destroying asyncLogQueue"); + base::utils::safeDelete(m_asyncLogQueue); +#endif // ELPP_ASYNC_LOGGING + ELPP_INTERNAL_INFO(5, "Destroying registeredHitCounters"); + base::utils::safeDelete(m_registeredHitCounters); + ELPP_INTERNAL_INFO(5, "Destroying registeredLoggers"); + base::utils::safeDelete(m_registeredLoggers); + ELPP_INTERNAL_INFO(5, "Destroying vRegistry"); + base::utils::safeDelete(m_vRegistry); + } + + inline bool validateEveryNCounter(const char* filename, unsigned long int lineNumber, std::size_t occasion) { + return hitCounters()->validateEveryN(filename, lineNumber, occasion); + } + + inline bool validateAfterNCounter(const char* filename, unsigned long int lineNumber, std::size_t n) { // NOLINT + return hitCounters()->validateAfterN(filename, lineNumber, n); + } + + inline bool validateNTimesCounter(const char* filename, unsigned long int lineNumber, std::size_t n) { // NOLINT + return hitCounters()->validateNTimes(filename, lineNumber, n); + } + + inline base::RegisteredHitCounters* hitCounters(void) const { + return m_registeredHitCounters; + } + + inline base::RegisteredLoggers* registeredLoggers(void) const { + return m_registeredLoggers; + } + + inline base::VRegistry* vRegistry(void) const { + return m_vRegistry; + } + +#if ELPP_ASYNC_LOGGING + inline base::AsyncLogQueue* asyncLogQueue(void) const { + return m_asyncLogQueue; + } +#endif // ELPP_ASYNC_LOGGING + + inline const base::utils::CommandLineArgs* commandLineArgs(void) const { + return &m_commandLineArgs; + } + + inline void addFlag(LoggingFlag flag) { + base::utils::addFlag(flag, &m_flags); + } + + inline void removeFlag(LoggingFlag flag) { + base::utils::removeFlag(flag, &m_flags); + } + + inline bool hasFlag(LoggingFlag flag) const { + return base::utils::hasFlag(flag, m_flags); + } + + inline base::type::EnumType flags(void) const { + return m_flags; + } + + inline void setFlags(base::type::EnumType flags) { + m_flags = flags; + } + + inline void setPreRollOutCallback(const PreRollOutCallback& callback) { + m_preRollOutCallback = callback; + } + + inline void unsetPreRollOutCallback(void) { + m_preRollOutCallback = base::defaultPreRollOutCallback; + } + + inline PreRollOutCallback& preRollOutCallback(void) { + return m_preRollOutCallback; + } + + inline bool hasCustomFormatSpecifier(const char* formatSpecifier) { + base::threading::ScopedLock scopedLock(lock()); + return std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(), + formatSpecifier) != m_customFormatSpecifiers.end(); + } + + inline void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) { + if (hasCustomFormatSpecifier(customFormatSpecifier.formatSpecifier())) { + return; + } + base::threading::ScopedLock scopedLock(lock()); + m_customFormatSpecifiers.push_back(customFormatSpecifier); + } + + inline bool uninstallCustomFormatSpecifier(const char* formatSpecifier) { + base::threading::ScopedLock scopedLock(lock()); + std::vector::iterator it = std::find(m_customFormatSpecifiers.begin(), + m_customFormatSpecifiers.end(), formatSpecifier); + if (it != m_customFormatSpecifiers.end() && strcmp(formatSpecifier, it->formatSpecifier()) == 0) { + m_customFormatSpecifiers.erase(it); + return true; + } + return false; + } + + const std::vector* customFormatSpecifiers(void) const { + return &m_customFormatSpecifiers; + } + + inline void setLoggingLevel(Level level) { + m_loggingLevel = level; + } + + template + inline bool installLogDispatchCallback(const std::string& id) { + return installCallback(id, &m_logDispatchCallbacks); + } + + template + inline void uninstallLogDispatchCallback(const std::string& id) { + uninstallCallback(id, &m_logDispatchCallbacks); + } + template + inline T* logDispatchCallback(const std::string& id) { + return callback(id, &m_logDispatchCallbacks); + } + + template + inline bool installPerformanceTrackingCallback(const std::string& id) { + return installCallback(id, &m_performanceTrackingCallbacks); + } + + template + inline void uninstallPerformanceTrackingCallback(const std::string& id) { + uninstallCallback(id, &m_performanceTrackingCallbacks); + } + + template + inline T* performanceTrackingCallback(const std::string& id) { + return callback(id, &m_performanceTrackingCallbacks); + } +private: + base::RegisteredHitCounters* m_registeredHitCounters; + base::RegisteredLoggers* m_registeredLoggers; + base::type::EnumType m_flags; + base::VRegistry* m_vRegistry; +#if ELPP_ASYNC_LOGGING + base::AsyncLogQueue* m_asyncLogQueue; + base::IWorker* m_asyncDispatchWorker; +#endif // ELPP_ASYNC_LOGGING + base::utils::CommandLineArgs m_commandLineArgs; + PreRollOutCallback m_preRollOutCallback; + std::map m_logDispatchCallbacks; + std::map m_performanceTrackingCallbacks; + std::vector m_customFormatSpecifiers; + Level m_loggingLevel; + + friend class el::Helpers; + friend class el::base::DefaultLogDispatchCallback; + friend class el::LogBuilder; + friend class el::base::MessageBuilder; + friend class el::base::Writer; + friend class el::base::PerformanceTracker; + friend class el::base::LogDispatcher; + + void setApplicationArguments(int argc, char** argv) { + m_commandLineArgs.setArgs(argc, argv); + m_vRegistry->setFromArgs(commandLineArgs()); + // default log file +#if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) + if (m_commandLineArgs.hasParamWithValue(base::consts::kDefaultLogFileParam)) { + Configurations c; + c.setGlobally(ConfigurationType::Filename, std::string(m_commandLineArgs.getParamValue(base::consts::kDefaultLogFileParam))); + registeredLoggers()->setDefaultConfigurations(c); + for (base::RegisteredLoggers::iterator it = registeredLoggers()->begin(); + it != registeredLoggers()->end(); ++it) { + it->second->configure(c); + } + } +#endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) +#if defined(ELPP_LOGGING_FLAGS_FROM_ARG) + if (m_commandLineArgs.hasParamWithValue(base::consts::kLoggingFlagsParam)) { + m_flags = atoi(m_commandLineArgs.getParamValue(base::consts::kLoggingFlagsParam)); + } +#endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG) + } + + inline void setApplicationArguments(int argc, const char** argv) { + setApplicationArguments(argc, const_cast(argv)); + } + + template + inline bool installCallback(const std::string& id, std::map* mapT) { + if (mapT->find(id) == mapT->end()) { + mapT->insert(std::make_pair(id, TPtr(new T()))); + return true; + } + return false; + } + + template + inline void uninstallCallback(const std::string& id, std::map* mapT) { + if (mapT->find(id) != mapT->end()) { + mapT->erase(id); + } + } + + template + inline T* callback(const std::string& id, std::map* mapT) { + typename std::map::iterator iter = mapT->find(id); + if (iter != mapT->end()) { + return static_cast(iter->second.get()); + } + return nullptr; + } +}; +extern ELPP_EXPORT base::type::StoragePointer elStorage; +#define ELPP el::base::elStorage +class DefaultLogDispatchCallback : public LogDispatchCallback { +protected: + void handle(const LogDispatchData* data) { + m_data = data; + dispatch(std::move(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(), + m_data->dispatchAction() == base::DispatchAction::NormalLog))); + } +private: + const LogDispatchData* m_data; + void dispatch(base::type::string_t&& logLine) { + if (m_data->dispatchAction() == base::DispatchAction::NormalLog) { + if (m_data->logMessage()->logger()->m_typedConfigurations->toFile(m_data->logMessage()->level())) { + base::type::fstream_t* fs = m_data->logMessage()->logger()->m_typedConfigurations->fileStream(m_data->logMessage()->level()); + if (fs != nullptr) { + fs->write(logLine.c_str(), logLine.size()); + if (fs->fail()) { + ELPP_INTERNAL_ERROR("Unable to write log to file [" + << m_data->logMessage()->logger()->m_typedConfigurations->filename(m_data->logMessage()->level()) << "].\n" + << "Few possible reasons (could be something else):\n" << " * Permission denied\n" + << " * Disk full\n" << " * Disk is not writable", true); + } else { + if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (m_data->logMessage()->logger()->isFlushNeeded(m_data->logMessage()->level()))) { + m_data->logMessage()->logger()->flush(m_data->logMessage()->level(), fs); + } + } + } else { + ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(m_data->logMessage()->level()) << "] " + << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " + << m_data->logMessage()->logger()->id() << "]", false); + } + } + if (m_data->logMessage()->logger()->m_typedConfigurations->toStandardOutput(m_data->logMessage()->level())) { + if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput)) + m_data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, m_data->logMessage()->level()); + ELPP_COUT << ELPP_COUT_LINE(logLine); + } + } +#if defined(ELPP_SYSLOG) + else if (m_data->dispatchAction() == base::DispatchAction::SysLog) { + // Determine syslog priority + int sysLogPriority = 0; + if (m_data->logMessage()->level() == Level::Fatal) + sysLogPriority = LOG_EMERG; + else if (m_data->logMessage()->level() == Level::Error) + sysLogPriority = LOG_ERR; + else if (m_data->logMessage()->level() == Level::Warning) + sysLogPriority = LOG_WARNING; + else if (m_data->logMessage()->level() == Level::Info) + sysLogPriority = LOG_INFO; + else if (m_data->logMessage()->level() == Level::Debug) + sysLogPriority = LOG_DEBUG; + else + sysLogPriority = LOG_NOTICE; +# if defined(ELPP_UNICODE) + char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str()); + syslog(sysLogPriority, "%s", line); + free(line); +# else + syslog(sysLogPriority, "%s", logLine.c_str()); +# endif + } +#endif // defined(ELPP_SYSLOG) + } +}; +#if ELPP_ASYNC_LOGGING +class AsyncLogDispatchCallback : public LogDispatchCallback { +protected: + void handle(const LogDispatchData* data) { + base::type::string_t logLine = data->logMessage()->logger()->logBuilder()->build(data->logMessage(), data->dispatchAction() == base::DispatchAction::NormalLog); + if (data->dispatchAction() == base::DispatchAction::NormalLog && data->logMessage()->logger()->typedConfigurations()->toStandardOutput(data->logMessage()->level())) { + if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput)) + data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, data->logMessage()->level()); + ELPP_COUT << ELPP_COUT_LINE(logLine); + } + // Save resources and only queue if we want to write to file otherwise just ignore handler + if (data->logMessage()->logger()->typedConfigurations()->toFile(data->logMessage()->level())) { + ELPP->asyncLogQueue()->push(AsyncLogItem(*(data->logMessage()), *data, logLine)); + } + } +}; +class AsyncDispatchWorker : public base::IWorker, public base::threading::ThreadSafe { +public: + AsyncDispatchWorker() { + setContinueRunning(false); + } + + virtual ~AsyncDispatchWorker() { + setContinueRunning(false); + ELPP_INTERNAL_INFO(6, "Stopping dispatch worker - Cleaning log queue"); + clean(); + ELPP_INTERNAL_INFO(6, "Log queue cleaned"); + } + + inline bool clean() { + std::mutex m; + std::unique_lock lk(m); + cv.wait(lk, []{ return !ELPP->asyncLogQueue()->empty(); }); + emptyQueue(); + lk.unlock(); + cv.notify_one(); + return ELPP->asyncLogQueue()->empty(); + } + + inline void emptyQueue() { + while (!ELPP->asyncLogQueue()->empty()) { + AsyncLogItem data = ELPP->asyncLogQueue()->next(); + handle(&data); + base::threading::msleep(100); + } + } + + virtual inline void start() { + base::threading::msleep(5000); // Wait extra few seconds + setContinueRunning(true); + std::thread t1(&AsyncDispatchWorker::runner, this); + t1.join(); + } + + void handle(AsyncLogItem* logItem) { + LogDispatchData* data = logItem->data(); + LogMessage* logMessage = logItem->logMessage(); + Logger* logger = logMessage->logger(); + base::TypedConfigurations* conf = logger->typedConfigurations(); + base::type::string_t logLine = logItem->logLine(); + if (data->dispatchAction() == base::DispatchAction::NormalLog) { + if (conf->toFile(logMessage->level())) { + base::type::fstream_t* fs = conf->fileStream(logMessage->level()); + if (fs != nullptr) { + fs->write(logLine.c_str(), logLine.size()); + if (fs->fail()) { + ELPP_INTERNAL_ERROR("Unable to write log to file [" + << conf->filename(logMessage->level()) << "].\n" + << "Few possible reasons (could be something else):\n" << " * Permission denied\n" + << " * Disk full\n" << " * Disk is not writable", true); + } else { + if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (logger->isFlushNeeded(logMessage->level()))) { + logger->flush(logMessage->level(), fs); + } + } + } else { + ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(logMessage->level()) << "] " + << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " << logger->id() << "]", false); + } + } + } +# if defined(ELPP_SYSLOG) + else if (data->dispatchAction() == base::DispatchAction::SysLog) { + // Determine syslog priority + int sysLogPriority = 0; + if (logMessage->level() == Level::Fatal) + sysLogPriority = LOG_EMERG; + else if (logMessage->level() == Level::Error) + sysLogPriority = LOG_ERR; + else if (logMessage->level() == Level::Warning) + sysLogPriority = LOG_WARNING; + else if (logMessage->level() == Level::Info) + sysLogPriority = LOG_INFO; + else if (logMessage->level() == Level::Debug) + sysLogPriority = LOG_DEBUG; + else + sysLogPriority = LOG_NOTICE; +# if defined(ELPP_UNICODE) + char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str()); + syslog(sysLogPriority, "%s", line); + free(line); +# else + syslog(sysLogPriority, "%s", logLine.c_str()); +# endif + } +# endif // defined(ELPP_SYSLOG) + } + + void run() { + while (continueRunning()) { + emptyQueue(); + base::threading::msleep(10); // 10ms + } + } + + static void* runner(void *context) { + static_cast(context)->run(); + return NULL; + } + + void setContinueRunning(bool value) { + base::threading::ScopedLock scopedLock(m_continueRunningMutex); + m_continueRunning = value; + } + bool continueRunning(void) { + return m_continueRunning; + } +private: + std::condition_variable cv; + bool m_continueRunning; + base::threading::Mutex m_continueRunningMutex; +}; +#endif // ELPP_ASYNC_LOGGING +} // namespace base +namespace base { +class DefaultLogBuilder : public LogBuilder { +public: + base::type::string_t build(const LogMessage* logMessage, bool appendNewLine) const { + base::TypedConfigurations* tc = logMessage->logger()->typedConfigurations(); + const base::LogFormat* logFormat = &tc->logFormat(logMessage->level()); + base::type::string_t logLine = logFormat->format(); + char buff[base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength] = ""; + const char* bufLim = buff + sizeof(buff); + if (logFormat->hasFlag(base::FormatFlags::AppName)) { + // App name + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kAppNameFormatSpecifier, + logMessage->logger()->parentApplicationName()); + } + if (logFormat->hasFlag(base::FormatFlags::ThreadId)) { + // Thread ID + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kThreadIdFormatSpecifier, + base::threading::getCurrentThreadId()); + } + if (logFormat->hasFlag(base::FormatFlags::DateTime)) { + // DateTime + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kDateTimeFormatSpecifier, + base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(), + &tc->millisecondsWidth(logMessage->level()))); + } + if (logFormat->hasFlag(base::FormatFlags::Function)) { + // Function + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFunctionFormatSpecifier, logMessage->func()); + } + if (logFormat->hasFlag(base::FormatFlags::File)) { + // File + char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength); + base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff); + buf = base::utils::Str::addToBuff(buff, buf, bufLim); + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileFormatSpecifier, std::string(buff)); + } + if (logFormat->hasFlag(base::FormatFlags::FileBase)) { + // FileBase + char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength); + base::utils::File::buildBaseFilename(logMessage->file(), buff); + buf = base::utils::Str::addToBuff(buff, buf, bufLim); + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileBaseFormatSpecifier, std::string(buff)); + } + if (logFormat->hasFlag(base::FormatFlags::Line)) { + // Line + char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceLineMaxLength); + buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), + base::consts::kSourceLineMaxLength, buf, bufLim, false); + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLineFormatSpecifier, std::string(buff)); + } + if (logFormat->hasFlag(base::FormatFlags::Location)) { + // Location + char* buf = base::utils::Str::clearBuff(buff, + base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength); + base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff); + buf = base::utils::Str::addToBuff(buff, buf, bufLim); + buf = base::utils::Str::addToBuff(":", buf, bufLim); + buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), + base::consts::kSourceLineMaxLength, buf, bufLim, false); + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLocationFormatSpecifier, std::string(buff)); + } + if (logMessage->level() == Level::Verbose && logFormat->hasFlag(base::FormatFlags::VerboseLevel)) { + // Verbose level + char* buf = base::utils::Str::clearBuff(buff, 1); + buf = base::utils::Str::convertAndAddToBuff(logMessage->verboseLevel(), 1, buf, bufLim, false); + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kVerboseLevelFormatSpecifier, std::string(buff)); + } + if (logFormat->hasFlag(base::FormatFlags::LogMessage)) { + // Log message + base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kMessageFormatSpecifier, logMessage->message()); + } +#if !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS) + for (std::vector::const_iterator it = ELPP->customFormatSpecifiers()->begin(); + it != ELPP->customFormatSpecifiers()->end(); ++it) { + std::string fs(it->formatSpecifier()); + base::type::string_t wcsFormatSpecifier(fs.begin(), fs.end()); + base::utils::Str::replaceFirstWithEscape(logLine, wcsFormatSpecifier, std::string(it->resolver()())); + } +#endif // !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS) + if (appendNewLine) logLine += ELPP_LITERAL("\n"); + return logLine; + } +}; +/// @brief Dispatches log messages +class LogDispatcher : base::NoCopy { +public: + LogDispatcher(bool proceed, LogMessage&& logMessage, base::DispatchAction dispatchAction) : + m_proceed(proceed), + m_logMessage(std::move(logMessage)), + m_dispatchAction(std::move(dispatchAction)) { + } + + void dispatch(void) { + if (m_proceed && m_dispatchAction == base::DispatchAction::None) { + m_proceed = false; + } + if (!m_proceed) { + return; + } + // We minimize the time of ELPP's lock - this lock is released after log is written + base::threading::ScopedLock scopedLock(ELPP->lock()); + base::TypedConfigurations* tc = m_logMessage.logger()->m_typedConfigurations; + if (ELPP->hasFlag(LoggingFlag::StrictLogFileSizeCheck)) { + tc->validateFileRolling(m_logMessage.level(), ELPP->preRollOutCallback()); + } + LogDispatchCallback* callback = nullptr; + LogDispatchData data; + for (const std::pair& h + : ELPP->m_logDispatchCallbacks) { + callback = h.second.get(); + if (callback != nullptr && callback->enabled()) { + data.setLogMessage(&m_logMessage); + data.setDispatchAction(m_dispatchAction); + callback->acquireLock(); + callback->handle(&data); + callback->releaseLock(); + } + } + } + +private: + bool m_proceed; + LogMessage m_logMessage; + base::DispatchAction m_dispatchAction; +}; +#if defined(ELPP_STL_LOGGING) +/// @brief Workarounds to write some STL logs +/// +/// @detail There is workaround needed to loop through some stl containers. In order to do that, we need iterable containers +/// of same type and provide iterator interface and pass it on to writeIterator(). +/// Remember, this is passed by value in constructor so that we dont change original containers. +/// This operation is as expensive as Big-O(std::min(class_.size(), base::consts::kMaxLogPerContainer)) +namespace workarounds { +/// @brief Abstract IterableContainer template that provides interface for iterable classes of type T +template +class IterableContainer { +public: + typedef typename Container::iterator iterator; + typedef typename Container::const_iterator const_iterator; + IterableContainer(void) {} + virtual ~IterableContainer(void) {} + iterator begin(void) { return getContainer().begin(); } + iterator end(void) { return getContainer().end(); } +private: + virtual Container& getContainer(void) = 0; +}; +/// @brief Implements IterableContainer and provides iterable std::priority_queue class +template, typename Comparator = std::less> +class IterablePriorityQueue : public IterableContainer, public std::priority_queue { +public: + IterablePriorityQueue(std::priority_queue queue_) { + std::size_t count_ = 0; + while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) { + this->push(queue_.top()); + queue_.pop(); + } + } +private: + inline Container& getContainer(void) { + return this->c; + } +}; +/// @brief Implements IterableContainer and provides iterable std::queue class +template> +class IterableQueue : public IterableContainer, public std::queue { +public: + IterableQueue(std::queue queue_) { + std::size_t count_ = 0; + while (++count_ < base::consts::kMaxLogPerContainer && !queue_.empty()) { + this->push(queue_.front()); + queue_.pop(); + } + } +private: + inline Container& getContainer(void) { + return this->c; + } +}; +/// @brief Implements IterableContainer and provides iterable std::stack class +template> +class IterableStack : public IterableContainer, public std::stack { +public: + IterableStack(std::stack stack_) { + std::size_t count_ = 0; + while (++count_ < base::consts::kMaxLogPerContainer && !stack_.empty()) { + this->push(stack_.top()); + stack_.pop(); + } + } +private: + inline Container& getContainer(void) { + return this->c; + } +}; +} // namespace workarounds +#endif // defined(ELPP_STL_LOGGING) +// Log message builder +class MessageBuilder { +public: + MessageBuilder(void) : m_logger(nullptr), m_containerLogSeperator(ELPP_LITERAL("")) {} + void initialize(Logger* logger) { + m_logger = logger; + m_containerLogSeperator = ELPP->hasFlag(LoggingFlag::NewLineForContainer) ? + ELPP_LITERAL("\n ") : ELPP_LITERAL(", "); + } + +# define ELPP_SIMPLE_LOG(LOG_TYPE)\ + inline MessageBuilder& operator<<(LOG_TYPE msg) {\ + m_logger->stream() << msg;\ + if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) {\ + m_logger->stream() << " ";\ + }\ + return *this;\ + } + + inline MessageBuilder& operator<<(const std::string& msg) { + return operator<<(msg.c_str()); + } + ELPP_SIMPLE_LOG(char) + ELPP_SIMPLE_LOG(bool) + ELPP_SIMPLE_LOG(signed short) + ELPP_SIMPLE_LOG(unsigned short) + ELPP_SIMPLE_LOG(signed int) + ELPP_SIMPLE_LOG(unsigned int) + ELPP_SIMPLE_LOG(signed long) + ELPP_SIMPLE_LOG(unsigned long) + ELPP_SIMPLE_LOG(float) + ELPP_SIMPLE_LOG(double) + ELPP_SIMPLE_LOG(char*) + ELPP_SIMPLE_LOG(const char*) + ELPP_SIMPLE_LOG(const void*) + ELPP_SIMPLE_LOG(long double) + inline MessageBuilder& operator<<(const std::wstring& msg) { + return operator<<(msg.c_str()); + } + inline MessageBuilder& operator<<(const wchar_t* msg) { + if (msg == nullptr) { + m_logger->stream() << base::consts::kNullPointer; + return *this; + } +# if defined(ELPP_UNICODE) + m_logger->stream() << msg; +# else + char* buff_ = base::utils::Str::wcharPtrToCharPtr(msg); + m_logger->stream() << buff_; + free(buff_); +# endif + if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) { + m_logger->stream() << " "; + } + return *this; + } + // ostream manipulators + inline MessageBuilder& operator<<(std::ostream& (*OStreamMani)(std::ostream&)) { + m_logger->stream() << OStreamMani; + return *this; + } +#define ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(temp) \ + template \ + inline MessageBuilder& operator<<(const temp& template_inst) { \ + return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ + } +#define ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(temp) \ + template \ + inline MessageBuilder& operator<<(const temp& template_inst) { \ + return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ + } +#define ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(temp) \ + template \ + inline MessageBuilder& operator<<(const temp& template_inst) { \ + return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ + } +#define ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(temp) \ + template \ + inline MessageBuilder& operator<<(const temp& template_inst) { \ + return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ + } +#define ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(temp) \ + template \ + inline MessageBuilder& operator<<(const temp& template_inst) { \ + return writeIterator(template_inst.begin(), template_inst.end(), template_inst.size()); \ + } + +#if defined(ELPP_STL_LOGGING) + ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::vector) + ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::list) + ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(std::deque) + ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::set) + ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(std::multiset) + ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::map) + ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::multimap) + template + inline MessageBuilder& operator<<(const std::queue& queue_) { + base::workarounds::IterableQueue iterableQueue_ = + static_cast >(queue_); + return writeIterator(iterableQueue_.begin(), iterableQueue_.end(), iterableQueue_.size()); + } + template + inline MessageBuilder& operator<<(const std::stack& stack_) { + base::workarounds::IterableStack iterableStack_ = + static_cast >(stack_); + return writeIterator(iterableStack_.begin(), iterableStack_.end(), iterableStack_.size()); + } + template + inline MessageBuilder& operator<<(const std::priority_queue& priorityQueue_) { + base::workarounds::IterablePriorityQueue iterablePriorityQueue_ = + static_cast >(priorityQueue_); + return writeIterator(iterablePriorityQueue_.begin(), iterablePriorityQueue_.end(), iterablePriorityQueue_.size()); + } + template + inline MessageBuilder& operator<<(const std::pair& pair_) { + m_logger->stream() << ELPP_LITERAL("("); + operator << (static_cast(pair_.first)); + m_logger->stream() << ELPP_LITERAL(", "); + operator << (static_cast(pair_.second)); + m_logger->stream() << ELPP_LITERAL(")"); + return *this; + } + template + inline MessageBuilder& operator<<(const std::bitset& bitset_) { + m_logger->stream() << ELPP_LITERAL("["); + operator << (bitset_.to_string()); + m_logger->stream() << ELPP_LITERAL("]"); + return *this; + } +# if defined(ELPP_LOG_STD_ARRAY) + template + inline MessageBuilder& operator<<(const std::array& array) { + return writeIterator(array.begin(), array.end(), array.size()); + } +# endif // defined(ELPP_LOG_STD_ARRAY) +# if defined(ELPP_LOG_UNORDERED_MAP) + ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_map) + ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG(std::unordered_multimap) +# endif // defined(ELPP_LOG_UNORDERED_MAP) +# if defined(ELPP_LOG_UNORDERED_SET) + ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_set) + ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(std::unordered_multiset) +# endif // defined(ELPP_LOG_UNORDERED_SET) +#endif // defined(ELPP_STL_LOGGING) +#if defined(ELPP_QT_LOGGING) + inline MessageBuilder& operator<<(const QString& msg) { +# if defined(ELPP_UNICODE) + m_logger->stream() << msg.toStdWString(); +# else + m_logger->stream() << msg.toStdString(); +# endif // defined(ELPP_UNICODE) + return *this; + } + inline MessageBuilder& operator<<(const QByteArray& msg) { + return operator << (QString(msg)); + } + inline MessageBuilder& operator<<(const QStringRef& msg) { + return operator<<(msg.toString()); + } + inline MessageBuilder& operator<<(qint64 msg) { +# if defined(ELPP_UNICODE) + m_logger->stream() << QString::number(msg).toStdWString(); +# else + m_logger->stream() << QString::number(msg).toStdString(); +# endif // defined(ELPP_UNICODE) + return *this; + } + inline MessageBuilder& operator<<(quint64 msg) { +# if defined(ELPP_UNICODE) + m_logger->stream() << QString::number(msg).toStdWString(); +# else + m_logger->stream() << QString::number(msg).toStdString(); +# endif // defined(ELPP_UNICODE) + return *this; + } + inline MessageBuilder& operator<<(QChar msg) { + m_logger->stream() << msg.toLatin1(); + return *this; + } + inline MessageBuilder& operator<<(const QLatin1String& msg) { + m_logger->stream() << msg.latin1(); + return *this; + } + ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QList) + ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QVector) + ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QQueue) + ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QSet) + ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QLinkedList) + ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(QStack) + template + inline MessageBuilder& operator<<(const QPair& pair_) { + m_logger->stream() << ELPP_LITERAL("("); + operator << (static_cast(pair_.first)); + m_logger->stream() << ELPP_LITERAL(", "); + operator << (static_cast(pair_.second)); + m_logger->stream() << ELPP_LITERAL(")"); + return *this; + } + template + inline MessageBuilder& operator<<(const QMap& map_) { + m_logger->stream() << ELPP_LITERAL("["); + QList keys = map_.keys(); + typename QList::const_iterator begin = keys.begin(); + typename QList::const_iterator end = keys.end(); + int max_ = static_cast(base::consts::kMaxLogPerContainer); // to prevent warning + for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) { + m_logger->stream() << ELPP_LITERAL("("); + operator << (static_cast(*begin)); + m_logger->stream() << ELPP_LITERAL(", "); + operator << (static_cast(map_.value(*begin))); + m_logger->stream() << ELPP_LITERAL(")"); + m_logger->stream() << ((index_ < keys.size() -1) ? m_containerLogSeperator : ELPP_LITERAL("")); + } + if (begin != end) { + m_logger->stream() << ELPP_LITERAL("..."); + } + m_logger->stream() << ELPP_LITERAL("]"); + return *this; + } + template + inline MessageBuilder& operator<<(const QMultiMap& map_) { + operator << (static_cast>(map_)); + return *this; + } + template + inline MessageBuilder& operator<<(const QHash& hash_) { + m_logger->stream() << ELPP_LITERAL("["); + QList keys = hash_.keys(); + typename QList::const_iterator begin = keys.begin(); + typename QList::const_iterator end = keys.end(); + int max_ = static_cast(base::consts::kMaxLogPerContainer); // prevent type warning + for (int index_ = 0; begin != end && index_ < max_; ++index_, ++begin) { + m_logger->stream() << ELPP_LITERAL("("); + operator << (static_cast(*begin)); + m_logger->stream() << ELPP_LITERAL(", "); + operator << (static_cast(hash_.value(*begin))); + m_logger->stream() << ELPP_LITERAL(")"); + m_logger->stream() << ((index_ < keys.size() -1) ? m_containerLogSeperator : ELPP_LITERAL("")); + } + if (begin != end) { + m_logger->stream() << ELPP_LITERAL("..."); + } + m_logger->stream() << ELPP_LITERAL("]"); + return *this; + } + template + inline MessageBuilder& operator<<(const QMultiHash& multiHash_) { + operator << (static_cast>(multiHash_)); + return *this; + } +#endif // defined(ELPP_QT_LOGGING) +#if defined(ELPP_BOOST_LOGGING) + ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::vector) + ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::stable_vector) + ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::list) + ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG(boost::container::deque) + ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::map) + ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG(boost::container::flat_map) + ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::set) + ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG(boost::container::flat_set) +#endif // defined(ELPP_BOOST_LOGGING) + +/// @brief Macro used internally that can be used externally to make containers easylogging++ friendly +/// +/// @detail This macro expands to write an ostream& operator<< for container. This container is expected to +/// have begin() and end() methods that return respective iterators +/// @param ContainerType Type of container e.g, MyList from WX_DECLARE_LIST(int, MyList); in wxwidgets +/// @param SizeMethod Method used to get size of container. +/// @param ElementInstance Instance of element to be fed out. Insance name is "elem". See WXELPP_ENABLED macro +/// for an example usage +#define MAKE_CONTAINERELPP_FRIENDLY(ContainerType, SizeMethod, ElementInstance) \ + el::base::type::ostream_t& operator<<(el::base::type::ostream_t& ss, const ContainerType& container) {\ + const el::base::type::char_t* sep = ELPP->hasFlag(el::LoggingFlag::NewLineForContainer) ? \ + ELPP_LITERAL("\n ") : ELPP_LITERAL(", ");\ + ContainerType::const_iterator elem = container.begin();\ + ContainerType::const_iterator endElem = container.end();\ + std::size_t size_ = container.SizeMethod; \ + ss << ELPP_LITERAL("[");\ + for (std::size_t i = 0; elem != endElem && i < el::base::consts::kMaxLogPerContainer; ++i, ++elem) { \ + ss << ElementInstance;\ + ss << ((i < size_ - 1) ? sep : ELPP_LITERAL(""));\ + }\ + if (elem != endElem) {\ + ss << ELPP_LITERAL("...");\ + }\ + ss << ELPP_LITERAL("]");\ + return ss;\ + } +#if defined(ELPP_WXWIDGETS_LOGGING) + ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG(wxVector) +# define ELPP_WX_PTR_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), *(*elem)) +# define ELPP_WX_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), (*elem)) +# define ELPP_WX_HASH_MAP_ENABLED(ContainerType) MAKE_CONTAINERELPP_FRIENDLY(ContainerType, size(), \ + ELPP_LITERAL("(") << elem->first << ELPP_LITERAL(", ") << elem->second << ELPP_LITERAL(")") +#else +# define ELPP_WX_PTR_ENABLED(ContainerType) +# define ELPP_WX_ENABLED(ContainerType) +# define ELPP_WX_HASH_MAP_ENABLED(ContainerType) +#endif // defined(ELPP_WXWIDGETS_LOGGING) + // Other classes + template + ELPP_SIMPLE_LOG(const Class&) +#undef ELPP_SIMPLE_LOG +#undef ELPP_ITERATOR_CONTAINER_LOG_ONE_ARG +#undef ELPP_ITERATOR_CONTAINER_LOG_TWO_ARG +#undef ELPP_ITERATOR_CONTAINER_LOG_THREE_ARG +#undef ELPP_ITERATOR_CONTAINER_LOG_FOUR_ARG +#undef ELPP_ITERATOR_CONTAINER_LOG_FIVE_ARG +private: + Logger* m_logger; + const base::type::char_t* m_containerLogSeperator; + + template + inline MessageBuilder& writeIterator(Iterator begin_, Iterator end_, std::size_t size_) { + m_logger->stream() << ELPP_LITERAL("["); + for (std::size_t i = 0; begin_ != end_ && i < base::consts::kMaxLogPerContainer; ++i, ++begin_) { + operator << (*begin_); + m_logger->stream() << ((i < size_ - 1) ? m_containerLogSeperator : ELPP_LITERAL("")); + } + if (begin_ != end_) { + m_logger->stream() << ELPP_LITERAL("..."); + } + m_logger->stream() << ELPP_LITERAL("]"); + if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) { + m_logger->stream() << " "; + } + return *this; + } +}; +/// @brief Writes nothing - Used when certain log is disabled +class NullWriter : base::NoCopy { +public: + NullWriter(void) {} + + // Null manipulator + inline NullWriter& operator<<(std::ostream& (*)(std::ostream&)) { + return *this; + } + + template + inline NullWriter& operator<<(const T&) { + return *this; + } +}; +/// @brief Main entry point of each logging +class Writer : base::NoCopy { +public: + Writer(Level level, const char* file, unsigned long int line, + const char* func, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog, + base::type::VerboseLevel verboseLevel = 0) : + m_level(level), m_file(file), m_line(line), m_func(func), m_verboseLevel(verboseLevel), + m_proceed(false), m_dispatchAction(dispatchAction) { + } + + virtual ~Writer(void) { + processDispatch(); + } + + template + inline Writer& operator<<(const T& log) { +#if ELPP_LOGGING_ENABLED + if (m_proceed) { + m_messageBuilder << log; + } +#endif // ELPP_LOGGING_ENABLED + return *this; + } + + inline Writer& operator<<(std::ostream& (*log)(std::ostream&)) { +#if ELPP_LOGGING_ENABLED + if (m_proceed) { + m_messageBuilder << log; + } +#endif // ELPP_LOGGING_ENABLED + return *this; + } + + Writer& construct(Logger* logger, bool needLock = true) { + m_logger = logger; + initializeLogger(logger->id(), false, needLock); + m_messageBuilder.initialize(m_logger); + return *this; + } + + Writer& construct(int count, const char* loggerIds, ...) { + if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) { + va_list loggersList; + va_start(loggersList, loggerIds); + const char* id = loggerIds; + for (int i = 0; i < count; ++i) { + m_loggerIds.push_back(std::string(id)); + id = va_arg(loggersList, const char*); + } + va_end(loggersList); + initializeLogger(m_loggerIds.at(0)); + } else { + initializeLogger(std::string(loggerIds)); + } + m_messageBuilder.initialize(m_logger); + return *this; + } +protected: + Level m_level; + const char* m_file; + const unsigned long int m_line; + const char* m_func; + base::type::VerboseLevel m_verboseLevel; + Logger* m_logger; + bool m_proceed; + base::MessageBuilder m_messageBuilder; + base::DispatchAction m_dispatchAction; + std::vector m_loggerIds; + friend class el::Helpers; + + void initializeLogger(const std::string& loggerId, bool lookup = true, bool needLock = true) { + if (lookup) { + m_logger = ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically)); + } + if (m_logger == nullptr) { + ELPP->acquireLock(); + if (!ELPP->registeredLoggers()->has(std::string(base::consts::kDefaultLoggerId))) { + // Somehow default logger has been unregistered. Not good! Register again + ELPP->registeredLoggers()->get(std::string(base::consts::kDefaultLoggerId)); + } + ELPP->releaseLock(); // Need to unlock it for next writer + Writer(Level::Debug, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId) + << "Logger [" << loggerId << "] is not registered yet!"; + m_proceed = false; + } else { + if (needLock) { + m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because + // m_proceed can be changed by lines below + } + if (ELPP->hasFlag(LoggingFlag::HierarchicalLogging)) { + m_proceed = m_level == Level::Verbose ? m_logger->enabled(m_level) : + LevelHelper::castToInt(m_level) >= LevelHelper::castToInt(ELPP->m_loggingLevel); + } else { + m_proceed = m_logger->enabled(m_level); + } + } + } + + void processDispatch() { +#if ELPP_LOGGING_ENABLED + if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) { + bool firstDispatched = false; + base::type::string_t logMessage; + std::size_t i = 0; + do { + if (m_proceed) { + if (firstDispatched) { + m_logger->stream() << logMessage; + } else { + firstDispatched = true; + if (m_loggerIds.size() > 1) { + logMessage = m_logger->stream().str(); + } + } + triggerDispatch(); + } else if (m_logger != nullptr) { + m_logger->stream().str(ELPP_LITERAL("")); + m_logger->releaseLock(); + } + if (i + 1 < m_loggerIds.size()) { + initializeLogger(m_loggerIds.at(i + 1)); + } + } while (++i < m_loggerIds.size()); + } else { + if (m_proceed) { + triggerDispatch(); + } else if (m_logger != nullptr) { + m_logger->stream().str(ELPP_LITERAL("")); + m_logger->releaseLock(); + } + } +#else + if (m_logger != nullptr) { + m_logger->stream().str(ELPP_LITERAL("")); + m_logger->releaseLock(); + } +#endif // ELPP_LOGGING_ENABLED + } + + void triggerDispatch(void) { + if (m_proceed) { + base::LogDispatcher(m_proceed, LogMessage(m_level, m_file, m_line, m_func, m_verboseLevel, + m_logger), m_dispatchAction).dispatch(); + } + if (m_logger != nullptr) { + m_logger->stream().str(ELPP_LITERAL("")); + m_logger->releaseLock(); + } + if (m_proceed && m_level == Level::Fatal + && !ELPP->hasFlag(LoggingFlag::DisableApplicationAbortOnFatalLog)) { + base::Writer(Level::Warning, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId) + << "Aborting application. Reason: Fatal log at [" << m_file << ":" << m_line << "]"; + std::stringstream reasonStream; + reasonStream << "Fatal log at [" << m_file << ":" << m_line << "]" + << " If you wish to disable 'abort on fatal log' please use " + << "el::Helpers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog)"; + base::utils::abort(1, reasonStream.str()); + } + m_proceed = false; + } +}; +class PErrorWriter : public base::Writer { +public: + PErrorWriter(Level level, const char* file, unsigned long int line, + const char* func, base::DispatchAction dispatchAction = base::DispatchAction::NormalLog, + base::type::VerboseLevel verboseLevel = 0) : + base::Writer(level, file, line, func, dispatchAction, verboseLevel) { + } + + virtual ~PErrorWriter(void) { + if (m_proceed) { +#if ELPP_COMPILER_MSVC + char buff[256]; + strerror_s(buff, 256, errno); + m_logger->stream() << ": " << buff << " [" << errno << "]"; +#else + m_logger->stream() << ": " << strerror(errno) << " [" << errno << "]"; +#endif + } + } +}; +} // namespace base +// Logging from Logger class. Why this is here? Because we have Storage and Writer class available +#if ELPP_VARIADIC_TEMPLATES_SUPPORTED + template + void Logger::log_(Level level, int vlevel, const char* s, const T& value, const Args&... args) { + base::MessageBuilder b; + b.initialize(this); + while (*s) { + if (*s == base::consts::kFormatSpecifierChar) { + if (*(s + 1) == base::consts::kFormatSpecifierChar) { + ++s; + } else { + if (*(s + 1) == base::consts::kFormatSpecifierCharValue) { + ++s; + b << value; + log_(level, vlevel, ++s, args...); + return; + } + } + } + b << *s++; + } + ELPP_INTERNAL_ERROR("Too many arguments provided. Unable to handle. Please provide more format specifiers", false); + } + template + inline void Logger::log_(Level level, int vlevel, const T& log) { + if (level == Level::Verbose) { + if (ELPP->vRegistry()->allowed(vlevel, __FILE__)) { + base::Writer(Level::Verbose, "FILE", 0, "FUNCTION", + base::DispatchAction::NormalLog, vlevel).construct(this, false) << log; + } else { + stream().str(ELPP_LITERAL("")); + } + } else { + base::Writer(level, "FILE", 0, "FUNCTION").construct(this, false) << log; + } + } + template + void Logger::log(Level level, const char* s, const T& value, const Args&... args) { + base::threading::ScopedLock scopedLock(lock()); + log_(level, 0, s, value, args...); + } + template + inline void Logger::log(Level level, const T& log) { + base::threading::ScopedLock scopedLock(lock()); + log_(level, 0, log); + } +# if ELPP_VERBOSE_LOG + template + inline void Logger::verbose(int vlevel, const char* s, const T& value, const Args&... args) { + base::threading::ScopedLock scopedLock(lock()); + log_(el::Level::Verbose, vlevel, s, value, args...); + } + template + inline void Logger::verbose(int vlevel, const T& log) { + base::threading::ScopedLock scopedLock(lock()); + log_(el::Level::Verbose, vlevel, log); + } +# else + template + inline void Logger::verbose(int, const char*, const T&, const Args&...) { + return; + } + template + inline void Logger::verbose(int, const T&) { + return; + } +# endif // ELPP_VERBOSE_LOG +# define LOGGER_LEVEL_WRITERS(FUNCTION_NAME, LOG_LEVEL)\ + template \ + inline void Logger::FUNCTION_NAME(const char* s, const T& value, const Args&... args) {\ + log(LOG_LEVEL, s, value, args...);\ + }\ + template \ + inline void Logger::FUNCTION_NAME(const T& value) {\ + log(LOG_LEVEL, value);\ + } +# define LOGGER_LEVEL_WRITERS_DISABLED(FUNCTION_NAME, LOG_LEVEL)\ + template \ + inline void Logger::FUNCTION_NAME(const char*, const T&, const Args&...) {\ + return;\ + }\ + template \ + inline void Logger::FUNCTION_NAME(const T&) {\ + return;\ + } + +# if ELPP_INFO_LOG + LOGGER_LEVEL_WRITERS(info, Level::Info) +# else + LOGGER_LEVEL_WRITERS_DISABLED(info, Level::Info) +# endif // ELPP_INFO_LOG +# if ELPP_DEBUG_LOG + LOGGER_LEVEL_WRITERS(debug, Level::Debug) +# else + LOGGER_LEVEL_WRITERS_DISABLED(debug, Level::Debug) +# endif // ELPP_DEBUG_LOG +# if ELPP_WARNING_LOG + LOGGER_LEVEL_WRITERS(warn, Level::Warning) +# else + LOGGER_LEVEL_WRITERS_DISABLED(warn, Level::Warning) +# endif // ELPP_WARNING_LOG +# if ELPP_ERROR_LOG + LOGGER_LEVEL_WRITERS(error, Level::Error) +# else + LOGGER_LEVEL_WRITERS_DISABLED(error, Level::Error) +# endif // ELPP_ERROR_LOG +# if ELPP_FATAL_LOG + LOGGER_LEVEL_WRITERS(fatal, Level::Fatal) +# else + LOGGER_LEVEL_WRITERS_DISABLED(fatal, Level::Fatal) +# endif // ELPP_FATAL_LOG +# if ELPP_TRACE_LOG + LOGGER_LEVEL_WRITERS(trace, Level::Trace) +# else + LOGGER_LEVEL_WRITERS_DISABLED(trace, Level::Trace) +# endif // ELPP_TRACE_LOG +# undef LOGGER_LEVEL_WRITERS +# undef LOGGER_LEVEL_WRITERS_DISABLED +#endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED +#if ELPP_COMPILER_MSVC +# define ELPP_VARIADIC_FUNC_MSVC(variadicFunction, variadicArgs) variadicFunction variadicArgs +# define ELPP_VARIADIC_FUNC_MSVC_RUN(variadicFunction, ...) ELPP_VARIADIC_FUNC_MSVC(variadicFunction, (__VA_ARGS__)) +# define el_getVALength(...) ELPP_VARIADIC_FUNC_MSVC_RUN(el_resolveVALength, 0, ## __VA_ARGS__,\ + 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +#else +# if ELPP_COMPILER_CLANG +# define el_getVALength(...) el_resolveVALength(0, __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +# else +# define el_getVALength(...) el_resolveVALength(0, ## __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) +# endif // ELPP_COMPILER_CLANG +#endif // ELPP_COMPILER_MSVC +#define el_resolveVALength(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N +#define ELPP_WRITE_LOG(writer, level, dispatchAction, ...) \ + writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) +#define ELPP_WRITE_LOG_IF(writer, condition, level, dispatchAction, ...) if (condition) \ + writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) +#define ELPP_WRITE_LOG_EVERY_N(writer, occasion, level, dispatchAction, ...) \ + if (ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion)) \ + writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) +#define ELPP_WRITE_LOG_AFTER_N(writer, n, level, dispatchAction, ...) \ + if (ELPP->validateAfterNCounter(__FILE__, __LINE__, n)) \ + writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) +#define ELPP_WRITE_LOG_N_TIMES(writer, n, level, dispatchAction, ...) \ + if (ELPP->validateNTimesCounter(__FILE__, __LINE__, n)) \ + writer(level, __FILE__, __LINE__, ELPP_FUNC, dispatchAction).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) +#undef ELPP_CURR_FILE_PERFORMANCE_LOGGER +#if defined(ELPP_PERFORMANCE_LOGGER) +# define ELPP_CURR_FILE_PERFORMANCE_LOGGER ELPP_PERFORMANCE_LOGGER +#else +# define ELPP_CURR_FILE_PERFORMANCE_LOGGER el::base::consts::kPerformanceLoggerId +#endif +class PerformanceTrackingData { +public: + enum class DataType : base::type::EnumType { + Checkpoint = 1, Complete = 2 + }; + // Do not use constructor, will run into multiple definition error, use init(PerformanceTracker*) + explicit PerformanceTrackingData(DataType dataType) : m_performanceTracker(nullptr), + m_dataType(dataType), m_file(""), m_line(0), m_func("") {} + inline const std::string* blockName(void) const; + inline const struct timeval* startTime(void) const; + inline const struct timeval* endTime(void) const; + inline const struct timeval* lastCheckpointTime(void) const; + inline const base::PerformanceTracker* performanceTracker(void) const { return m_performanceTracker; } + inline PerformanceTrackingData::DataType dataType(void) const { return m_dataType; } + inline bool firstCheckpoint(void) const { return m_firstCheckpoint; } + inline std::string checkpointId(void) const { return m_checkpointId; } + inline const char* file(void) const { return m_file; } + inline unsigned long int line(void) const { return m_line; } + inline const char* func(void) const { return m_func; } + inline const base::type::string_t* formattedTimeTaken() const { return &m_formattedTimeTaken; } + inline const std::string& loggerId(void) const; +private: + base::PerformanceTracker* m_performanceTracker; + base::type::string_t m_formattedTimeTaken; + PerformanceTrackingData::DataType m_dataType; + bool m_firstCheckpoint; + std::string m_checkpointId; + const char* m_file; + unsigned long int m_line; + const char* m_func; + inline void init(base::PerformanceTracker* performanceTracker, bool firstCheckpoint = false) { + m_performanceTracker = performanceTracker; + m_firstCheckpoint = firstCheckpoint; + } + + friend class el::base::PerformanceTracker; +}; +namespace base { +/// @brief Represents performanceTracker block of code that conditionally adds performance status to log +/// either when goes outside the scope of when checkpoint() is called +class PerformanceTracker : public base::threading::ThreadSafe, public Loggable { +public: + PerformanceTracker(const std::string& blockName, + base::TimestampUnit timestampUnit = base::TimestampUnit::Millisecond, + const std::string& loggerId = std::string(ELPP_CURR_FILE_PERFORMANCE_LOGGER), + bool scopedLog = true, Level level = base::consts::kPerformanceTrackerDefaultLevel) : + m_blockName(blockName), m_timestampUnit(timestampUnit), m_loggerId(loggerId), m_scopedLog(scopedLog), + m_level(level), m_hasChecked(false), m_lastCheckpointId(std::string()), m_enabled(false) { +#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED + // We store it locally so that if user happen to change configuration by the end of scope + // or before calling checkpoint, we still depend on state of configuraton at time of construction + el::Logger* loggerPtr = ELPP->registeredLoggers()->get(loggerId, false); + m_enabled = loggerPtr != nullptr && loggerPtr->m_typedConfigurations->performanceTracking(m_level); + if (m_enabled) { + base::utils::DateTime::gettimeofday(&m_startTime); + } +#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED + } + /// @brief Copy constructor + PerformanceTracker(const PerformanceTracker& t) : + m_blockName(t.m_blockName), m_timestampUnit(t.m_timestampUnit), m_loggerId(t.m_loggerId), m_scopedLog(t.m_scopedLog), + m_level(t.m_level), m_hasChecked(t.m_hasChecked), m_lastCheckpointId(t.m_lastCheckpointId), m_enabled(t.m_enabled), + m_startTime(t.m_startTime), m_endTime(t.m_endTime), m_lastCheckpointTime(t.m_lastCheckpointTime) { + } + virtual ~PerformanceTracker(void) { +#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED + if (m_enabled) { + base::threading::ScopedLock scopedLock(lock()); + if (m_scopedLog) { + base::utils::DateTime::gettimeofday(&m_endTime); + base::type::string_t formattedTime = getFormattedTimeTaken(); + PerformanceTrackingData data(PerformanceTrackingData::DataType::Complete); + data.init(this); + data.m_formattedTimeTaken = formattedTime; + PerformanceTrackingCallback* callback = nullptr; + for (const std::pair& h + : ELPP->m_performanceTrackingCallbacks) { + callback = h.second.get(); + if (callback != nullptr && callback->enabled()) { + callback->acquireLock(); + callback->handle(&data); + callback->releaseLock(); + } + } + } + } +#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) + } + /// @brief A checkpoint for current performanceTracker block. + void checkpoint(const std::string& id = std::string(), const char* file = __FILE__, unsigned long int line = __LINE__, const char* func = "") { +#if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED + if (m_enabled) { + base::threading::ScopedLock scopedLock(lock()); + base::utils::DateTime::gettimeofday(&m_endTime); + base::type::string_t formattedTime = m_hasChecked ? getFormattedTimeTaken(m_lastCheckpointTime) : ELPP_LITERAL(""); + PerformanceTrackingData data(PerformanceTrackingData::DataType::Checkpoint); + data.init(this); + data.m_checkpointId = id; + data.m_file = file; + data.m_line = line; + data.m_func = func; + data.m_formattedTimeTaken = formattedTime; + PerformanceTrackingCallback* callback = nullptr; + for (const std::pair& h + : ELPP->m_performanceTrackingCallbacks) { + callback = h.second.get(); + if (callback != nullptr && callback->enabled()) { + callback->acquireLock(); + callback->handle(&data); + callback->releaseLock(); + } + } + base::utils::DateTime::gettimeofday(&m_lastCheckpointTime); + m_hasChecked = true; + m_lastCheckpointId = id; + } +#endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED + ELPP_UNUSED(id); + ELPP_UNUSED(file); + ELPP_UNUSED(line); + ELPP_UNUSED(func); + } + inline Level level(void) const { return m_level; } +private: + std::string m_blockName; + base::TimestampUnit m_timestampUnit; + std::string m_loggerId; + bool m_scopedLog; + Level m_level; + bool m_hasChecked; + std::string m_lastCheckpointId; + bool m_enabled; + struct timeval m_startTime, m_endTime, m_lastCheckpointTime; + + PerformanceTracker(void); + + friend class el::PerformanceTrackingData; + friend class base::DefaultPerformanceTrackingCallback; + + const inline base::type::string_t getFormattedTimeTaken() const { + return getFormattedTimeTaken(m_startTime); + } + + const base::type::string_t getFormattedTimeTaken(struct timeval startTime) const { + if (ELPP->hasFlag(LoggingFlag::FixedTimeFormat)) { + base::type::stringstream_t ss; + ss << base::utils::DateTime::getTimeDifference(m_endTime, + startTime, m_timestampUnit) << " " << base::consts::kTimeFormats[static_cast(m_timestampUnit)].unit; + return ss.str(); + } + return base::utils::DateTime::formatTime(base::utils::DateTime::getTimeDifference(m_endTime, + startTime, m_timestampUnit), m_timestampUnit); + } + + virtual inline void log(el::base::type::ostream_t& os) const { + os << getFormattedTimeTaken(); + } +}; +class DefaultPerformanceTrackingCallback : public PerformanceTrackingCallback { +protected: + void handle(const PerformanceTrackingData* data) { + m_data = data; + base::type::stringstream_t ss; + if (m_data->dataType() == PerformanceTrackingData::DataType::Complete) { + ss << ELPP_LITERAL("Executed [") << m_data->blockName()->c_str() << ELPP_LITERAL("] in [") << *m_data->formattedTimeTaken() << ELPP_LITERAL("]"); + } else { + ss << ELPP_LITERAL("Performance checkpoint"); + if (!m_data->checkpointId().empty()) { + ss << ELPP_LITERAL(" [") << m_data->checkpointId().c_str() << ELPP_LITERAL("]"); + } + ss << ELPP_LITERAL(" for block [") << m_data->blockName()->c_str() << ELPP_LITERAL("] : [") << *m_data->performanceTracker(); + if (!ELPP->hasFlag(LoggingFlag::DisablePerformanceTrackingCheckpointComparison) && m_data->performanceTracker()->m_hasChecked) { + ss << ELPP_LITERAL(" ([") << *m_data->formattedTimeTaken() << ELPP_LITERAL("] from "); + if (m_data->performanceTracker()->m_lastCheckpointId.empty()) { + ss << ELPP_LITERAL("last checkpoint"); + } else { + ss << ELPP_LITERAL("checkpoint '") << m_data->performanceTracker()->m_lastCheckpointId.c_str() << ELPP_LITERAL("'"); + } + ss << ELPP_LITERAL(")]"); + } else { + ss << ELPP_LITERAL("]"); + } + } + el::base::Writer(m_data->performanceTracker()->level(), m_data->file(), m_data->line(), m_data->func()).construct(1, m_data->loggerId().c_str()) << ss.str(); + } +private: + const PerformanceTrackingData* m_data; +}; +} // namespace base +inline const std::string* PerformanceTrackingData::blockName() const { + return const_cast(&m_performanceTracker->m_blockName); +} +inline const struct timeval* PerformanceTrackingData::startTime() const { + return const_cast(&m_performanceTracker->m_startTime); +} +inline const struct timeval* PerformanceTrackingData::endTime() const { + return const_cast(&m_performanceTracker->m_endTime); +} +inline const struct timeval* PerformanceTrackingData::lastCheckpointTime() const { + return const_cast(&m_performanceTracker->m_lastCheckpointTime); +} +inline const std::string& PerformanceTrackingData::loggerId(void) const { return m_performanceTracker->m_loggerId; } +namespace base { +/// @brief Contains some internal debugging tools like crash handler and stack tracer +namespace debug { +class StackTrace : base::NoCopy { +public: + static const std::size_t kMaxStack = 64; + static const std::size_t kStackStart = 2; // We want to skip c'tor and StackTrace::generateNew() + class StackTraceEntry { + public: + StackTraceEntry(std::size_t index, const char* loc, const char* demang, const char* hex, const char* addr) { + m_index = index; + m_location = std::string(loc); + m_demangled = std::string(demang); + m_hex = std::string(hex); + m_addr = std::string(addr); + } + StackTraceEntry(std::size_t index, char* loc) { + m_index = index; + m_location = std::string(loc); + } + std::size_t m_index; + std::string m_location; + std::string m_demangled; + std::string m_hex; + std::string m_addr; + friend std::ostream& operator<<(std::ostream& ss, const StackTraceEntry& si) { + ss << "[" << si.m_index << "] " << si.m_location << (si.m_demangled.empty() ? "" : ":") << si.m_demangled + << (si.m_hex.empty() ? "" : "+") << si.m_hex << si.m_addr; + return ss; + } + + private: + StackTraceEntry(void); + }; + + StackTrace(void) { + generateNew(); + } + + virtual ~StackTrace(void) { + } + + inline std::vector& getLatestStack(void) { + return m_stack; + } + + friend inline std::ostream& operator<<(std::ostream& os, const StackTrace& st) { + std::vector::const_iterator it = st.m_stack.begin(); + while (it != st.m_stack.end()) { + os << " " << *it++ << "\n"; + } + return os; + } + +private: + std::vector m_stack; + + void generateNew(void) { +#if ELPP_STACKTRACE + m_stack.clear(); + void* stack[kMaxStack]; + std::size_t size = backtrace(stack, kMaxStack); + char** strings = backtrace_symbols(stack, size); + if (size > kStackStart) { // Skip StackTrace c'tor and generateNew + for (std::size_t i = kStackStart; i < size; ++i) { + char* mangName = nullptr; + char* hex = nullptr; + char* addr = nullptr; + for (char* c = strings[i]; *c; ++c) { + switch (*c) { + case '(': + mangName = c; + break; + case '+': + hex = c; + break; + case ')': + addr = c; + break; + } + } + // Perform demangling if parsed properly + if (mangName != nullptr && hex != nullptr && addr != nullptr && mangName < hex) { + *mangName++ = '\0'; + *hex++ = '\0'; + *addr++ = '\0'; + int status = 0; + char* demangName = abi::__cxa_demangle(mangName, 0, 0, &status); + // if demangling is successful, output the demangled function name + if (status == 0) { + // Success (see http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html) + StackTraceEntry entry(i - 1, strings[i], demangName, hex, addr); + m_stack.push_back(entry); + } else { + // Not successful - we will use mangled name + StackTraceEntry entry(i - 1, strings[i], mangName, hex, addr); + m_stack.push_back(entry); + } + free(demangName); + } else { + StackTraceEntry entry(i - 1, strings[i]); + m_stack.push_back(entry); + } + } + } + free(strings); +#else + ELPP_INTERNAL_INFO(1, "Stacktrace generation not supported for selected compiler"); +#endif // ELPP_STACKTRACE + } +}; +static std::string crashReason(int sig) { + std::stringstream ss; + bool foundReason = false; + for (int i = 0; i < base::consts::kCrashSignalsCount; ++i) { + if (base::consts::kCrashSignals[i].numb == sig) { + ss << "Application has crashed due to [" << base::consts::kCrashSignals[i].name << "] signal"; + if (ELPP->hasFlag(el::LoggingFlag::LogDetailedCrashReason)) { + ss << std::endl << + " " << base::consts::kCrashSignals[i].brief << std::endl << + " " << base::consts::kCrashSignals[i].detail; + } + foundReason = true; + } + } + if (!foundReason) { + ss << "Application has crashed due to unknown signal [" << sig << "]"; + } + return ss.str(); +} +/// @brief Logs reason of crash from sig +static void logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) { + std::stringstream ss; + ss << "CRASH HANDLED; "; + ss << crashReason(sig); +#if ELPP_STACKTRACE + if (stackTraceIfAvailable) { + ss << std::endl << " ======= Backtrace: =========" << std::endl << base::debug::StackTrace(); + } +#else + ELPP_UNUSED(stackTraceIfAvailable); +#endif // ELPP_STACKTRACE + ELPP_WRITE_LOG(el::base::Writer, level, base::DispatchAction::NormalLog, logger) << ss.str(); +} +static inline void crashAbort(int sig) { + base::utils::abort(sig); +} +/// @brief Default application crash handler +/// +/// @detail This function writes log using 'default' logger, prints stack trace for GCC based compilers and aborts program. +static inline void defaultCrashHandler(int sig) { + base::debug::logCrashReason(sig, true, Level::Fatal, base::consts::kDefaultLoggerId); + base::debug::crashAbort(sig); +} +/// @brief Handles unexpected crashes +class CrashHandler : base::NoCopy { +public: + typedef void (*Handler)(int); + + explicit CrashHandler(bool useDefault) { + if (useDefault) { + setHandler(defaultCrashHandler); + } + } + explicit CrashHandler(const Handler& cHandler) { + setHandler(cHandler); + } + void setHandler(const Handler& cHandler) { + m_handler = cHandler; +#if defined(ELPP_HANDLE_SIGABRT) + int i = 0; // SIGABRT is at base::consts::kCrashSignals[0] +#else + int i = 1; +#endif // defined(ELPP_HANDLE_SIGABRT) + for (; i < base::consts::kCrashSignalsCount; ++i) { + m_handler = signal(base::consts::kCrashSignals[i].numb, cHandler); + } + } + +private: + Handler m_handler; +}; +} // namespace debug +} // namespace base +extern base::debug::CrashHandler elCrashHandler; +#define MAKE_LOGGABLE(ClassType, ClassInstance, OutputStreamInstance) \ + el::base::type::ostream_t& operator<<(el::base::type::ostream_t& OutputStreamInstance, const ClassType& ClassInstance) +/// @brief Initializes syslog with process ID, options and facility. calls closelog() on d'tor +class SysLogInitializer { +public: + SysLogInitializer(const char* processIdent, int options = 0, int facility = 0) { +#if defined(ELPP_SYSLOG) + openlog(processIdent, options, facility); +#else + ELPP_UNUSED(processIdent); + ELPP_UNUSED(options); + ELPP_UNUSED(facility); +#endif // defined(ELPP_SYSLOG) + } + virtual ~SysLogInitializer(void) { +#if defined(ELPP_SYSLOG) + closelog(); +#endif // defined(ELPP_SYSLOG) + } +}; +#define ELPP_INITIALIZE_SYSLOG(id, opt, fac) el::SysLogInitializer elSyslogInit(id, opt, fac) +/// @brief Static helpers for developers +class Helpers : base::StaticClass { +public: + /// @brief Shares logging repository (base::Storage) + static inline void setStorage(base::type::StoragePointer storage) { + ELPP = storage; + } + /// @return Main storage repository + static inline base::type::StoragePointer storage() { + return ELPP; + } + /// @brief Sets application arguments and figures out whats active for logging and whats not. + static inline void setArgs(int argc, char** argv) { + ELPP->setApplicationArguments(argc, argv); + } + /// @copydoc setArgs(int argc, char** argv) + static inline void setArgs(int argc, const char** argv) { + ELPP->setApplicationArguments(argc, const_cast(argv)); + } + /// @brief Overrides default crash handler and installs custom handler. + /// @param crashHandler A functor with no return type that takes single int argument. + /// Handler is a typedef with specification: void (*Handler)(int) + static inline void setCrashHandler(const el::base::debug::CrashHandler::Handler& crashHandler) { + el::elCrashHandler.setHandler(crashHandler); + } + /// @brief Abort due to crash with signal in parameter + /// @param sig Crash signal + static inline void crashAbort(int sig, const char* sourceFile = "", unsigned int long line = 0) { + std::stringstream ss; + ss << base::debug::crashReason(sig).c_str(); + ss << " - [Called el::Helpers::crashAbort(" << sig << ")]"; + if (sourceFile != nullptr && strlen(sourceFile) > 0) { + ss << " - Source: " << sourceFile; + if (line > 0) + ss << ":" << line; + else + ss << " (line number not specified)"; + } + base::utils::abort(sig, ss.str()); + } + /// @brief Logs reason of crash as per sig + /// @param sig Crash signal + /// @param stackTraceIfAvailable Includes stack trace if available + /// @param level Logging level + /// @param logger Logger to use for logging + static inline void logCrashReason(int sig, bool stackTraceIfAvailable = false, + Level level = Level::Fatal, const char* logger = base::consts::kDefaultLoggerId) { + el::base::debug::logCrashReason(sig, stackTraceIfAvailable, level, logger); + } + /// @brief Installs pre rollout callback, this callback is triggered when log file is about to be rolled out + /// (can be useful for backing up) + static inline void installPreRollOutCallback(const PreRollOutCallback& callback) { + ELPP->setPreRollOutCallback(callback); + } + /// @brief Uninstalls pre rollout callback + static inline void uninstallPreRollOutCallback(void) { + ELPP->unsetPreRollOutCallback(); + } + /// @brief Installs post log dispatch callback, this callback is triggered when log is dispatched + template + static inline bool installLogDispatchCallback(const std::string& id) { + return ELPP->installLogDispatchCallback(id); + } + /// @brief Uninstalls log dispatch callback + template + static inline void uninstallLogDispatchCallback(const std::string& id) { + ELPP->uninstallLogDispatchCallback(id); + } + template + static inline T* logDispatchCallback(const std::string& id) { + return ELPP->logDispatchCallback(id); + } + /// @brief Installs post performance tracking callback, this callback is triggered when performance tracking is finished + template + static inline bool installPerformanceTrackingCallback(const std::string& id) { + return ELPP->installPerformanceTrackingCallback(id); + } + /// @brief Uninstalls post performance tracking handler + template + static inline void uninstallPerformanceTrackingCallback(const std::string& id) { + ELPP->uninstallPerformanceTrackingCallback(id); + } + template + static inline T* performanceTrackingCallback(const std::string& id) { + return ELPP->performanceTrackingCallback(id); + } + /// @brief Converts template to std::string - useful for loggable classes to log containers within log(std::ostream&) const + template + static std::string convertTemplateToStdString(const T& templ) { + el::Logger* logger = + ELPP->registeredLoggers()->get(el::base::consts::kDefaultLoggerId); + if (logger == nullptr) { + return std::string(); + } + base::MessageBuilder b; + b.initialize(logger); + logger->acquireLock(); + b << templ; +#if defined(ELPP_UNICODE) + std::string s = std::string(logger->stream().str().begin(), logger->stream().str().end()); +#else + std::string s = logger->stream().str(); +#endif // defined(ELPP_UNICODE) + logger->stream().str(ELPP_LITERAL("")); + logger->releaseLock(); + return s; + } + /// @brief Returns command line arguments (pointer) provided to easylogging++ + static inline const el::base::utils::CommandLineArgs* commandLineArgs(void) { + return ELPP->commandLineArgs(); + } + /// @brief Installs user defined format specifier and handler + static inline void installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) { + ELPP->installCustomFormatSpecifier(customFormatSpecifier); + } + /// @brief Uninstalls user defined format specifier and handler + static inline bool uninstallCustomFormatSpecifier(const char* formatSpecifier) { + return ELPP->uninstallCustomFormatSpecifier(formatSpecifier); + } + /// @brief Returns true if custom format specifier is installed + static inline bool hasCustomFormatSpecifier(const char* formatSpecifier) { + return ELPP->hasCustomFormatSpecifier(formatSpecifier); + } + static inline void validateFileRolling(Logger* logger, Level level) { + if (logger == nullptr) return; + logger->m_typedConfigurations->validateFileRolling(level, ELPP->preRollOutCallback()); + } +}; +/// @brief Static helpers to deal with loggers and their configurations +class Loggers : base::StaticClass { +public: + /// @brief Gets existing or registers new logger + static inline Logger* getLogger(const std::string& identity, bool registerIfNotAvailable = true) { + base::threading::ScopedLock scopedLock(ELPP->lock()); + return ELPP->registeredLoggers()->get(identity, registerIfNotAvailable); + } + /// @brief Unregisters logger - use it only when you know what you are doing, you may unregister + /// loggers initialized / used by third-party libs. + static inline bool unregisterLogger(const std::string& identity) { + base::threading::ScopedLock scopedLock(ELPP->lock()); + return ELPP->registeredLoggers()->remove(identity); + } + /// @brief Whether or not logger with id is registered + static inline bool hasLogger(const std::string& identity) { + base::threading::ScopedLock scopedLock(ELPP->lock()); + return ELPP->registeredLoggers()->has(identity); + } + /// @brief Reconfigures specified logger with new configurations + static inline Logger* reconfigureLogger(Logger* logger, const Configurations& configurations) { + if (!logger) return nullptr; + logger->configure(configurations); + return logger; + } + /// @brief Reconfigures logger with new configurations after looking it up using identity + static inline Logger* reconfigureLogger(const std::string& identity, const Configurations& configurations) { + return Loggers::reconfigureLogger(Loggers::getLogger(identity), configurations); + } + /// @brief Reconfigures logger's single configuration + static inline Logger* reconfigureLogger(const std::string& identity, ConfigurationType configurationType, + const std::string& value) { + Logger* logger = Loggers::getLogger(identity); + if (logger == nullptr) { + return nullptr; + } + logger->configurations()->set(Level::Global, configurationType, value); + logger->reconfigure(); + return logger; + } + /// @brief Reconfigures all the existing loggers with new configurations + static inline void reconfigureAllLoggers(const Configurations& configurations) { + for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin(); + it != ELPP->registeredLoggers()->end(); ++it) { + Loggers::reconfigureLogger(it->second, configurations); + } + } + /// @brief Reconfigures single configuration for all the loggers + static inline void reconfigureAllLoggers(ConfigurationType configurationType, const std::string& value) { + reconfigureAllLoggers(Level::Global, configurationType, value); + } + /// @brief Reconfigures single configuration for all the loggers for specified level + static inline void reconfigureAllLoggers(Level level, ConfigurationType configurationType, + const std::string& value) { + for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin(); + it != ELPP->registeredLoggers()->end(); ++it) { + Logger* logger = it->second; + logger->configurations()->set(level, configurationType, value); + logger->reconfigure(); + } + } + /// @brief Sets default configurations. This configuration is used for future (and conditionally for existing) loggers + static inline void setDefaultConfigurations(const Configurations& configurations, bool reconfigureExistingLoggers = false) { + ELPP->registeredLoggers()->setDefaultConfigurations(configurations); + if (reconfigureExistingLoggers) { + Loggers::reconfigureAllLoggers(configurations); + } + } + /// @brief Returns current default + static inline const Configurations* defaultConfigurations(void) { + return ELPP->registeredLoggers()->defaultConfigurations(); + } + /// @brief Returns log stream reference pointer if needed by user + static inline const base::LogStreamsReferenceMap* logStreamsReference(void) { + return ELPP->registeredLoggers()->logStreamsReference(); + } + /// @brief Default typed configuration based on existing defaultConf + static base::TypedConfigurations defaultTypedConfigurations(void) { + return base::TypedConfigurations( + ELPP->registeredLoggers()->defaultConfigurations(), + ELPP->registeredLoggers()->logStreamsReference()); + } + /// @brief Populates all logger IDs in current repository. + /// @param [out] targetList List of fill up. + static inline std::vector* populateAllLoggerIds(std::vector* targetList) { + targetList->clear(); + for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->list().begin(); + it != ELPP->registeredLoggers()->list().end(); ++it) { + targetList->push_back(it->first); + } + return targetList; + } + /// @brief Sets configurations from global configuration file. + static void configureFromGlobal(const char* globalConfigurationFilePath) { + std::ifstream gcfStream(globalConfigurationFilePath, std::ifstream::in); + ELPP_ASSERT(gcfStream.is_open(), "Unable to open global configuration file [" << globalConfigurationFilePath + << "] for parsing."); + std::string line = std::string(); + std::stringstream ss; + Logger* logger = nullptr; + auto configure = [&](void) { + ELPP_INTERNAL_INFO(8, "Configuring logger: '" << logger->id() << "' with configurations \n" << ss.str() + << "\n--------------"); + Configurations c; + c.parseFromText(ss.str()); + logger->configure(c); + }; + while (gcfStream.good()) { + std::getline(gcfStream, line); + ELPP_INTERNAL_INFO(1, "Parsing line: " << line); + base::utils::Str::trim(line); + if (Configurations::Parser::isComment(line)) continue; + Configurations::Parser::ignoreComments(&line); + base::utils::Str::trim(line); + if (line.size() > 2 && base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLoggerId))) { + if (!ss.str().empty() && logger != nullptr) { + configure(); + } + ss.str(std::string("")); + line = line.substr(2); + base::utils::Str::trim(line); + if (line.size() > 1) { + ELPP_INTERNAL_INFO(1, "Getting logger: '" << line << "'"); + logger = getLogger(line); + } + } else { + ss << line << "\n"; + } + } + if (!ss.str().empty() && logger != nullptr) { + configure(); + } + } + /// @brief Configures loggers using command line arg. Ensure you have already set command line args, + /// @return False if invalid argument or argument with no value provided, true if attempted to configure logger. + /// If true is returned that does not mean it has been configured successfully, it only means that it + /// has attempeted to configure logger using configuration file provided in argument + static inline bool configureFromArg(const char* argKey) { +#if defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS) + ELPP_UNUSED(argKey); +#else + if (!Helpers::commandLineArgs()->hasParamWithValue(argKey)) { + return false; + } + configureFromGlobal(Helpers::commandLineArgs()->getParamValue(argKey)); +#endif // defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS) + return true; + } + /// @brief Flushes all loggers for all levels - Be careful if you dont know how many loggers are registered + static inline void flushAll(void) { + ELPP->registeredLoggers()->flushAll(); + } + /// @brief Adds logging flag used internally. + static inline void addFlag(LoggingFlag flag) { + ELPP->addFlag(flag); + } + /// @brief Removes logging flag used internally. + static inline void removeFlag(LoggingFlag flag) { + ELPP->removeFlag(flag); + } + /// @brief Determines whether or not certain flag is active + static inline bool hasFlag(LoggingFlag flag) { + return ELPP->hasFlag(flag); + } + /// @brief Adds flag and removes it when scope goes out + class ScopedAddFlag { + public: + ScopedAddFlag(LoggingFlag flag) : m_flag(flag) { Loggers::addFlag(m_flag); } + ~ScopedAddFlag(void) { Loggers::removeFlag(m_flag); } + private: + LoggingFlag m_flag; + }; + /// @brief Removes flag and add it when scope goes out + class ScopedRemoveFlag { + public: + ScopedRemoveFlag(LoggingFlag flag) : m_flag(flag) { Loggers::removeFlag(m_flag); } + ~ScopedRemoveFlag(void) { Loggers::addFlag(m_flag); } + private: + LoggingFlag m_flag; + }; + /// @brief Sets hierarchy for logging. Needs to enable logging flag (HierarchicalLogging) + static inline void setLoggingLevel(Level level) { + ELPP->setLoggingLevel(level); + } + /// @brief Sets verbose level on the fly + static inline void setVerboseLevel(base::type::VerboseLevel level) { + ELPP->vRegistry()->setLevel(level); + } + /// @brief Gets current verbose level + static inline base::type::VerboseLevel verboseLevel(void) { + return ELPP->vRegistry()->level(); + } + /// @brief Sets vmodules as specified (on the fly) + static inline void setVModules(const char* modules) { + if (ELPP->vRegistry()->vModulesEnabled()) { + ELPP->vRegistry()->setModules(modules); + } + } + /// @brief Clears vmodules + static inline void clearVModules(void) { + ELPP->vRegistry()->clearModules(); + } +}; +class VersionInfo : base::StaticClass { +public: + /// @brief Current version number + static inline const std::string version(void) { return std::string("9.80"); } + /// @brief Release date of current version + static inline const std::string releaseDate(void) { return std::string("08-01-2015 0850hrs"); } +}; +} // namespace el +#undef VLOG_IS_ON +/// @brief Determines whether verbose logging is on for specified level current file. +#define VLOG_IS_ON(verboseLevel) (ELPP->vRegistry()->allowed(verboseLevel, __FILE__)) +#undef TIMED_BLOCK +#undef TIMED_SCOPE +#undef TIMED_FUNC +#undef ELPP_MIN_UNIT +#if defined(ELPP_PERFORMANCE_MICROSECONDS) +# define ELPP_MIN_UNIT el::base::TimestampUnit::Microsecond +#else +# define ELPP_MIN_UNIT el::base::TimestampUnit::Millisecond +#endif // (defined(ELPP_PERFORMANCE_MICROSECONDS)) +/// @brief Performance tracked scope. Performance gets written when goes out of scope using +/// 'performance' logger. +/// +/// @detail Please note in order to check the performance at a certain time you can use obj.checkpoint(); +/// @see el::base::PerformanceTracker +/// @see el::base::PerformanceTracker::checkpoint +// Note: Do not surround this definition with null macro because of obj instance +#define TIMED_SCOPE(obj, blockname) el::base::PerformanceTracker obj(blockname, ELPP_MIN_UNIT) +#define TIMED_BLOCK(obj, blockName) for (struct { int i; el::base::PerformanceTracker timer; } obj = { 0, \ + el::base::PerformanceTracker(blockName, ELPP_MIN_UNIT) }; obj.i < 1; ++obj.i) +/// @brief Performance tracked function. Performance gets written when goes out of scope using +/// 'performance' logger. +/// +/// @detail Please note in order to check the performance at a certain time you can use obj.checkpoint(); +/// @see el::base::PerformanceTracker +/// @see el::base::PerformanceTracker::checkpoint +#define TIMED_FUNC(obj) TIMED_SCOPE(obj, ELPP_FUNC) +#undef PERFORMANCE_CHECKPOINT +#undef PERFORMANCE_CHECKPOINT_WITH_ID +#define PERFORMANCE_CHECKPOINT(obj) obj.checkpoint(std::string(), __FILE__, __LINE__, ELPP_FUNC) +#define PERFORMANCE_CHECKPOINT_WITH_ID(obj, id) obj.checkpoint(id, __FILE__, __LINE__, ELPP_FUNC) +#undef ELPP_COUNTER +#undef ELPP_COUNTER_POS +/// @brief Gets hit counter for file/line +#define ELPP_COUNTER (ELPP->hitCounters()->getCounter(__FILE__, __LINE__)) +/// @brief Gets hit counter position for file/line, -1 if not registered yet +#define ELPP_COUNTER_POS (ELPP_COUNTER == nullptr ? -1 : ELPP_COUNTER->hitCounts()) +// Undef levels to support LOG(LEVEL) +#undef INFO +#undef WARNING +#undef DEBUG +#undef ERROR +#undef FATAL +#undef TRACE +#undef VERBOSE +// Undef existing +#undef CINFO +#undef CWARNING +#undef CDEBUG +#undef CFATAL +#undef CERROR +#undef CTRACE +#undef CVERBOSE +#undef CINFO_IF +#undef CWARNING_IF +#undef CDEBUG_IF +#undef CERROR_IF +#undef CFATAL_IF +#undef CTRACE_IF +#undef CVERBOSE_IF +#undef CINFO_EVERY_N +#undef CWARNING_EVERY_N +#undef CDEBUG_EVERY_N +#undef CERROR_EVERY_N +#undef CFATAL_EVERY_N +#undef CTRACE_EVERY_N +#undef CVERBOSE_EVERY_N +#undef CINFO_AFTER_N +#undef CWARNING_AFTER_N +#undef CDEBUG_AFTER_N +#undef CERROR_AFTER_N +#undef CFATAL_AFTER_N +#undef CTRACE_AFTER_N +#undef CVERBOSE_AFTER_N +#undef CINFO_N_TIMES +#undef CWARNING_N_TIMES +#undef CDEBUG_N_TIMES +#undef CERROR_N_TIMES +#undef CFATAL_N_TIMES +#undef CTRACE_N_TIMES +#undef CVERBOSE_N_TIMES +// Normal logs +#if ELPP_INFO_LOG +# define CINFO(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Info, dispatchAction, __VA_ARGS__) +#else +# define CINFO(writer, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_INFO_LOG +#if ELPP_WARNING_LOG +# define CWARNING(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Warning, dispatchAction, __VA_ARGS__) +#else +# define CWARNING(writer, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_WARNING_LOG +#if ELPP_DEBUG_LOG +# define CDEBUG(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Debug, dispatchAction, __VA_ARGS__) +#else +# define CDEBUG(writer, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_DEBUG_LOG +#if ELPP_ERROR_LOG +# define CERROR(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Error, dispatchAction, __VA_ARGS__) +#else +# define CERROR(writer, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_ERROR_LOG +#if ELPP_FATAL_LOG +# define CFATAL(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Fatal, dispatchAction, __VA_ARGS__) +#else +# define CFATAL(writer, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_FATAL_LOG +#if ELPP_TRACE_LOG +# define CTRACE(writer, dispatchAction, ...) ELPP_WRITE_LOG(writer, el::Level::Trace, dispatchAction, __VA_ARGS__) +#else +# define CTRACE(writer, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_TRACE_LOG +#if ELPP_VERBOSE_LOG +# define CVERBOSE(writer, vlevel, dispatchAction, ...) if (VLOG_IS_ON(vlevel)) writer(\ + el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) +#else +# define CVERBOSE(writer, vlevel, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_VERBOSE_LOG +// Conditional logs +#if ELPP_INFO_LOG +# define CINFO_IF(writer, condition_, dispatchAction, ...) \ + ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Info, dispatchAction, __VA_ARGS__) +#else +# define CINFO_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_INFO_LOG +#if ELPP_WARNING_LOG +# define CWARNING_IF(writer, condition_, dispatchAction, ...)\ + ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Warning, dispatchAction, __VA_ARGS__) +#else +# define CWARNING_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_WARNING_LOG +#if ELPP_DEBUG_LOG +# define CDEBUG_IF(writer, condition_, dispatchAction, ...)\ + ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Debug, dispatchAction, __VA_ARGS__) +#else +# define CDEBUG_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_DEBUG_LOG +#if ELPP_ERROR_LOG +# define CERROR_IF(writer, condition_, dispatchAction, ...)\ + ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Error, dispatchAction, __VA_ARGS__) +#else +# define CERROR_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_ERROR_LOG +#if ELPP_FATAL_LOG +# define CFATAL_IF(writer, condition_, dispatchAction, ...)\ + ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Fatal, dispatchAction, __VA_ARGS__) +#else +# define CFATAL_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_FATAL_LOG +#if ELPP_TRACE_LOG +# define CTRACE_IF(writer, condition_, dispatchAction, ...)\ + ELPP_WRITE_LOG_IF(writer, (condition_), el::Level::Trace, dispatchAction, __VA_ARGS__) +#else +# define CTRACE_IF(writer, condition_, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_TRACE_LOG +#if ELPP_VERBOSE_LOG +# define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) if (VLOG_IS_ON(vlevel) && (condition_)) writer( \ + el::Level::Verbose, __FILE__, __LINE__, ELPP_FUNC, dispatchAction, vlevel).construct(el_getVALength(__VA_ARGS__), __VA_ARGS__) +#else +# define CVERBOSE_IF(writer, condition_, vlevel, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_VERBOSE_LOG +// Occasional logs +#if ELPP_INFO_LOG +# define CINFO_EVERY_N(writer, occasion, dispatchAction, ...)\ + ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Info, dispatchAction, __VA_ARGS__) +#else +# define CINFO_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_INFO_LOG +#if ELPP_WARNING_LOG +# define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...)\ + ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Warning, dispatchAction, __VA_ARGS__) +#else +# define CWARNING_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_WARNING_LOG +#if ELPP_DEBUG_LOG +# define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...)\ + ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Debug, dispatchAction, __VA_ARGS__) +#else +# define CDEBUG_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_DEBUG_LOG +#if ELPP_ERROR_LOG +# define CERROR_EVERY_N(writer, occasion, dispatchAction, ...)\ + ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Error, dispatchAction, __VA_ARGS__) +#else +# define CERROR_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_ERROR_LOG +#if ELPP_FATAL_LOG +# define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...)\ + ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Fatal, dispatchAction, __VA_ARGS__) +#else +# define CFATAL_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_FATAL_LOG +#if ELPP_TRACE_LOG +# define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...)\ + ELPP_WRITE_LOG_EVERY_N(writer, occasion, el::Level::Trace, dispatchAction, __VA_ARGS__) +#else +# define CTRACE_EVERY_N(writer, occasion, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_TRACE_LOG +#if ELPP_VERBOSE_LOG +# define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...)\ + CVERBOSE_IF(writer, ELPP->validateEveryNCounter(__FILE__, __LINE__, occasion), vlevel, dispatchAction, __VA_ARGS__) +#else +# define CVERBOSE_EVERY_N(writer, occasion, vlevel, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_VERBOSE_LOG +// After N logs +#if ELPP_INFO_LOG +# define CINFO_AFTER_N(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__) +#else +# define CINFO_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_INFO_LOG +#if ELPP_WARNING_LOG +# define CWARNING_AFTER_N(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__) +#else +# define CWARNING_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_WARNING_LOG +#if ELPP_DEBUG_LOG +# define CDEBUG_AFTER_N(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__) +#else +# define CDEBUG_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_DEBUG_LOG +#if ELPP_ERROR_LOG +# define CERROR_AFTER_N(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__) +#else +# define CERROR_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_ERROR_LOG +#if ELPP_FATAL_LOG +# define CFATAL_AFTER_N(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__) +#else +# define CFATAL_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_FATAL_LOG +#if ELPP_TRACE_LOG +# define CTRACE_AFTER_N(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_AFTER_N(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__) +#else +# define CTRACE_AFTER_N(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_TRACE_LOG +#if ELPP_VERBOSE_LOG +# define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...)\ + CVERBOSE_IF(writer, ELPP->validateAfterNCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__) +#else +# define CVERBOSE_AFTER_N(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_VERBOSE_LOG +// N Times logs +#if ELPP_INFO_LOG +# define CINFO_N_TIMES(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Info, dispatchAction, __VA_ARGS__) +#else +# define CINFO_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_INFO_LOG +#if ELPP_WARNING_LOG +# define CWARNING_N_TIMES(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Warning, dispatchAction, __VA_ARGS__) +#else +# define CWARNING_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_WARNING_LOG +#if ELPP_DEBUG_LOG +# define CDEBUG_N_TIMES(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Debug, dispatchAction, __VA_ARGS__) +#else +# define CDEBUG_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_DEBUG_LOG +#if ELPP_ERROR_LOG +# define CERROR_N_TIMES(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Error, dispatchAction, __VA_ARGS__) +#else +# define CERROR_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_ERROR_LOG +#if ELPP_FATAL_LOG +# define CFATAL_N_TIMES(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Fatal, dispatchAction, __VA_ARGS__) +#else +# define CFATAL_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_FATAL_LOG +#if ELPP_TRACE_LOG +# define CTRACE_N_TIMES(writer, n, dispatchAction, ...)\ + ELPP_WRITE_LOG_N_TIMES(writer, n, el::Level::Trace, dispatchAction, __VA_ARGS__) +#else +# define CTRACE_N_TIMES(writer, n, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_TRACE_LOG +#if ELPP_VERBOSE_LOG +# define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...)\ + CVERBOSE_IF(writer, ELPP->validateNTimesCounter(__FILE__, __LINE__, n), vlevel, dispatchAction, __VA_ARGS__) +#else +# define CVERBOSE_N_TIMES(writer, n, vlevel, dispatchAction, ...) el::base::NullWriter() +#endif // ELPP_VERBOSE_LOG +// +// Custom Loggers - Requires (level, dispatchAction, loggerId/s) +// +// undef existing +#undef CLOG +#undef CLOG_VERBOSE +#undef CVLOG +#undef CLOG_IF +#undef CLOG_VERBOSE_IF +#undef CVLOG_IF +#undef CLOG_EVERY_N +#undef CVLOG_EVERY_N +#undef CLOG_AFTER_N +#undef CVLOG_AFTER_N +#undef CLOG_N_TIMES +#undef CVLOG_N_TIMES +// Normal logs +#define CLOG(LEVEL, ...)\ + C##LEVEL(el::base::Writer, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define CVLOG(vlevel, ...) CVERBOSE(el::base::Writer, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) +// Conditional logs +#define CLOG_IF(condition, LEVEL, ...)\ + C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define CVLOG_IF(condition, vlevel, ...)\ + CVERBOSE_IF(el::base::Writer, condition, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) +// Hit counts based logs +#define CLOG_EVERY_N(n, LEVEL, ...)\ + C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define CVLOG_EVERY_N(n, vlevel, ...)\ + CVERBOSE_EVERY_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define CLOG_AFTER_N(n, LEVEL, ...)\ + C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define CVLOG_AFTER_N(n, vlevel, ...)\ + CVERBOSE_AFTER_N(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define CLOG_N_TIMES(n, LEVEL, ...)\ + C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define CVLOG_N_TIMES(n, vlevel, ...)\ + CVERBOSE_N_TIMES(el::base::Writer, n, vlevel, el::base::DispatchAction::NormalLog, __VA_ARGS__) +// +// Default Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros +// +// undef existing +#undef LOG +#undef VLOG +#undef LOG_IF +#undef VLOG_IF +#undef LOG_EVERY_N +#undef VLOG_EVERY_N +#undef LOG_AFTER_N +#undef VLOG_AFTER_N +#undef LOG_N_TIMES +#undef VLOG_N_TIMES +#undef ELPP_CURR_FILE_LOGGER_ID +#if defined(ELPP_DEFAULT_LOGGER) +# define ELPP_CURR_FILE_LOGGER_ID ELPP_DEFAULT_LOGGER +#else +# define ELPP_CURR_FILE_LOGGER_ID el::base::consts::kDefaultLoggerId +#endif +#undef ELPP_TRACE +#define ELPP_TRACE CLOG(TRACE, ELPP_CURR_FILE_LOGGER_ID) +// Normal logs +#define LOG(LEVEL) CLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define VLOG(vlevel) CVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID) +// Conditional logs +#define LOG_IF(condition, LEVEL) CLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define VLOG_IF(condition, vlevel) CVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID) +// Hit counts based logs +#define LOG_EVERY_N(n, LEVEL) CLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define VLOG_EVERY_N(n, vlevel) CVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) +#define LOG_AFTER_N(n, LEVEL) CLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define VLOG_AFTER_N(n, vlevel) CVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) +#define LOG_N_TIMES(n, LEVEL) CLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define VLOG_N_TIMES(n, vlevel) CVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) +// Generic PLOG() +#undef CPLOG +#undef CPLOG_IF +#undef PLOG +#undef PLOG_IF +#undef DCPLOG +#undef DCPLOG_IF +#undef DPLOG +#undef DPLOG_IF +#define CPLOG(LEVEL, ...)\ + C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define CPLOG_IF(condition, LEVEL, ...)\ + C##LEVEL##_IF(el::base::PErrorWriter, condition, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define DCPLOG(LEVEL, ...)\ + if (ELPP_DEBUG_LOG) C##LEVEL(el::base::PErrorWriter, el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define DCPLOG_IF(condition, LEVEL, ...)\ + C##LEVEL##_IF(el::base::PErrorWriter, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::NormalLog, __VA_ARGS__) +#define PLOG(LEVEL) CPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define PLOG_IF(condition, LEVEL) CPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define DPLOG(LEVEL) DCPLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define DPLOG_IF(condition, LEVEL) DCPLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +// Generic SYSLOG() +#undef CSYSLOG +#undef CSYSLOG_IF +#undef CSYSLOG_EVERY_N +#undef CSYSLOG_AFTER_N +#undef CSYSLOG_N_TIMES +#undef SYSLOG +#undef SYSLOG_IF +#undef SYSLOG_EVERY_N +#undef SYSLOG_AFTER_N +#undef SYSLOG_N_TIMES +#undef DCSYSLOG +#undef DCSYSLOG_IF +#undef DCSYSLOG_EVERY_N +#undef DCSYSLOG_AFTER_N +#undef DCSYSLOG_N_TIMES +#undef DSYSLOG +#undef DSYSLOG_IF +#undef DSYSLOG_EVERY_N +#undef DSYSLOG_AFTER_N +#undef DSYSLOG_N_TIMES +#if defined(ELPP_SYSLOG) +# define CSYSLOG(LEVEL, ...)\ + C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define CSYSLOG_IF(condition, LEVEL, ...)\ + C##LEVEL##_IF(el::base::Writer, condition, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define CSYSLOG_EVERY_N(n, LEVEL, ...) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define CSYSLOG_AFTER_N(n, LEVEL, ...) C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define CSYSLOG_N_TIMES(n, LEVEL, ...) C##LEVEL##_N_TIMES(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define SYSLOG(LEVEL) CSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId) +# define SYSLOG_IF(condition, LEVEL) CSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId) +# define SYSLOG_EVERY_N(n, LEVEL) CSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId) +# define SYSLOG_AFTER_N(n, LEVEL) CSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId) +# define SYSLOG_N_TIMES(n, LEVEL) CSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId) +# define DCSYSLOG(LEVEL, ...) if (ELPP_DEBUG_LOG) C##LEVEL(el::base::Writer, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define DCSYSLOG_IF(condition, LEVEL, ...)\ + C##LEVEL##_IF(el::base::Writer, (ELPP_DEBUG_LOG) && (condition), el::base::DispatchAction::SysLog, __VA_ARGS__) +# define DCSYSLOG_EVERY_N(n, LEVEL, ...)\ + if (ELPP_DEBUG_LOG) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define DCSYSLOG_AFTER_N(n, LEVEL, ...)\ + if (ELPP_DEBUG_LOG) C##LEVEL##_AFTER_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define DCSYSLOG_N_TIMES(n, LEVEL, ...)\ + if (ELPP_DEBUG_LOG) C##LEVEL##_EVERY_N(el::base::Writer, n, el::base::DispatchAction::SysLog, __VA_ARGS__) +# define DSYSLOG(LEVEL) DCSYSLOG(LEVEL, el::base::consts::kSysLogLoggerId) +# define DSYSLOG_IF(condition, LEVEL) DCSYSLOG_IF(condition, LEVEL, el::base::consts::kSysLogLoggerId) +# define DSYSLOG_EVERY_N(n, LEVEL) DCSYSLOG_EVERY_N(n, LEVEL, el::base::consts::kSysLogLoggerId) +# define DSYSLOG_AFTER_N(n, LEVEL) DCSYSLOG_AFTER_N(n, LEVEL, el::base::consts::kSysLogLoggerId) +# define DSYSLOG_N_TIMES(n, LEVEL) DCSYSLOG_N_TIMES(n, LEVEL, el::base::consts::kSysLogLoggerId) +#else +# define CSYSLOG(LEVEL, ...) el::base::NullWriter() +# define CSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter() +# define CSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter() +# define CSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter() +# define CSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter() +# define SYSLOG(LEVEL) el::base::NullWriter() +# define SYSLOG_IF(condition, LEVEL) el::base::NullWriter() +# define SYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter() +# define SYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter() +# define SYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter() +# define DCSYSLOG(LEVEL, ...) el::base::NullWriter() +# define DCSYSLOG_IF(condition, LEVEL, ...) el::base::NullWriter() +# define DCSYSLOG_EVERY_N(n, LEVEL, ...) el::base::NullWriter() +# define DCSYSLOG_AFTER_N(n, LEVEL, ...) el::base::NullWriter() +# define DCSYSLOG_N_TIMES(n, LEVEL, ...) el::base::NullWriter() +# define DSYSLOG(LEVEL) el::base::NullWriter() +# define DSYSLOG_IF(condition, LEVEL) el::base::NullWriter() +# define DSYSLOG_EVERY_N(n, LEVEL) el::base::NullWriter() +# define DSYSLOG_AFTER_N(n, LEVEL) el::base::NullWriter() +# define DSYSLOG_N_TIMES(n, LEVEL) el::base::NullWriter() +#endif // defined(ELPP_SYSLOG) +// +// Custom Debug Only Loggers - Requires (level, loggerId/s) +// +// undef existing +#undef DCLOG +#undef DCVLOG +#undef DCLOG_IF +#undef DCVLOG_IF +#undef DCLOG_EVERY_N +#undef DCVLOG_EVERY_N +#undef DCLOG_AFTER_N +#undef DCVLOG_AFTER_N +#undef DCLOG_N_TIMES +#undef DCVLOG_N_TIMES +// Normal logs +#define DCLOG(LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG(LEVEL, __VA_ARGS__) +#define DCLOG_VERBOSE(vlevel, ...) if (ELPP_DEBUG_LOG) CLOG_VERBOSE(vlevel, __VA_ARGS__) +#define DCVLOG(vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG(vlevel, __VA_ARGS__) +// Conditional logs +#define DCLOG_IF(condition, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_IF(condition, LEVEL, __VA_ARGS__) +#define DCVLOG_IF(condition, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_IF(condition, vlevel, __VA_ARGS__) +// Hit counts based logs +#define DCLOG_EVERY_N(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_EVERY_N(n, LEVEL, __VA_ARGS__) +#define DCVLOG_EVERY_N(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_EVERY_N(n, vlevel, __VA_ARGS__) +#define DCLOG_AFTER_N(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_AFTER_N(n, LEVEL, __VA_ARGS__) +#define DCVLOG_AFTER_N(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_AFTER_N(n, vlevel, __VA_ARGS__) +#define DCLOG_N_TIMES(n, LEVEL, ...) if (ELPP_DEBUG_LOG) CLOG_N_TIMES(n, LEVEL, __VA_ARGS__) +#define DCVLOG_N_TIMES(n, vlevel, ...) if (ELPP_DEBUG_LOG) CVLOG_N_TIMES(n, vlevel, __VA_ARGS__) +// +// Default Debug Only Loggers macro using CLOG(), CLOG_VERBOSE() and CVLOG() macros +// +// undef existing +#undef DLOG +#undef DVLOG +#undef DLOG_IF +#undef DVLOG_IF +#undef DLOG_EVERY_N +#undef DVLOG_EVERY_N +#undef DLOG_AFTER_N +#undef DVLOG_AFTER_N +#undef DLOG_N_TIMES +#undef DVLOG_N_TIMES +// Normal logs +#define DLOG(LEVEL) DCLOG(LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define DVLOG(vlevel) DCVLOG(vlevel, ELPP_CURR_FILE_LOGGER_ID) +// Conditional logs +#define DLOG_IF(condition, LEVEL) DCLOG_IF(condition, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define DVLOG_IF(condition, vlevel) DCVLOG_IF(condition, vlevel, ELPP_CURR_FILE_LOGGER_ID) +// Hit counts based logs +#define DLOG_EVERY_N(n, LEVEL) DCLOG_EVERY_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define DVLOG_EVERY_N(n, vlevel) DCVLOG_EVERY_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) +#define DLOG_AFTER_N(n, LEVEL) DCLOG_AFTER_N(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define DVLOG_AFTER_N(n, vlevel) DCVLOG_AFTER_N(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) +#define DLOG_N_TIMES(n, LEVEL) DCLOG_N_TIMES(n, LEVEL, ELPP_CURR_FILE_LOGGER_ID) +#define DVLOG_N_TIMES(n, vlevel) DCVLOG_N_TIMES(n, vlevel, ELPP_CURR_FILE_LOGGER_ID) +// Check macros +#undef CCHECK +#undef CPCHECK +#undef CCHECK_EQ +#undef CCHECK_NE +#undef CCHECK_LT +#undef CCHECK_GT +#undef CCHECK_LE +#undef CCHECK_GE +#undef CCHECK_BOUNDS +#undef CCHECK_NOTNULL +#undef CCHECK_STRCASEEQ +#undef CCHECK_STRCASENE +#undef CHECK +#undef PCHECK +#undef CHECK_EQ +#undef CHECK_NE +#undef CHECK_LT +#undef CHECK_GT +#undef CHECK_LE +#undef CHECK_GE +#undef CHECK_BOUNDS +#undef CHECK_NOTNULL +#undef CHECK_STRCASEEQ +#undef CHECK_STRCASENE +#define CCHECK(condition, ...) CLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] " +#define CPCHECK(condition, ...) CPLOG_IF(!(condition), FATAL, __VA_ARGS__) << "Check failed: [" << #condition << "] " +#define CHECK(condition) CCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) +#define PCHECK(condition) CPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) +#define CCHECK_EQ(a, b, ...) CCHECK(a == b, __VA_ARGS__) +#define CCHECK_NE(a, b, ...) CCHECK(a != b, __VA_ARGS__) +#define CCHECK_LT(a, b, ...) CCHECK(a < b, __VA_ARGS__) +#define CCHECK_GT(a, b, ...) CCHECK(a > b, __VA_ARGS__) +#define CCHECK_LE(a, b, ...) CCHECK(a <= b, __VA_ARGS__) +#define CCHECK_GE(a, b, ...) CCHECK(a >= b, __VA_ARGS__) +#define CCHECK_BOUNDS(val, min, max, ...) CCHECK(val >= min && val <= max, __VA_ARGS__) +#define CHECK_EQ(a, b) CCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_NE(a, b) CCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_LT(a, b) CCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_GT(a, b) CCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_LE(a, b) CCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_GE(a, b) CCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_BOUNDS(val, min, max) CCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID) +namespace el { +namespace base { +namespace utils { +template +static T* checkNotNull(T* ptr, const char* name, const char* loggers, ...) { + CLOG_IF(ptr == nullptr, FATAL, loggers) << "Check failed: [" << name << " != nullptr]"; + return ptr; +} +} // namespace utils +} // namespace base +} // namespace el +#define CCHECK_NOTNULL(ptr, ...) el::base::utils::checkNotNull(ptr, #ptr, __VA_ARGS__) +#define CCHECK_STREQ(str1, str2, ...) CLOG_IF(!el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \ + << "Check failed: [" << #str1 << " == " << #str2 << "] " +#define CCHECK_STRNE(str1, str2, ...) CLOG_IF(el::base::utils::Str::cStringEq(str1, str2), FATAL, __VA_ARGS__) \ + << "Check failed: [" << #str1 << " != " << #str2 << "] " +#define CCHECK_STRCASEEQ(str1, str2, ...) CLOG_IF(!el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \ + << "Check failed: [" << #str1 << " == " << #str2 << "] " +#define CCHECK_STRCASENE(str1, str2, ...) CLOG_IF(el::base::utils::Str::cStringCaseEq(str1, str2), FATAL, __VA_ARGS__) \ + << "Check failed: [" << #str1 << " != " << #str2 << "] " +#define CHECK_NOTNULL(ptr) CCHECK_NOTNULL(ptr, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_STREQ(str1, str2) CCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_STRNE(str1, str2) CCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_STRCASEEQ(str1, str2) CCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) +#define CHECK_STRCASENE(str1, str2) CCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) +#undef DCCHECK +#undef DCCHECK_EQ +#undef DCCHECK_NE +#undef DCCHECK_LT +#undef DCCHECK_GT +#undef DCCHECK_LE +#undef DCCHECK_GE +#undef DCCHECK_BOUNDS +#undef DCCHECK_NOTNULL +#undef DCCHECK_STRCASEEQ +#undef DCCHECK_STRCASENE +#undef DCPCHECK +#undef DCHECK +#undef DCHECK_EQ +#undef DCHECK_NE +#undef DCHECK_LT +#undef DCHECK_GT +#undef DCHECK_LE +#undef DCHECK_GE +#undef DCHECK_BOUNDS_ +#undef DCHECK_NOTNULL +#undef DCHECK_STRCASEEQ +#undef DCHECK_STRCASENE +#undef DPCHECK +#define DCCHECK(condition, ...) if (ELPP_DEBUG_LOG) CCHECK(condition, __VA_ARGS__) +#define DCCHECK_EQ(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_EQ(a, b, __VA_ARGS__) +#define DCCHECK_NE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_NE(a, b, __VA_ARGS__) +#define DCCHECK_LT(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_LT(a, b, __VA_ARGS__) +#define DCCHECK_GT(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_GT(a, b, __VA_ARGS__) +#define DCCHECK_LE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_LE(a, b, __VA_ARGS__) +#define DCCHECK_GE(a, b, ...) if (ELPP_DEBUG_LOG) CCHECK_GE(a, b, __VA_ARGS__) +#define DCCHECK_BOUNDS(val, min, max, ...) if (ELPP_DEBUG_LOG) CCHECK_BOUNDS(val, min, max, __VA_ARGS__) +#define DCCHECK_NOTNULL(ptr, ...) if (ELPP_DEBUG_LOG) CCHECK_NOTNULL(ptr, __VA_ARGS__) +#define DCCHECK_STREQ(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STREQ(str1, str2, __VA_ARGS__) +#define DCCHECK_STRNE(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRNE(str1, str2, __VA_ARGS__) +#define DCCHECK_STRCASEEQ(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRCASEEQ(str1, str2, __VA_ARGS__) +#define DCCHECK_STRCASENE(str1, str2, ...) if (ELPP_DEBUG_LOG) CCHECK_STRCASENE(str1, str2, __VA_ARGS__) +#define DCPCHECK(condition, ...) if (ELPP_DEBUG_LOG) CPCHECK(condition, __VA_ARGS__) +#define DCHECK(condition) DCCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_EQ(a, b) DCCHECK_EQ(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_NE(a, b) DCCHECK_NE(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_LT(a, b) DCCHECK_LT(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_GT(a, b) DCCHECK_GT(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_LE(a, b) DCCHECK_LE(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_GE(a, b) DCCHECK_GE(a, b, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_BOUNDS(val, min, max) DCCHECK_BOUNDS(val, min, max, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_NOTNULL(ptr) DCCHECK_NOTNULL(ptr, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_STREQ(str1, str2) DCCHECK_STREQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_STRNE(str1, str2) DCCHECK_STRNE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_STRCASEEQ(str1, str2) DCCHECK_STRCASEEQ(str1, str2, ELPP_CURR_FILE_LOGGER_ID) +#define DCHECK_STRCASENE(str1, str2) DCCHECK_STRCASENE(str1, str2, ELPP_CURR_FILE_LOGGER_ID) +#define DPCHECK(condition) DCPCHECK(condition, ELPP_CURR_FILE_LOGGER_ID) +#if defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING) +# define ELPP_USE_DEF_CRASH_HANDLER false +#else +# define ELPP_USE_DEF_CRASH_HANDLER true +#endif // defined(ELPP_DISABLE_DEFAULT_CRASH_HANDLING) +#define ELPP_CRASH_HANDLER_INIT +#define ELPP_INIT_EASYLOGGINGPP(val)\ + ELPP_INITI_BASIC_DECLR\ + namespace el {\ + namespace base {\ + el::base::type::StoragePointer elStorage(val);\ + }\ + el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\ + } + +#if ELPP_ASYNC_LOGGING +# define INITIALIZE_EASYLOGGINGPP\ + ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()),\ + new el::base::AsyncDispatchWorker()))\ + +#else +# define INITIALIZE_EASYLOGGINGPP\ + ELPP_INIT_EASYLOGGINGPP(new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()))) +#endif // ELPP_ASYNC_LOGGING +#define INITIALIZE_NULL_EASYLOGGINGPP\ + ELPP_INITI_BASIC_DECLR\ + namespace el {\ + namespace base {\ + el::base::type::StoragePointer elStorage;\ + }\ + el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\ + } +// NOTE: no ELPP_INITI_BASIC_DECLR when sharing - causes double free corruption on external symbols +#define SHARE_EASYLOGGINGPP(initializedStorage)\ + namespace el {\ + namespace base {\ + el::base::type::StoragePointer elStorage(initializedStorage);\ + }\ + el::base::debug::CrashHandler elCrashHandler(ELPP_USE_DEF_CRASH_HANDLER);\ + } + +#if defined(ELPP_UNICODE) +# define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv); std::locale::global(std::locale("")) +#else +# define START_EASYLOGGINGPP(argc, argv) el::Helpers::setArgs(argc, argv) +#endif // defined(ELPP_UNICODE) +#endif // EASYLOGGINGPP_H diff --git a/extras/init_database.sql b/extras/init_database.sql new file mode 100644 index 0000000..a98b064 --- /dev/null +++ b/extras/init_database.sql @@ -0,0 +1,73 @@ +CREATE TABLE avatar (id INTEGER PRIMARY KEY, + user_id INTEGER, + name TEXT, + address TEXT, + attributes INTEGER, + UNIQUE(name, address)); + +CREATE TABLE room (id INTEGER PRIMARY KEY, + creator_id INTEGER, + creator_name TEXT, + creator_address TEXT, + room_name TEXT, + room_topic TEXT, + room_password TEXT, + room_prefix TEXT, + room_address TEXT, + room_attributes INTEGER, + room_max_size INTEGER, + room_message_id INTEGER, + created_at INTEGER, + node_level INTEGER, + UNIQUE(room_name, room_address), + FOREIGN KEY(creator_id) REFERENCES avatar(id)); + +CREATE TABLE room_administrator (admin_avatar_id INTEGER, + room_id INTEGER, + PRIMARY KEY(admin_avatar_id, room_id), + FOREIGN KEY(admin_avatar_id) REFERENCES avatar(id) ON DELETE CASCADE, + FOREIGN KEY(room_id) REFERENCES room(id) ON DELETE CASCADE); + +CREATE TABLE room_moderator (moderator_avatar_id INTEGER, + room_id INTEGER, + PRIMARY KEY(moderator_avatar_id, room_id), + FOREIGN KEY(moderator_avatar_id) REFERENCES avatar(id) ON DELETE CASCADE, + FOREIGN KEY(room_id) REFERENCES room(id) ON DELETE CASCADE); + +CREATE TABLE room_ban (banned_avatar_id INTEGER, + room_id INTEGER, + PRIMARY KEY(banned_avatar_id, room_id), + FOREIGN KEY(banned_avatar_id) REFERENCES avatar(id) ON DELETE CASCADE, + FOREIGN KEY(room_id) REFERENCES room(id) ON DELETE CASCADE); + +CREATE TABLE room_invite (invited_avatar_id INTEGER, + room_id INTEGER, + PRIMARY KEY(invited_avatar_id, room_id), + FOREIGN KEY(invited_avatar_id) REFERENCES avatar(id) ON DELETE CASCADE, + FOREIGN KEY(room_id) REFERENCES room(id) ON DELETE CASCADE); + +CREATE TABLE persistent_message (id INTEGER PRIMARY KEY, + avatar_id INTEGER, + from_name TEXT, + from_address TEXT, + subject TEXT, + sent_time INTEGER, + status INTEGER, + folder TEXT, + category TEXT, + message TEXT, + oob BLOB, + FOREIGN KEY(avatar_id) REFERENCES avatar(id) ON DELETE CASCADE); + +CREATE TABLE friend (avatar_id INTEGER, + friend_avatar_id INTEGER, + comment TEXT, + PRIMARY KEY(avatar_id, friend_avatar_id), + FOREIGN KEY(avatar_id) REFERENCES avatar(id) ON DELETE CASCADE, + FOREIGN KEY(friend_avatar_id) REFERENCES avatar(id) ON DELETE CASCADE); + +CREATE TABLE ignore (avatar_id INTEGER, + ignore_avatar_id INTEGER, + PRIMARY KEY(avatar_id, ignore_avatar_id) + FOREIGN KEY(avatar_id) REFERENCES avatar(id) ON DELETE CASCADE, + FOREIGN KEY(ignore_avatar_id) REFERENCES avatar(id) ON DELETE CASCADE); diff --git a/extras/logger.cfg.dist b/extras/logger.cfg.dist new file mode 100644 index 0000000..75648b9 --- /dev/null +++ b/extras/logger.cfg.dist @@ -0,0 +1,18 @@ +* GLOBAL: + FILENAME = "logs/swgchat.log" + TO_STANDARD_OUTPUT = true +* TRACE: + FILENAME = "logs/swgchat.log" +* DEBUG: + FILENAME = "logs/swgchat.log" +* FATAL: + FILENAME = "logs/swgchat.log" +* ERROR: + FILENAME = "logs/swgchat.log" +* WARNING: + FILENAME = "logs/swgchat.log" +* INFO: + FILENAME = "logs/swgchat.log" +* VERBOSE: + FILENAME = "logs/verbose.%datetime{%Y%M%d_%H%m%s}.log" + TO_STANDARD_OUTPUT = false diff --git a/extras/swgchat.cfg.dist b/extras/swgchat.cfg.dist new file mode 100644 index 0000000..f9215ef --- /dev/null +++ b/extras/swgchat.cfg.dist @@ -0,0 +1,14 @@ +# Address that the gateway server will listen for connections on +gateway_address = 127.0.0.1 + +# Port the gateway server will listen for connections on +gateway_port = 5001 + +# Address that the registrar server will listen for connections on +registrar_address = 127.0.0.1 + +# Port the registrar server will listen for connections on +registrar_port = 5000 + +# Path to the application database +database_path = chat.db diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..df6e72c --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,132 @@ +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/externals/easyloggingpp + ${Boost_INCLUDE_DIRS} + ${SQLite3_INCLUDE_DIR}) + +if(HAVE_UDPLIBRARY) + include_directories(${PROJECT_SOURCE_DIR}/externals/udplibrary) +endif() + +set(SOURCES + protocol/AddBan.cpp + protocol/AddBan.hpp + protocol/AddFriend.cpp + protocol/AddFriend.hpp + protocol/AddIgnore.cpp + protocol/AddIgnore.hpp + protocol/AddInvite.cpp + protocol/AddInvite.hpp + protocol/AddModerator.cpp + protocol/AddModerator.hpp + protocol/CreateRoom.cpp + protocol/CreateRoom.hpp + protocol/DestroyAvatar.cpp + protocol/DestroyAvatar.hpp + protocol/DestroyRoom.cpp + protocol/DestroyRoom.hpp + protocol/EnterRoom.cpp + protocol/EnterRoom.hpp + protocol/FailoverReLoginAvatar.cpp + protocol/FailoverReLoginAvatar.hpp + protocol/FriendStatus.cpp + protocol/FriendStatus.hpp + protocol/GetAnyAvatar.cpp + protocol/GetAnyAvatar.hpp + protocol/GetPersistentHeaders.cpp + protocol/GetPersistentHeaders.hpp + protocol/GetPersistentMessage.cpp + protocol/GetPersistentMessage.hpp + protocol/GetRoom.cpp + protocol/GetRoom.hpp + protocol/GetRoomSummaries.cpp + protocol/GetRoomSummaries.hpp + protocol/IgnoreStatus.cpp + protocol/IgnoreStatus.hpp + protocol/KickAvatar.cpp + protocol/KickAvatar.hpp + protocol/LeaveRoom.cpp + protocol/LeaveRoom.hpp + protocol/LoginAvatar.cpp + protocol/LoginAvatar.hpp + protocol/LogoutAvatar.cpp + protocol/LogoutAvatar.hpp + protocol/RegistrarGetChatServer.cpp + protocol/RegistrarGetChatServer.hpp + protocol/RemoveBan.cpp + protocol/RemoveBan.hpp + protocol/RemoveFriend.cpp + protocol/RemoveFriend.hpp + protocol/RemoveIgnore.cpp + protocol/RemoveIgnore.hpp + protocol/RemoveInvite.cpp + protocol/RemoveInvite.hpp + protocol/RemoveModerator.cpp + protocol/RemoveModerator.hpp + protocol/SendInstantMessage.cpp + protocol/SendInstantMessage.hpp + protocol/SendPersistentMessage.cpp + protocol/SendPersistentMessage.hpp + protocol/SendRoomMessage.cpp + protocol/SendRoomMessage.hpp + protocol/SetApiVersion.cpp + protocol/SetApiVersion.hpp + protocol/SetAvatarAttributes.cpp + protocol/SetAvatarAttributes.hpp + protocol/UpdatePersistentMessage.cpp + protocol/UpdatePersistentMessage.hpp + + ChatAvatar.cpp + ChatAvatar.hpp + ChatAvatarService.cpp + ChatAvatarService.hpp + ChatEnums.cpp + ChatEnums.hpp + ChatRoom.cpp + ChatRoom.hpp + ChatRoomService.cpp + ChatRoomService.hpp + GatewayClient.cpp + GatewayClient.hpp + GatewayNode.cpp + GatewayNode.hpp + Message.hpp + Node.hpp + NodeClient.cpp + NodeClient.hpp + PersistentMessage.hpp + PersistentMessageService.cpp + PersistentMessageService.hpp + RegistrarClient.cpp + RegistrarClient.hpp + RegistrarNode.cpp + RegistrarNode.hpp + Serialization.hpp + SQLite3.hpp + StreamUtils.cpp + StreamUtils.hpp + StringUtils.cpp + StringUtils.hpp) + +add_library(stationapi ${SOURCES}) + +GroupSourceByFilesystem("${SOURCES}") + +add_executable(stationchat + main.cpp + StationChatApp.cpp + StationChatApp.hpp + StationChatConfig.hpp) + +target_link_libraries(stationchat + stationapi + ${Boost_LIBRARIES} + ${SQLite3_LIBRARY}) + +if (HAVE_UDPLIBRARY) + target_link_libraries(stationchat udplibrary) +endif() + +if(WIN32) + target_link_libraries(stationchat ws2_32) +endif() diff --git a/src/ChatAvatar.cpp b/src/ChatAvatar.cpp new file mode 100644 index 0000000..adb4cc4 --- /dev/null +++ b/src/ChatAvatar.cpp @@ -0,0 +1,107 @@ +#include "ChatAvatar.hpp" +#include "ChatAvatarService.hpp" +#include "ChatRoom.hpp" + +#include + +ChatAvatar::ChatAvatar(ChatAvatarService * avatarService) + : avatarService_{avatarService} {} + +ChatAvatar::ChatAvatar(ChatAvatarService* avatarService, const std::u16string& name, const std::u16string& address, uint32_t userId, + uint32_t attributes, const std::u16string& loginLocation) + : avatarService_{avatarService} + , userId_{userId} + , name_{name} + , address_{address} + , attributes_{attributes} + , loginLocation_{loginLocation} {} + +void ChatAvatar::SetAttributes(const uint32_t attributes) { attributes_ = attributes; } + +void ChatAvatar::AddFriend(ChatAvatar* avatar, const std::u16string& comment) { + if (IsFriend(avatar)) return; + if (IsIgnored(avatar)) RemoveIgnore(avatar); + + friendList_.push_back(FriendContact{avatar, comment}); + + avatarService_->PersistFriend(avatarId_, avatar->avatarId_, comment); +} + +void ChatAvatar::RemoveFriend(const ChatAvatar* avatar) { + auto del_iter = std::remove_if(std::begin(friendList_), std::end(friendList_), + [avatar](auto& frnd) { return frnd.frnd->GetAvatarId() == avatar->GetAvatarId(); }); + + if (del_iter != std::end(friendList_)) { + friendList_.erase(del_iter); + + avatarService_->RemoveFriend(avatarId_, avatar->avatarId_); + } +} + +void ChatAvatar::UpdateFriendComment(const ChatAvatar* avatar, const std::u16string& comment) { + auto find_iter = std::find_if(std::begin(friendList_), std::end(friendList_), + [avatar](auto& frnd) { return frnd.frnd->GetAvatarId() == avatar->GetAvatarId(); }); + + if (find_iter != std::end(friendList_)) { + find_iter->comment = comment; + avatarService_->UpdateFriendComment(avatarId_, avatar->avatarId_, comment); + } +} + +bool ChatAvatar::IsFriend(const ChatAvatar* avatar) { + auto find_iter = std::find_if(std::begin(friendList_), std::end(friendList_), + [avatar](auto& frnd) { return frnd.frnd->GetAvatarId() == avatar->GetAvatarId(); }); + + if (find_iter != std::end(friendList_)) { + return true; + } + + return false; +} + +void ChatAvatar::AddIgnore(ChatAvatar* avatar) { + if (IsIgnored(avatar)) return; + if (IsFriend(avatar)) RemoveFriend(avatar); + + ignoreList_.push_back(IgnoreContact{avatar}); + + avatarService_->PersistIgnore(avatarId_, avatar->avatarId_); +} + +void ChatAvatar::RemoveIgnore(const ChatAvatar* avatar) { + auto del_iter = std::remove_if(std::begin(ignoreList_), std::end(ignoreList_), + [avatar](auto& ignored) { return ignored.ignored->GetAvatarId() == avatar->GetAvatarId(); }); + + if (del_iter != std::end(ignoreList_)) { + ignoreList_.erase(del_iter); + + avatarService_->RemoveIgnore(avatarId_, avatar->avatarId_); + } +} + +bool ChatAvatar::IsIgnored(const ChatAvatar* avatar) { + auto find_iter = std::find_if(std::begin(ignoreList_), std::end(ignoreList_), + [avatar](auto& ignored) { return ignored.ignored->GetAvatarId() == avatar->GetAvatarId(); }); + + if (find_iter != std::end(ignoreList_)) { + return true; + } + + return false; +} + +std::vector ChatAvatar::GetJoinedRooms() { + return rooms_; +} + +void ChatAvatar::JoinRoom(ChatRoom * room) { + rooms_.push_back(room); +} + +void ChatAvatar::UnjoinRoom(ChatRoom * room) { + if (rooms_.empty()) return; + + rooms_.erase(std::remove_if(std::begin(rooms_), std::end(rooms_), [room](const auto joinedRoom) { + return room->GetRoomId() == joinedRoom->GetRoomId(); + })); +} diff --git a/src/ChatAvatar.hpp b/src/ChatAvatar.hpp new file mode 100644 index 0000000..7e6db70 --- /dev/null +++ b/src/ChatAvatar.hpp @@ -0,0 +1,135 @@ + +#pragma once + +#include "Serialization.hpp" + +#include +#include +#include + +class ChatAvatar; +class ChatAvatarService; +class ChatRoom; + +enum class AvatarAttribute : uint32_t { + INVISIBLE = 1 << 0, + GM = 1 << 1, + SUPERGM = 1 << 2, + SUPERSNOOP = 1 << 3, + EXTENDED = 1 << 4 +}; + +struct FriendContact { + FriendContact(const ChatAvatar* frnd_, const std::u16string& comment_) + : frnd{frnd_} + , comment{comment_} {} + + const ChatAvatar* frnd; + std::u16string comment = u""; +}; + +struct IgnoreContact { + IgnoreContact(const ChatAvatar* ignored_) + : ignored{ignored_} {} + + const ChatAvatar* ignored; +}; + +class ChatAvatar { +public: + explicit ChatAvatar(ChatAvatarService* avatarService); + ChatAvatar(ChatAvatarService* avatarService, const std::u16string& name, const std::u16string& address, uint32_t userId, + uint32_t attributes, const std::u16string& loginLocation); + + bool IsInvisible() const { return (attributes_ & static_cast(AvatarAttribute::INVISIBLE)) != 0; } + bool IsGm() const { return (attributes_ & static_cast(AvatarAttribute::GM)) != 0; } + bool IsSuperGm() const { return (attributes_ & static_cast(AvatarAttribute::SUPERGM)) != 0; } + bool IsSuperSnoop() const { return (attributes_ & static_cast(AvatarAttribute::SUPERSNOOP)) != 0; } + + const uint32_t GetAvatarId() const { return avatarId_; } + const uint32_t GetUserId() const { return userId_; } + const std::u16string& GetName() const { return name_; } + const std::u16string& GetAddress() const { return address_; } + const uint32_t GetAttributes() const { return attributes_; } + void SetAttributes(const uint32_t attributes); + const std::u16string& GetLoginLocation() const { return loginLocation_; } + const std::u16string& GetServer() const { return server_; } + const std::u16string& GetGateway() const { return gateway_; } + const uint32_t GetServerId() const { return serverId_; } + const uint32_t GetGatewayId() const { return gatewayId_; } + const std::u16string& GetEmail() const { return email_; } + const uint32_t GetInboxLimit() const { return inboxLimit_; } + const std::u16string& GetStatusMessage() const { return statusMessage_; } + const bool IsOnline() const { return isOnline_; } + + void AddFriend(ChatAvatar* avatar, const std::u16string& comment = u""); + void RemoveFriend(const ChatAvatar* avatar); + void UpdateFriendComment(const ChatAvatar* avatar, const std::u16string& comment); + bool IsFriend(const ChatAvatar* avatar); + + const std::vector GetFriendList() const { return friendList_; } + + void AddIgnore(ChatAvatar* avatar); + void RemoveIgnore(const ChatAvatar* avatar); + bool IsIgnored(const ChatAvatar* avatar); + + const std::vector GetIgnoreList() const { return ignoreList_; } + + std::vector GetJoinedRooms(); + void JoinRoom(ChatRoom* room); + void UnjoinRoom(ChatRoom* room); + +private: + friend class ChatAvatarService; + + ChatAvatarService* avatarService_; + + uint32_t avatarId_ = 0; + uint32_t userId_ = 0; + std::u16string name_ = u""; + std::u16string address_ = u""; + uint32_t attributes_ = 0; + std::u16string loginLocation_ = u""; + std::u16string server_ = u""; + std::u16string gateway_ = u""; + uint32_t serverId_ = 0; + uint32_t gatewayId_ = 0; + std::u16string email_ = u""; + uint32_t inboxLimit_ = 0; + std::u16string statusMessage_ = u""; + bool isOnline_ = false; + + std::vector friendList_; + std::vector ignoreList_; + + std::vector rooms_; +}; + +template +void write(StreamT& ar, const ChatAvatar* data) { + write(ar, data->GetAvatarId()); + write(ar, data->GetUserId()); + write(ar, data->GetName()); + write(ar, data->GetAddress()); + write(ar, data->GetAttributes()); + write(ar, data->GetLoginLocation()); + write(ar, data->GetServer()); + write(ar, data->GetGateway()); + write(ar, data->GetServerId()); + write(ar, data->GetGatewayId()); +} + + +template +void write(StreamT& ar, const FriendContact& data) { + write(ar, data.frnd->GetName()); + write(ar, data.frnd->GetAddress()); + write(ar, data.comment); + write(ar, static_cast(data.frnd->IsOnline() ? 1 : 0)); +} + +template +void write(StreamT& ar, const IgnoreContact& data) { + write(ar, data.ignored->GetName()); + write(ar, data.ignored->GetAddress()); +} diff --git a/src/ChatAvatarService.cpp b/src/ChatAvatarService.cpp new file mode 100644 index 0000000..0de85a3 --- /dev/null +++ b/src/ChatAvatarService.cpp @@ -0,0 +1,488 @@ +#include "ChatAvatarService.hpp" +#include "ChatAvatar.hpp" +#include "SQLite3.hpp" +#include "StringUtils.hpp" + +#include + +ChatAvatarService::ChatAvatarService(sqlite3* db) + : db_{db} {} + +ChatAvatarService::~ChatAvatarService() {} + +ChatAvatar* ChatAvatarService::GetAvatar(const std::u16string& name, const std::u16string& address) { + ChatAvatar* avatar = GetCachedAvatar(name, address); + + if (!avatar) { + auto loadedAvatar = LoadStoredAvatar(name, address); + if (loadedAvatar != nullptr) { + avatar = loadedAvatar.get(); + avatarCache_.emplace_back(std::move(loadedAvatar)); + + LoadFriendList(avatar); + LoadIgnoreList(avatar); + } + } + + return avatar; +} + +ChatAvatar* ChatAvatarService::GetAvatar(uint32_t avatarId) { + ChatAvatar* avatar = GetCachedAvatar(avatarId); + + if (!avatar) { + auto loadedAvatar = LoadStoredAvatar(avatarId); + if (loadedAvatar != nullptr) { + avatar = loadedAvatar.get(); + avatarCache_.emplace_back(std::move(loadedAvatar)); + + LoadFriendList(avatar); + LoadIgnoreList(avatar); + } + } + + return avatar; +} + +ChatAvatar* ChatAvatarService::CreateAvatar(const std::u16string& name, const std::u16string& address, + uint32_t userId, uint32_t loginAttributes, const std::u16string& loginLocation) { + auto tmp + = std::make_unique(this, name, address, userId, loginAttributes, loginLocation); + auto avatar = tmp.get(); + + InsertAvatar(avatar); + + avatarCache_.emplace_back(std::move(tmp)); + + return avatar; +} + +void ChatAvatarService::DestroyAvatar(ChatAvatar* avatar) { + DeleteAvatar(avatar); + LogoutAvatar(avatar); + RemoveCachedAvatar(avatar->GetAvatarId()); +} + +void ChatAvatarService::LoginAvatar(ChatAvatar* avatar) { + avatar->isOnline_ = true; + + if (!IsOnline(avatar)) { + onlineAvatars_.push_back(avatar); + } +} + +void ChatAvatarService::LogoutAvatar(ChatAvatar* avatar) { + avatar->isOnline_ = false; + + onlineAvatars_.erase(std::remove_if( + std::begin(onlineAvatars_), std::end(onlineAvatars_), [avatar](auto onlineAvatar) { + return onlineAvatar->GetAvatarId() == avatar->GetAvatarId(); + })); +} + +void ChatAvatarService::PersistAvatar(const ChatAvatar* avatar) { UpdateAvatar(avatar); } + +void ChatAvatarService::PersistFriend( + uint32_t srcAvatarId, uint32_t destAvatarId, const std::u16string& comment) { + sqlite3_stmt* stmt; + char sql[] = "INSERT INTO friend (avatar_id, friend_avatar_id, comment) VALUES (@avatar_id, " + "@friend_avatar_id, @comment)"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + int friendAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@friend_avatar_id"); + int commentIdx = sqlite3_bind_parameter_index(stmt, "@comment"); + + std::string commentStr = FromWideString(comment); + + sqlite3_bind_int(stmt, avatarIdIdx, srcAvatarId); + sqlite3_bind_int(stmt, friendAvatarIdIdx, destAvatarId); + sqlite3_bind_text(stmt, commentIdx, commentStr.c_str(), -1, 0); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatAvatarService::PersistIgnore(uint32_t srcAvatarId, uint32_t destAvatarId) { + sqlite3_stmt* stmt; + char sql[] = "INSERT INTO ignore (avatar_id, ignore_avatar_id, comment) VALUES (@avatar_id, " + "@ignore_avatar_id)"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + int ignoreAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@ignore_avatar_id"); + + sqlite3_bind_int(stmt, avatarIdIdx, srcAvatarId); + sqlite3_bind_int(stmt, ignoreAvatarIdIdx, destAvatarId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatAvatarService::RemoveFriend(uint32_t srcAvatarId, uint32_t destAvatarId) { + sqlite3_stmt* stmt; + + char sql[] = "DELETE FROM friend WHERE avatar_id = @avatar_id AND friend_avatar_id = " + "@friend_avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + int friendAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@friend_avatar_id"); + + sqlite3_bind_int(stmt, avatarIdIdx, srcAvatarId); + sqlite3_bind_int(stmt, friendAvatarIdIdx, destAvatarId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatAvatarService::RemoveIgnore(uint32_t srcAvatarId, uint32_t destAvatarId) { + sqlite3_stmt* stmt; + + char sql[] = "DELETE FROM ignore WHERE avatar_id = @avatar_id AND ignore_avatar_id = " + "@ignore_avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + int ignoreAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@ignore_avatar_id"); + + sqlite3_bind_int(stmt, avatarIdIdx, srcAvatarId); + sqlite3_bind_int(stmt, ignoreAvatarIdIdx, destAvatarId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatAvatarService::UpdateFriendComment( + uint32_t srcAvatarId, uint32_t destAvatarId, const std::u16string& comment) { + sqlite3_stmt* stmt; + char sql[] = "UDPATE friend SET comment = @comment WHERE avatar_id = @avatar_id AND " + "friend_avatar_id = @friend_avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int commentIdx = sqlite3_bind_parameter_index(stmt, "@comment"); + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + int friendAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@friend_avatar_id"); + + std::string commentStr = FromWideString(comment); + + sqlite3_bind_text(stmt, commentIdx, commentStr.c_str(), -1, 0); + sqlite3_bind_int(stmt, avatarIdIdx, srcAvatarId); + sqlite3_bind_int(stmt, friendAvatarIdIdx, destAvatarId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +ChatAvatar* ChatAvatarService::GetCachedAvatar( + const std::u16string& name, const std::u16string& address) { + ChatAvatar* avatar = nullptr; + + // First look for the avatar in the cache + auto find_iter = std::find_if( + std::begin(avatarCache_), std::end(avatarCache_), [name, address](const auto& avatar) { + return avatar->name_.compare(name) == 0 && avatar->address_.compare(address) == 0; + }); + + if (find_iter != std::end(avatarCache_)) { + avatar = find_iter->get(); + } + + return avatar; +} + +ChatAvatar* ChatAvatarService::GetCachedAvatar(uint32_t avatarId) { + ChatAvatar* avatar = nullptr; + + // First look for the avatar in the cache + auto find_iter = std::find_if(std::begin(avatarCache_), std::end(avatarCache_), + [avatarId](const auto& avatar) { return avatar->avatarId_ == avatarId; }); + + if (find_iter != std::end(avatarCache_)) { + avatar = find_iter->get(); + } + + return avatar; +} + +void ChatAvatarService::RemoveCachedAvatar(uint32_t avatarId) { + auto remove_iter = std::remove_if(std::begin(avatarCache_), std::end(avatarCache_), + [avatarId](const auto& avatar) { return avatar->avatarId_ == avatarId; }); + + if (remove_iter != std::end(avatarCache_)) { + avatarCache_.erase(remove_iter); + } +} + +void ChatAvatarService::RemoveAsFriendOrIgnoreFromAll(const ChatAvatar* avatar) { + for (auto& cachedAvatar : avatarCache_) { + if (cachedAvatar->IsFriend(avatar)) { + cachedAvatar->RemoveFriend(avatar); + } + + if (cachedAvatar->IsIgnored(avatar)) { + cachedAvatar->RemoveIgnore(avatar); + } + } +} + +std::unique_ptr ChatAvatarService::LoadStoredAvatar( + const std::u16string& name, const std::u16string& address) { + std::unique_ptr avatar{nullptr}; + + sqlite3_stmt* stmt; + + char sql[] = "SELECT id, user_id, name, address, attributes FROM avatar WHERE name = @name AND " + "address = @address"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + std::string nameStr = FromWideString(name); + std::string addressStr = FromWideString(address); + + int nameIdx = sqlite3_bind_parameter_index(stmt, "@name"); + int addressIdx = sqlite3_bind_parameter_index(stmt, "@address"); + + sqlite3_bind_text(stmt, nameIdx, nameStr.c_str(), -1, 0); + sqlite3_bind_text(stmt, addressIdx, addressStr.c_str(), -1, 0); + + if (sqlite3_step(stmt) == SQLITE_ROW) { + avatar = std::make_unique(this); + avatar->avatarId_ = sqlite3_column_int(stmt, 0); + avatar->userId_ = sqlite3_column_int(stmt, 1); + + auto tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 2))); + avatar->name_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 3))); + avatar->address_ = std::u16string(std::begin(tmp), std::end(tmp)); + + avatar->attributes_ = sqlite3_column_int(stmt, 4); + } + + sqlite3_finalize(stmt); + + return avatar; +} + +std::unique_ptr ChatAvatarService::LoadStoredAvatar(uint32_t avatarId) { + std::unique_ptr avatar{nullptr}; + + sqlite3_stmt* stmt; + + char sql[] = "SELECT id, user_id, name, address, attributes FROM avatar WHERE id = @avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + + sqlite3_bind_int(stmt, avatarIdIdx, avatarId); + + if (sqlite3_step(stmt) == SQLITE_ROW) { + avatar = std::make_unique(this); + avatar->avatarId_ = sqlite3_column_int(stmt, 0); + avatar->userId_ = sqlite3_column_int(stmt, 1); + + auto tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 2))); + avatar->name_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 3))); + avatar->address_ = std::u16string(std::begin(tmp), std::end(tmp)); + + avatar->attributes_ = sqlite3_column_int(stmt, 4); + } + + sqlite3_finalize(stmt); + + return avatar; +} + +void ChatAvatarService::InsertAvatar(ChatAvatar* avatar) { + CHECK_NOTNULL(avatar); + sqlite3_stmt* stmt; + + char sql[] = "INSERT INTO avatar (user_id, name, address, attributes) VALUES (@user_id, @name, " + "@address, @attributes)"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + std::string nameStr = FromWideString(avatar->name_); + std::string addressStr = FromWideString(avatar->address_); + + int userIdIdx = sqlite3_bind_parameter_index(stmt, "@user_id"); + int nameIdx = sqlite3_bind_parameter_index(stmt, "@name"); + int addressIdx = sqlite3_bind_parameter_index(stmt, "@address"); + int attributesIdx = sqlite3_bind_parameter_index(stmt, "@attributes"); + + sqlite3_bind_int(stmt, userIdIdx, avatar->userId_); + sqlite3_bind_text(stmt, nameIdx, nameStr.c_str(), -1, 0); + sqlite3_bind_text(stmt, addressIdx, addressStr.c_str(), -1, 0); + sqlite3_bind_int(stmt, attributesIdx, avatar->attributes_); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + avatar->avatarId_ = static_cast(sqlite3_last_insert_rowid(db_)); + + sqlite3_finalize(stmt); +} + +void ChatAvatarService::UpdateAvatar(const ChatAvatar* avatar) { + CHECK_NOTNULL(avatar); + sqlite3_stmt* stmt; + + char sql[] = "UPDATE avatar SET user_id = @user_id, name = @name, address = @address, " + "attributes = @attributes " + "WHERE id = @avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + std::string nameStr = FromWideString(avatar->name_); + std::string addressStr = FromWideString(avatar->address_); + + int userIdIdx = sqlite3_bind_parameter_index(stmt, "@user_id"); + int nameIdx = sqlite3_bind_parameter_index(stmt, "@name"); + int addressIdx = sqlite3_bind_parameter_index(stmt, "@address"); + int attributesIdx = sqlite3_bind_parameter_index(stmt, "@attributes"); + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + + sqlite3_bind_int(stmt, userIdIdx, avatar->userId_); + sqlite3_bind_text(stmt, nameIdx, nameStr.c_str(), -1, 0); + sqlite3_bind_text(stmt, addressIdx, addressStr.c_str(), -1, 0); + sqlite3_bind_int(stmt, attributesIdx, avatar->attributes_); + sqlite3_bind_int(stmt, avatarIdIdx, avatar->avatarId_); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + sqlite3_finalize(stmt); +} + +void ChatAvatarService::DeleteAvatar(ChatAvatar* avatar) { + CHECK_NOTNULL(avatar); + sqlite3_stmt* stmt; + + char sql[] = "DELETE FROM avatar WHERE id = @avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + + sqlite3_bind_int(stmt, avatarIdIdx, avatar->avatarId_); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + sqlite3_finalize(stmt); +} + +void ChatAvatarService::LoadFriendList(ChatAvatar* avatar) { + sqlite3_stmt* stmt; + + char sql[] = "SELECT friend_avatar_id, comment FROM friend WHERE avatar_id = @avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + + sqlite3_bind_int(stmt, avatarIdIdx, avatar->avatarId_); + + uint32_t tmpFriendId; + std::string tmpComment; + while (sqlite3_step(stmt) == SQLITE_ROW) { + tmpFriendId = sqlite3_column_int(stmt, 0); + tmpComment = reinterpret_cast(sqlite3_column_text(stmt, 1)); + + auto friendAvatar = GetAvatar(tmpFriendId); + + avatar->friendList_.emplace_back(friendAvatar, ToWideString(tmpComment)); + } +} + +void ChatAvatarService::LoadIgnoreList(ChatAvatar* avatar) { + sqlite3_stmt* stmt; + + char sql[] = "SELECT ignore_avatar_id FROM ignore WHERE avatar_id = @avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + + sqlite3_bind_int(stmt, avatarIdIdx, avatar->avatarId_); + + uint32_t tmpIgnoreId; + while (sqlite3_step(stmt) == SQLITE_ROW) { + tmpIgnoreId = sqlite3_column_int(stmt, 0); + + auto ignoreAvatar = GetAvatar(tmpIgnoreId); + + avatar->ignoreList_.emplace_back(ignoreAvatar); + } +} + +bool ChatAvatarService::IsOnline(const ChatAvatar * avatar) const { + for (auto onlineAvatar : onlineAvatars_) { + if (onlineAvatar->GetAvatarId() == avatar->GetAvatarId()) { + return true; + } + } + + return false; +} diff --git a/src/ChatAvatarService.hpp b/src/ChatAvatarService.hpp new file mode 100644 index 0000000..8c47b03 --- /dev/null +++ b/src/ChatAvatarService.hpp @@ -0,0 +1,65 @@ + +#pragma once + +#include "ChatAvatar.hpp" +#include "ChatEnums.hpp" + +#include + +#include +#include +#include + +struct sqlite3; + +class ChatAvatarService { +public: + explicit ChatAvatarService(sqlite3* db); + ~ChatAvatarService(); + + ChatAvatar* GetAvatar(const std::u16string& name, const std::u16string& address); + ChatAvatar* GetAvatar(uint32_t avatarId); + + ChatAvatar* CreateAvatar(const std::u16string& name, + const std::u16string& address, uint32_t userId, uint32_t loginAttributes, + const std::u16string& loginLocation); + + void DestroyAvatar(ChatAvatar* avatar); + + void LoginAvatar(ChatAvatar* avatar); + void LogoutAvatar(ChatAvatar* avatar); + + void PersistAvatar(const ChatAvatar* avatar); + void PersistFriend(uint32_t srcAvatarId, uint32_t destAvatarId, const std::u16string& comment); + void PersistIgnore(uint32_t srcAvatarId, uint32_t destAvatarId); + + void RemoveFriend(uint32_t srcAvatarId, uint32_t destAvatarId); + void RemoveIgnore(uint32_t srcAvatarId, uint32_t destAvatarId); + + void UpdateFriendComment(uint32_t srcAvatarId, uint32_t destAvatarId, const std::u16string& comment); + + const std::vector& GetOnlineAvatars() const { return onlineAvatars_; } + +private: + ChatAvatar* GetCachedAvatar(const std::u16string& name, const std::u16string& address); + ChatAvatar* GetCachedAvatar(uint32_t avatarId); + + void RemoveCachedAvatar(uint32_t avatarId); + void RemoveAsFriendOrIgnoreFromAll(const ChatAvatar* avatar); + + std::unique_ptr LoadStoredAvatar(const std::u16string& name, const std::u16string& address); + std::unique_ptr LoadStoredAvatar(uint32_t avatarId); + + void InsertAvatar(ChatAvatar* avatar); + void UpdateAvatar(const ChatAvatar* avatar); + void DeleteAvatar(ChatAvatar* avatar); + + void LoadFriendList(ChatAvatar* avatar); + void LoadIgnoreList(ChatAvatar* avatar); + + bool IsOnline(const ChatAvatar* avatar) const; + + std::vector> avatarCache_; + std::vector onlineAvatars_; + sqlite3* db_; +}; diff --git a/src/ChatEnums.cpp b/src/ChatEnums.cpp new file mode 100644 index 0000000..042c579 --- /dev/null +++ b/src/ChatEnums.cpp @@ -0,0 +1,152 @@ +#include "ChatEnums.hpp" + +const char* ToString(ChatResultCode code) { + switch (code) { + case ChatResultCode::SUCCESS: + return "SUCCESS"; + case ChatResultCode::TIMEOUT: + return "TIMEOUT"; + case ChatResultCode::DUPLICATELOGIN: + return "DUPLICATELOGIN"; + case ChatResultCode::SRCAVATARDOESNTEXIST: + return "SRCAVATARDOESNTEXIST"; + case ChatResultCode::DESTAVATARDOESNTEXIST: + return "DESTAVATARDOESNTEXIST"; + case ChatResultCode::ADDRESSDOESNTEXIST: + return "ADDRESSDOESNTEXIST"; + case ChatResultCode::ADDRESSNOTROOM: + return "ADDRESSNOTROOM"; + case ChatResultCode::ADDRESSNOTAID: + return "ADDRESSNOTAID"; + case ChatResultCode::FRIENDNOTFOUND: + return "FRIENDNOTFOUND"; + case ChatResultCode::ROOM_UNKNOWNFAILURE: + return "ROOM_UNKNOWNFAILURE"; + case ChatResultCode::ROOM_SRCNOTINROOM: + return "ROOM_SRCNOTINROOM"; + case ChatResultCode::ROOM_DESTNOTINROOM: + return "ROOM_DESTNOTINROOM"; + case ChatResultCode::ROOM_BANNEDAVATAR: + return "ROOM_BANNEDAVATAR"; + case ChatResultCode::ROOM_PRIVATEROOM: + return "ROOM_PRIVATEROOM"; + case ChatResultCode::ROOM_MODERATEDROOM: + return "ROOM_MODERATEDROOM"; + case ChatResultCode::ROOM_NOTINROOM: + return "ROOM_NOTINROOM"; + case ChatResultCode::ROOM_NOPRIVILEGES: + return "ROOM_NOPRIVILEGES"; + case ChatResultCode::DATABASE: + return "DATABASE"; + case ChatResultCode::CANNOTGETAVATARID: + return "CANNOTGETAVATARID"; + case ChatResultCode::CANNOTGETNODEID: + return "CANNOTGETNODEID"; + case ChatResultCode::CANNOTGETPMSGID: + return "CANNOTGETPMSGID"; + case ChatResultCode::PMSGNOTFOUND: + return "PMSGNOTFOUND"; + case ChatResultCode::ROOMMAXAVATARSREACHED: + return "ROOMMAXAVATARSREACHED"; + case ChatResultCode::IGNORING: + return "IGNORING"; + case ChatResultCode::ROOM_ALREADYEXISTS: + return "ROOM_ALREADYEXISTS"; + case ChatResultCode::NOTHINGTOCONFIRM: + return "NOTHINGTOCONFIRM"; + case ChatResultCode::DUPLICATEFRIEND: + return "DUPLICATEFRIEND"; + case ChatResultCode::IGNORENOTFOUND: + return "IGNORENOTFOUND"; + case ChatResultCode::DUPLICATEIGNORE: + return "DUPLICATEIGNORE"; + case ChatResultCode::DBFAIL: + return "DBFAIL"; + case ChatResultCode::ROOM_DESTAVATARNOTMODERATOR: + return "ROOM_DESTAVATARNOTMODERATOR"; + case ChatResultCode::ROOM_DESTAVATARNOTINVITED: + return "ROOM_DESTAVATARNOTINVITED"; + case ChatResultCode::ROOM_DESTAVATARNOTBANNED: + return "ROOM_DESTAVATARNOTBANNED"; + case ChatResultCode::ROOM_DUPLICATEBAN: + return "ROOM_DUPLICATEBAN"; + case ChatResultCode::ROOM_DUPLICATEMODERATOR: + return "ROOM_DUPLICATEMODERATOR"; + case ChatResultCode::ROOM_DUPLICATEINVITE: + return "ROOM_DUPLICATEINVITE"; + case ChatResultCode::ROOM_ALREADYINROOM: + return "ROOM_ALREADYINROOM"; + case ChatResultCode::ROOM_PARENTNONPERSISTENT: + return "ROOM_PARENTNONPERSISTENT"; + case ChatResultCode::ROOM_PARENTBADNODETYPE: + return "ROOM_PARENTBADNODETYPE"; + case ChatResultCode::NOFANCLUBHANDLE: + return "NOFANCLUBHANDLE"; + case ChatResultCode::AIDALREADYEXISTS: + return "AIDALREADYEXISTS"; + case ChatResultCode::UIDALREADYEXISTS: + return "UIDALREADYEXISTS"; + case ChatResultCode::WRONGCHATSERVERFORREQUEST: + return "WRONGCHATSERVERFORREQUEST"; + case ChatResultCode::SUCCESSBADDATA: + return "SUCCESSBADDATA"; + case ChatResultCode::NULLNAMELOGIN: + return "NULLNAMELOGIN"; + case ChatResultCode::SERVER_IDENTITY_EMPTY: + return "SERVER_IDENTITY_EMPTY"; + case ChatResultCode::SERVER_IDENTITY_TAKEN: + return "SERVER_IDENTITY_TAKEN"; + case ChatResultCode::REMOTESERVERDOWN: + return "REMOTESERVERDOWN"; + case ChatResultCode::NODEIDCONFLICT: + return "NODEIDCONFLICT"; + case ChatResultCode::INVALIDNODENAME: + return "INVALIDNODENAME"; + case ChatResultCode::INSUFFICIENTGMPRIVS: + return "INSUFFICIENTGMPRIVS"; + case ChatResultCode::SNOOPALREADYADDED: + return "SNOOPALREADYADDED"; + case ChatResultCode::NOTSNOOPING: + return "NOTSNOOPING"; + case ChatResultCode::ROOM_DESTAVATARNOTTEMPORARYMODERATOR: + return "ROOM_DESTAVATARNOTTEMPORARYMODERATOR"; + case ChatResultCode::ROOM_DESTAVATARNOTVOICE: + return "ROOM_DESTAVATARNOTVOICE"; + case ChatResultCode::ROOM_DUPLICATETEMPORARYMODERATOR: + return "ROOM_DUPLICATETEMPORARYMODERATOR"; + case ChatResultCode::ROOM_DUPLICATEVOICE: + return "ROOM_DUPLICATEVOICE"; + case ChatResultCode::AVATARMUSTBELOGGEDOUT: + return "AVATARMUSTBELOGGEDOUT"; + case ChatResultCode::NOTHINGTODO: + return "NOTHINGTODO"; + case ChatResultCode::TRANSFERNAMENULL: + return "TRANSFERNAMENULL"; + case ChatResultCode::TRANSFERUSERIDZERO: + return "TRANSFERUSERIDZERO"; + case ChatResultCode::TRANSFERADDRESSNULL: + return "TRANSFERADDRESSNULL"; + case ChatResultCode::OUTOFIDS: + return "OUTOFIDS"; + case ChatResultCode::ROOM_LOCALROOM: + return "ROOM_LOCALROOM"; + case ChatResultCode::ROOM_GAMEROOM: + return "ROOM_GAMEROOM"; + case ChatResultCode::ROOM_DESTAVATARNOTENTERING: + return "ROOM_DESTAVATARNOTENTERING"; + case ChatResultCode::INSUFFICIENTPRIORITY: + return "INSUFFICIENTPRIORITY"; + case ChatResultCode::ROOM_WAITINGFORENTRY: + return "ROOM_WAITINGFORENTRY"; + case ChatResultCode::INBOXLIMITEXCEEDED: + return "INBOXLIMITEXCEEDED"; + case ChatResultCode::DUPLICATEDESTINATION: + return "DUPLICATEDESTINATION"; + case ChatResultCode::CATEGORYLIMITEXCEEDED: + return "CATEGORYLIMITEXCEEDED"; + case ChatResultCode::MESSAGE_FILTER_FAILURE: + return "MESSAGE_FILTER_FAILURE"; + case ChatResultCode::INVALID_INPUT: + return "INVALID_INPUT"; + }; +} diff --git a/src/ChatEnums.hpp b/src/ChatEnums.hpp new file mode 100644 index 0000000..1804bd0 --- /dev/null +++ b/src/ChatEnums.hpp @@ -0,0 +1,252 @@ + +#pragma once + +#include +#include + +enum class ChatRequestType : uint16_t { + LOGINAVATAR = 0, + LOGOUTAVATAR, + DESTROYAVATAR, + GETAVATAR, + CREATEROOM, + DESTROYROOM, // 5 + SENDINSTANTMESSAGE, + SENDROOMMESSAGE, + SENDBROADCASTMESSAGE, + ADDFRIEND, + REMOVEFRIEND, // 10 + FRIENDSTATUS, + ADDIGNORE, + REMOVEIGNORE, + ENTERROOM, + LEAVEROOM, // 15 + ADDMODERATOR, + REMOVEMODERATOR, + ADDBAN, + REMOVEBAN, + ADDINVITE, // 20 + REMOVEINVITE, + KICKAVATAR, + SETROOMPARAMS, + GETROOM, + GETROOMSUMMARIES, // 25 + SENDPERSISTENTMESSAGE, + GETPERSISTENTHEADERS, + GETPERSISTENTMESSAGE, + UPDATEPERSISTENTMESSAGE, + UNREGISTERROOM, // 30 + IGNORESTATUS, + FAILOVER_RELOGINAVATAR, + FAILOVER_RECREATEROOM, + CONFIRMFRIEND, + GETAVATARKEYWORDS, // 35 + SETAVATARKEYWORDS, + SEARCHAVATARKEYWORDS, + GETFANCLUBHANDLE, + UPDATEPERSISTENTMESSAGES, + FINDAVATARBYUID, // 40 + CHANGEROOMOWNER, + SETAPIVERSION, + ADDTEMPORARYMODERATOR, + REMOVETEMPORARYMODERATOR, + GRANTVOICE, // 45 + REVOKEVOICE, + SETAVATARATTRIBUTES, + ADDSNOOPAVATAR, + REMOVESNOOPAVATAR, + ADDSNOOPROOM, // 50 + REMOVESNOOPROOM, + GETSNOOPLIST, + PARTIALPERSISTENTHEADERS, + COUNTPERSISTENTMESSAGES, + PURGEPERSISTENTMESSAGES, // 55 + SETFRIENDCOMMENT, + TRANSFERAVATAR, + CHANGEPERSISTENTFOLDER, + ALLOWROOMENTRY, + SETAVATAREMAIL, // 60 + SETAVATARINBOXLIMIT, + SENDMULTIPLEPERSISTENTMESSAGES, + GETMULTIPLEPERSISTENTMESSAGES, + ALTERPERISTENTMESSAGE, + GETANYAVATAR, // 65 + TEMPORARYAVATAR, + AVATARLIST, + SETAVATARSTATUSMESSAGE, + CONFIRMFRIEND_RECIPROCATE, + ADDFRIEND_RECIPROCATE, // 70 + REMOVEFRIEND_RECIPROCATE, + FILTERMESSAGE, + FILTERMESSAGE_EX, + REGISTRAR_GETCHATSERVER = 20001, +}; + +enum class ChatResponseType : uint16_t { + LOGINAVATAR = 0, + LOGOUTAVATAR, + DESTROYAVATAR, + GETAVATAR, + CREATEROOM, + DESTROYROOM, + SENDINSTANTMESSAGE, + SENDROOMMESSAGE, + SENDBROADCASTMESSAGE, + ADDFRIEND, + REMOVEFRIEND, + FRIENDSTATUS, + ADDIGNORE, + REMOVEIGNORE, + ENTERROOM, + LEAVEROOM, + ADDMODERATOR, + REMOVEMODERATOR, + ADDBAN, + REMOVEBAN, + ADDINVITE, + REMOVEINVITE, + KICKAVATAR, + SETROOMPARAMS, + GETROOM, + GETROOMSUMMARIES, + SENDPERSISTENTMESSAGE, + GETPERSISTENTHEADERS, + GETPERSISTENTMESSAGE, + UPDATEPERSISTENTMESSAGE, + UNREGISTERROOM, + IGNORESTATUS, + FAILOVER_RELOGINAVATAR, + FAILOVER_RECREATEROOM, + CONFIRMFRIEND, + GETAVATARKEYWORDS, + SETAVATARKEYWORDS, + SEARCHAVATARKEYWORDS, + GETFANCLUBHANDLE, + UPDATEPERSISTENTMESSAGES, + FINDAVATARBYUID, + CHANGEROOMOWNER, + SETAPIVERSION, + ADDTEMPORARYMODERATOR, + REMOVETEMPORARYMODERATOR, + GRANTVOICE, + REVOKEVOICE, + SETAVATARATTRIBUTES, + ADDSNOOPAVATAR, + REMOVESNOOPAVATAR, + ADDSNOOPROOM, + REMOVESNOOPROOM, + GETSNOOPLIST, + PARTIALPERSISTENTHEADERS, + COUNTPERSISTENTMESSAGES, + PURGEPERSISTENTMESSAGES, + SETFRIENDCOMMENT, + TRANSFERAVATAR, + CHANGEPERSISTENTFOLDER, + ALLOWROOMENTRY, + SETAVATAREMAIL, + SETAVATARINBOXLIMIT, + SENDMULTIPLEPERSISTENTMESSAGES, + GETMULTIPLEPERSISTENTMESSAGES, + ALTERPERSISTENTMESSAGE, + GETANYAVATAR, + TEMPORARYAVATAR, + AVATARLIST, + SETSTATUSMESSAGE, + CONFIRMFRIEND_RECIPROCATE, + ADDFRIEND_RECIPROCATE, + REMOVEFRIEND_RECIPROCATE, + FILTERMESSAGE, + FILTERMESSAGE_EX, + + REGISTRAR_GETCHATSERVER = 20001, +}; + +enum class ChatResultCode : uint32_t { + SUCCESS = 0, + TIMEOUT = 1, + DUPLICATELOGIN, + SRCAVATARDOESNTEXIST, + DESTAVATARDOESNTEXIST, + ADDRESSDOESNTEXIST, // 5 + ADDRESSNOTROOM, + ADDRESSNOTAID, + FRIENDNOTFOUND, + ROOM_UNKNOWNFAILURE, + ROOM_SRCNOTINROOM, // 10 + ROOM_DESTNOTINROOM, + ROOM_BANNEDAVATAR, + ROOM_PRIVATEROOM, + ROOM_MODERATEDROOM, + ROOM_NOTINROOM, // 15 + ROOM_NOPRIVILEGES, + DATABASE, + CANNOTGETAVATARID, + CANNOTGETNODEID, + CANNOTGETPMSGID, // 20 + PMSGNOTFOUND, + ROOMMAXAVATARSREACHED, + IGNORING, + ROOM_ALREADYEXISTS, + NOTHINGTOCONFIRM, // 25 + DUPLICATEFRIEND, + IGNORENOTFOUND, + DUPLICATEIGNORE, + DBFAIL, + ROOM_DESTAVATARNOTMODERATOR, // 30 + ROOM_DESTAVATARNOTINVITED, + ROOM_DESTAVATARNOTBANNED, + ROOM_DUPLICATEBAN, + ROOM_DUPLICATEMODERATOR, + ROOM_DUPLICATEINVITE, // 35 + ROOM_ALREADYINROOM, + ROOM_PARENTNONPERSISTENT, + ROOM_PARENTBADNODETYPE, + NOFANCLUBHANDLE, + AIDALREADYEXISTS, // 40 + UIDALREADYEXISTS, + WRONGCHATSERVERFORREQUEST, + SUCCESSBADDATA, + NULLNAMELOGIN, + SERVER_IDENTITY_EMPTY, // 45 + SERVER_IDENTITY_TAKEN, + REMOTESERVERDOWN, + NODEIDCONFLICT, + INVALIDNODENAME, + INSUFFICIENTGMPRIVS, // 50 + SNOOPALREADYADDED, + NOTSNOOPING, + ROOM_DESTAVATARNOTTEMPORARYMODERATOR, + ROOM_DESTAVATARNOTVOICE, + ROOM_DUPLICATETEMPORARYMODERATOR, // 55 + ROOM_DUPLICATEVOICE, + AVATARMUSTBELOGGEDOUT, + NOTHINGTODO, + TRANSFERNAMENULL, + TRANSFERUSERIDZERO, // 60 + TRANSFERADDRESSNULL, + OUTOFIDS, + ROOM_LOCALROOM, + ROOM_GAMEROOM, + ROOM_DESTAVATARNOTENTERING, // 65 + INSUFFICIENTPRIORITY, + ROOM_WAITINGFORENTRY, + INBOXLIMITEXCEEDED, + DUPLICATEDESTINATION, + CATEGORYLIMITEXCEEDED, // 70 + MESSAGE_FILTER_FAILURE, + INVALID_INPUT, +}; + +struct ChatResultException { + ChatResultCode code; + std::string message; + + explicit ChatResultException(const ChatResultCode result) + : code{result} {} + + ChatResultException(const ChatResultCode result, char const * text) + : code{result} + , message{text} {} +}; + +const char* ToString(ChatResultCode code); \ No newline at end of file diff --git a/src/ChatRoom.cpp b/src/ChatRoom.cpp new file mode 100644 index 0000000..8db4ddf --- /dev/null +++ b/src/ChatRoom.cpp @@ -0,0 +1,307 @@ + +#include "ChatRoom.hpp" +#include "ChatAvatar.hpp" +#include "ChatRoomService.hpp" + +#include + +inline unsigned IS_SET(unsigned var, unsigned bit) { return (var & bit); } + +ChatRoom::ChatRoom(ChatRoomService* roomService, uint32_t roomId, const ChatAvatar* creator, + const std::u16string& roomName, const std::u16string& roomTopic, const std::u16string& roomPassword, + uint32_t roomAttributes, uint32_t maxRoomSize, const std::u16string& roomAddress, + const std::u16string& srcAddress) + : roomService_{roomService} + , roomId_{roomId} + , creatorName_{creator->GetName()} + , creatorAddress_{creator->GetAddress()} + , roomName_{roomName} + , roomTopic_{roomTopic} + , roomPassword_{roomPassword} + , roomAddress_{roomAddress + u"+" + roomName} + , creatorId_{creator->GetAvatarId()} + , roomAttributes_{roomAttributes} + , maxRoomSize_{maxRoomSize} { + administrators_.push_back(creator); + moderators_.push_back(creator); +} + +bool ChatRoom::IsPrivate() const { + return (roomAttributes_ & static_cast(RoomAttributes::PRIVATE)) != 0; +} + +bool ChatRoom::IsModerated() const { + return (roomAttributes_ & static_cast(RoomAttributes::MODERATED)) != 0; +} + +bool ChatRoom::IsPersistent() const { + return (roomAttributes_ & static_cast(RoomAttributes::PERSISTENT)) != 0; +} + +bool ChatRoom::IsLocalWorld() const { + return (roomAttributes_ & static_cast(RoomAttributes::LOCAL_WORLD)) != 0; +} + +bool ChatRoom::IsLocalGame() const { + return (roomAttributes_ & static_cast(RoomAttributes::LOCAL_GAME)) != 0; +} + +void ChatRoom::EnterRoom(ChatAvatar* avatar, const std::u16string& password) { + if (roomPassword_.length() > 0 && roomPassword_.compare(password) != 0) { + throw ChatResultException{ChatResultCode::ROOM_PRIVATEROOM}; + } + + if (IsBanned(avatar->GetAvatarId())) { + throw ChatResultException{ChatResultCode::ROOM_BANNEDAVATAR}; + } + + if (IsInRoom(avatar)) { + throw ChatResultException{ChatResultCode::ROOM_ALREADYINROOM}; + } + + if (IsPrivate() && !IsCreator(avatar->GetAvatarId()) && !IsInvited(avatar->GetAvatarId())) { + throw ChatResultException{ChatResultCode::ROOM_PRIVATEROOM}; + } + + avatars_.push_back(avatar); + avatarIds_.push_back(avatar->GetAvatarId()); + avatar->JoinRoom(this); +} + +bool ChatRoom::IsInRoom(ChatAvatar* avatar) const { return IsInRoom(avatar->GetAvatarId()); } + +bool ChatRoom::IsInRoom(uint32_t avatarId) const { + return std::find_if(std::begin(avatars_), std::end(avatars_), + [avatarId](ChatAvatar* roomAvatar) { return roomAvatar->GetAvatarId() == avatarId; }) + != std::end(avatars_); +} + +void ChatRoom::LeaveRoom(ChatAvatar* avatar) { + avatar->UnjoinRoom(this); + + auto avatarsIter = std::remove_if(std::begin(avatars_), std::end(avatars_), + [avatar](auto roomAvatar) { return roomAvatar->GetAvatarId() == avatar->GetAvatarId(); }); + + if (avatarsIter != std::end(avatars_)) { + avatars_.erase(avatarsIter); + } + + auto avatarsIdIter = std::remove_if(std::begin(avatarIds_), std::end(avatarIds_), [avatar](auto avatarId) { + return avatar->GetAvatarId() == avatarId; + }); + + if (avatarsIdIter != std::end(avatarIds_)) { + avatarIds_.erase(avatarsIdIter); + } +} + +std::vector ChatRoom::GetConnectedAddresses() const { + std::vector connectedAddresses; + + std::u16string address; + for (auto avatar : avatars_) { + address = avatar->GetAddress(); + if (connectedAddresses.empty() + || std::none_of(std::begin(connectedAddresses), std::end(connectedAddresses), + [&address](const auto& connectedAddress) { + return connectedAddress.compare(address) == 0; + })) { + connectedAddresses.push_back(address); + } + } + + return connectedAddresses; +} + +std::vector ChatRoom::GetRemoteAddresses() const { + std::vector connectedAddresses; + + std::u16string address; + for (auto avatar : avatars_) { + address = avatar->GetAddress(); + if (creatorAddress_.compare(address) != 0 && (connectedAddresses.empty() + || std::none_of(std::begin(connectedAddresses), std::end(connectedAddresses), + [&address](const auto& connectedAddress) { + return connectedAddress.compare(address) == 0; + }))) { + connectedAddresses.push_back(address); + } + } + + return connectedAddresses; +} + +bool ChatRoom::IsCreator(uint32_t avatarId) const { return avatarId == creatorId_; } + +bool ChatRoom::IsModerator(uint32_t avatarId) const { + if (moderators_.empty()) + return false; + + auto find_iter = std::find_if(std::begin(moderators_), std::end(moderators_), + [avatarId](const auto& moderator) { return moderator->GetAvatarId() == avatarId; }); + + return find_iter != std::end(moderators_); +} + +bool ChatRoom::IsAdministrator(uint32_t avatarId) const { + if (administrators_.empty()) + return false; + + auto find_iter = std::find_if(std::begin(administrators_), std::end(administrators_), + [avatarId](const auto& administrator) { return administrator->GetAvatarId() == avatarId; }); + + return find_iter != std::end(administrators_); +} + +bool ChatRoom::IsBanned(uint32_t avatarId) const { + if (banned_.empty()) + return false; + + auto find_iter = std::find_if(std::begin(banned_), std::end(banned_), + [avatarId](const auto& banned) { return banned->GetAvatarId() == avatarId; }); + + return find_iter != std::end(banned_); +} + +bool ChatRoom::IsInvited(uint32_t avatarId) const { + if (invited_.empty()) + return false; + + auto find_iter = std::find_if(std::begin(invited_), std::end(invited_), + [avatarId](const auto& invited) { return invited->GetAvatarId() == avatarId; }); + + return find_iter != std::end(invited_); +} + +void ChatRoom::KickAvatar(uint32_t srcAvatarId, ChatAvatar* destAvatar) { + if (!IsModerator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (!IsInRoom(destAvatar)) { + throw ChatResultException{ChatResultCode::ROOM_NOTINROOM}; + } + + LeaveRoom(destAvatar); +} + +void ChatRoom::AddAdministrator(uint32_t srcAvatarId, ChatAvatar* administrator) { + if (!IsCreator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (!IsAdministrator(administrator->GetAvatarId())) { + administrators_.push_back(administrator); + + if (IsPersistent()) { + roomService_->PersistBanned(administrator->GetAvatarId(), roomId_); + } + } +} + +void ChatRoom::AddModerator(uint32_t srcAvatarId, ChatAvatar* moderator) { + if (!IsCreator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (IsModerator(moderator->GetAvatarId())) { + throw ChatResultException{ChatResultCode::ROOM_DUPLICATEMODERATOR}; + } + + moderators_.push_back(moderator); + + if (IsPersistent()) { + roomService_->PersistBanned(moderator->GetAvatarId(), roomId_); + } +} + +void ChatRoom::AddBanned(uint32_t srcAvatarId, ChatAvatar* banned) { + if (!IsModerator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (IsBanned(banned->GetAvatarId())) { + throw ChatResultException{ChatResultCode::ROOM_DUPLICATEBAN}; + } + + banned_.push_back(banned); + + if (IsPersistent()) { + roomService_->PersistBanned(banned->GetAvatarId(), roomId_); + } +} + +void ChatRoom::AddInvite(uint32_t srcAvatarId, ChatAvatar* invited) { + if (!IsModerator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (IsInvited(invited->GetAvatarId())) { + throw ChatResultException{ChatResultCode::ROOM_DUPLICATEINVITE}; + } + + invited_.push_back(invited); +} + +void ChatRoom::RemoveAdministrator(uint32_t srcAvatarId, uint32_t avatarId) { + if (!IsCreator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (administrators_.empty()) + return; + + administrators_.erase(std::remove_if(std::begin(administrators_), std::end(administrators_), + [avatarId](auto administrator) { return administrator->GetAvatarId() == avatarId; })); + + if (IsPersistent()) { + roomService_->DeleteAdministrator(avatarId, roomId_); + } +} + +void ChatRoom::RemoveModerator(uint32_t srcAvatarId, uint32_t avatarId) { + if (!IsCreator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (moderators_.empty() || !IsModerator(avatarId)) { + throw ChatResultException{ChatResultCode::ROOM_DESTAVATARNOTMODERATOR}; + } + + moderators_.erase(std::remove_if(std::begin(moderators_), std::end(moderators_), + [avatarId](auto moderator) { return moderator->GetAvatarId() == avatarId; })); + + if (IsPersistent()) { + roomService_->DeleteModerator(avatarId, roomId_); + } +} + +void ChatRoom::RemoveBanned(uint32_t srcAvatarId, uint32_t avatarId) { + if (!IsModerator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (banned_.empty() || !IsBanned(avatarId)) { + throw ChatResultException{ChatResultCode::ROOM_DESTAVATARNOTBANNED}; + } + + banned_.erase(std::remove_if(std::begin(banned_), std::end(banned_), + [avatarId](auto banned) { return banned->GetAvatarId() == avatarId; })); + + if (IsPersistent()) { + roomService_->DeleteBanned(avatarId, roomId_); + } +} + +void ChatRoom::RemoveInvite(uint32_t srcAvatarId, uint32_t avatarId) { + if (!IsModerator(srcAvatarId)) { + throw ChatResultException{ChatResultCode::ROOM_NOPRIVILEGES}; + } + + if (invited_.empty() || !IsInvited(avatarId)) { + throw ChatResultException{ChatResultCode::ROOM_DESTAVATARNOTINVITED}; + } + + invited_.erase(std::remove_if(std::begin(invited_), std::end(invited_), + [avatarId](auto invited) { return invited->GetAvatarId() == avatarId; })); +} diff --git a/src/ChatRoom.hpp b/src/ChatRoom.hpp new file mode 100644 index 0000000..72ad5e9 --- /dev/null +++ b/src/ChatRoom.hpp @@ -0,0 +1,169 @@ + +#pragma once + +#include "ChatEnums.hpp" + +#include +#include + +class ChatAvatar; +class ChatRoomService; + +enum class RoomAttributes : uint32_t { + PRIVATE = 1 << 0, + MODERATED = 1 << 1, + PERSISTENT = 1 << 2, + LOCAL_WORLD = 1 << 4, + LOCAL_GAME = 1 << 5 +}; + +class ChatRoom { +public: + ChatRoom() = default; + ChatRoom(ChatRoomService* roomService, uint32_t roomId, const ChatAvatar* creator, + const std::u16string& roomName, const std::u16string& roomTopic, const std::u16string& roomPassword, + uint32_t roomAttributes, uint32_t maxRoomSize, const std::u16string& roomAddress, + const std::u16string& srcAddress); + + bool IsPrivate() const; + bool IsModerated() const; + bool IsPersistent() const; + bool IsLocalWorld() const; + bool IsLocalGame() const; + + void EnterRoom(ChatAvatar* avatar, const std::u16string& password); + bool IsInRoom(ChatAvatar* avatar) const; + bool IsInRoom(uint32_t avatarId) const; + void LeaveRoom(ChatAvatar* avatar); + + uint32_t GetCreatorId() const { return creatorId_; } + const std::u16string& GetCreatorName() const { return creatorName_; } + const std::u16string& GetCreatorAddress() const { return creatorAddress_; } + const std::u16string& GetRoomName() const { return roomName_; } + const std::u16string& GetRoomAddress() const { return roomAddress_; } + const std::u16string& GetRoomTopic() const { return roomTopic_; } + const std::u16string& GetRoomPassword() const { return roomPassword_; } + const std::u16string& GetRoomPrefix() const { return roomPrefix_; } + uint32_t GetRoomAttributes() const { return roomAttributes_; } + uint32_t GetCurrentRoomSize() const { return avatars_.size(); } + uint32_t GetMaxRoomSize() const { return maxRoomSize_; } + uint32_t GetRoomId() const { return roomId_; } + uint32_t GetCreateTime() const { return createTime_; } + uint32_t GetNodeLevel() const { return nodeLevel_; } + + const std::vector GetAvatars() const { return avatars_; } + std::vector GetAvatarIds() const { return avatarIds_; } + const std::vector GetAdminstrators() const { return administrators_; } + const std::vector GetModerators() const { return moderators_; } + const std::vector GetTempModerators() const { return tempModerators_; } + const std::vector GetBanned() const { return banned_; } + const std::vector GetInvited() const { return invited_; } + const std::vector GetVoice() const { return voice_; } + + /* Returns the addresses of the different game servers currently with avatars + * connected to this room. + */ + std::vector GetConnectedAddresses() const; + std::vector GetRemoteAddresses() const; + + bool IsCreator(uint32_t avatarId) const; + bool IsModerator(uint32_t avatarId) const; + bool IsAdministrator(uint32_t avatarId) const; + bool IsBanned(uint32_t avatarId) const; + bool IsInvited(uint32_t avatarId) const; + + void KickAvatar(uint32_t srcAvatarId, ChatAvatar* destAvatar); + + void AddAdministrator(uint32_t srcAvatarId, ChatAvatar* administrator); + void AddModerator(uint32_t srcAvatarId, ChatAvatar* moderator); + void AddBanned(uint32_t srcAvatarId, ChatAvatar* banned); + void AddInvite(uint32_t srcAvatarId, ChatAvatar* invited); + + void RemoveAdministrator(uint32_t srcAvatarId, uint32_t avatarId); + void RemoveModerator(uint32_t srcAvatarId, uint32_t avatarId); + void RemoveBanned(uint32_t srcAvatarId, uint32_t avatarId); + void RemoveInvite(uint32_t srcAvatarId, uint32_t avatarId); + + uint32_t GetNextMessageId() { return roomMessageId_++; } + +private: + friend class ChatRoomService; + ChatRoomService* roomService_; + std::u16string creatorName_; + std::u16string creatorAddress_; + std::u16string roomName_; + std::u16string roomTopic_; + std::u16string roomPassword_; + std::u16string roomPrefix_ = u""; + std::u16string roomAddress_; + + uint32_t creatorId_; + uint32_t roomAttributes_; + uint32_t maxRoomSize_; + uint32_t roomId_ = 0; + uint32_t createTime_ = 0; + uint32_t nodeLevel_ = 0; + uint32_t roomMessageId_ = 1; + int32_t dbId_ = -1; + + std::vector avatars_; + std::vector avatarIds_; + std::vector administrators_; + std::vector moderators_; + std::vector tempModerators_; + std::vector banned_; + std::vector invited_; + std::vector voice_; +}; + +template +void write(StreamT& ar, const ChatRoom& data) { + write(ar, data.GetCreatorName()); + write(ar, data.GetCreatorAddress()); + write(ar, data.GetCreatorId()); + write(ar, data.GetRoomName()); + write(ar, data.GetRoomTopic()); + write(ar, data.GetRoomPrefix()); + write(ar, data.GetRoomAddress()); + write(ar, data.GetRoomPassword()); + write(ar, data.GetRoomAttributes()); + write(ar, data.GetMaxRoomSize()); + write(ar, data.GetRoomId()); + write(ar, data.GetCreateTime()); + write(ar, data.GetNodeLevel()); + + auto& avatars = data.GetAvatars(); + write(ar, static_cast(avatars.size())); + for (auto& avatar : avatars) + write(ar, avatar); + + auto& administrators = data.GetAdminstrators(); + write(ar, static_cast(administrators.size())); + for (auto& avatar : administrators) + write(ar, avatar); + + auto& moderators = data.GetModerators(); + write(ar, static_cast(moderators.size())); + for (auto& avatar : moderators) + write(ar, avatar); + + auto& tempModerators = data.GetTempModerators(); + write(ar, static_cast(tempModerators.size())); + for (auto& avatar : tempModerators) + write(ar, avatar); + + auto& banned = data.GetBanned(); + write(ar, static_cast(banned.size())); + for (auto& avatar : banned) + write(ar, avatar); + + auto& invited = data.GetInvited(); + write(ar, static_cast(invited.size())); + for (auto& avatar : invited) + write(ar, avatar); + + auto& voice = data.GetVoice(); + write(ar, static_cast(voice.size())); + for (auto& avatar : voice) + write(ar, avatar); +} diff --git a/src/ChatRoomService.cpp b/src/ChatRoomService.cpp new file mode 100644 index 0000000..2787ed6 --- /dev/null +++ b/src/ChatRoomService.cpp @@ -0,0 +1,407 @@ +#include "ChatRoomService.hpp" +#include "ChatAvatarService.hpp" +#include "SQLite3.hpp" +#include "StreamUtils.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +ChatRoomService::ChatRoomService(ChatAvatarService* avatarService, sqlite3* db) + : avatarService_{avatarService} + , db_{db} {} + +ChatRoomService::~ChatRoomService() {} + +void ChatRoomService::LoadRoomsFromStorage(const std::u16string& baseAddress) { + rooms_.clear(); + + sqlite3_stmt* stmt; + + char sql[] = "SELECT id, creator_id, creator_name, creator_address, room_name, room_topic, " + "room_password, room_prefix, room_address, room_attributes, room_max_size, " + "room_message_id, created_at, node_level FROM room WHERE room_address LIKE @baseAddress||'%'"; + + if (sqlite3_prepare_v2(db_, sql, -1, &stmt, 0) != SQLITE_OK) { + throw std::runtime_error("Error preparing SQL statement"); + } + + int baseAddressIdx = sqlite3_bind_parameter_index(stmt, "@baseAddress"); + + auto baseAddressStr = FromWideString(baseAddress); + LOG(INFO) << "Loading rooms for base address: " << baseAddressStr; + sqlite3_bind_text(stmt, baseAddressIdx, baseAddressStr.c_str(), -1, 0); + + while (sqlite3_step(stmt) == SQLITE_ROW) { + auto room = std::make_unique(); + std::string tmp; + room->roomId_ = nextRoomId_++; + room->dbId_ = sqlite3_column_int(stmt, 0); + room->creatorId_ = sqlite3_column_int(stmt, 1); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 2))); + room->creatorName_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 3))); + room->creatorAddress_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 4))); + room->roomName_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 5))); + room->roomTopic_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 6))); + room->roomPassword_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 7))); + room->roomPrefix_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 8))); + room->roomAddress_ = std::u16string{std::begin(tmp), std::end(tmp)}; + + room->roomAttributes_ = sqlite3_column_int(stmt, 9); + room->maxRoomSize_ = sqlite3_column_int(stmt, 10); + room->roomMessageId_ = sqlite3_column_int(stmt, 11); + room->createTime_ = sqlite3_column_int(stmt, 12); + room->nodeLevel_ = sqlite3_column_int(stmt, 13); + + if (!RoomExists(room->GetRoomAddress())) { + rooms_.emplace_back(std::move(room)); + } + } + + LOG(INFO) << "Rooms currently loaded: " << rooms_.size(); +} + +ChatRoom* ChatRoomService::CreateRoom(const ChatAvatar* creator, + const std::u16string& roomName, const std::u16string& roomTopic, const std::u16string& roomPassword, + uint32_t roomAttributes, uint32_t maxRoomSize, const std::u16string& roomAddress, + const std::u16string& srcAddress) { + ChatRoom* roomPtr = nullptr; + + if (RoomExists(roomAddress + u"+" + roomName)) { + throw ChatResultException(ChatResultCode::ROOM_ALREADYEXISTS, "ChatRoom already exists"); + } + + LOG(INFO) << "Creating room " << FromWideString(roomName) << "@" << FromWideString(roomAddress) << " with attributes " + << roomAttributes; + + rooms_.emplace_back(std::make_unique(this, nextRoomId_++, creator, roomName, + roomTopic, roomPassword, roomAttributes, maxRoomSize, roomAddress, srcAddress)); + roomPtr = rooms_.back().get(); + + if (roomPtr->IsPersistent()) { + PersistNewRoom(*roomPtr); + } + + return roomPtr; +} + +void ChatRoomService::DestroyRoom(ChatRoom* room) { + if (room->IsPersistent()) { + DeleteRoom(room); + } + + rooms_.erase(std::remove_if(std::begin(rooms_), std::end(rooms_), + [room](const auto& trackedRoom) { return trackedRoom->GetRoomId() == room->GetRoomId(); })); +} + +ChatResultCode ChatRoomService::PersistNewRoom(ChatRoom& room) { + ChatResultCode result = ChatResultCode::SUCCESS; + sqlite3_stmt* stmt; + + char sql[] = "INSERT INTO room (creator_id, creator_name, creator_address, room_name, " + "room_topic, room_password, room_prefix, room_address, room_attributes, " + "room_max_size, room_message_id, created_at, node_level) VALUES (@creator_id, " + "@creator_name, @creator_address, @room_name, @room_topic, @room_password, " + "@room_prefix, @room_address, @room_attributes, @room_max_size, @room_message_id, " + "@created_at, @node_level)"; + + if (sqlite3_prepare_v2(db_, sql, -1, &stmt, 0) != SQLITE_OK) { + result = ChatResultCode::DBFAIL; + } else { + int creatorIdIdx = sqlite3_bind_parameter_index(stmt, "@creator_id"); + int creatorNameIdx = sqlite3_bind_parameter_index(stmt, "@creator_name"); + int creatorAddressIdx = sqlite3_bind_parameter_index(stmt, "@creator_address"); + int roomNameIdx = sqlite3_bind_parameter_index(stmt, "@room_name"); + int roomTopicIdx = sqlite3_bind_parameter_index(stmt, "@room_topic"); + int roomPasswordIdx = sqlite3_bind_parameter_index(stmt, "@room_password"); + int roomPrefixIdx = sqlite3_bind_parameter_index(stmt, "@room_prefix"); + int roomAddressIdx = sqlite3_bind_parameter_index(stmt, "@room_address"); + int roomAttributesIdx = sqlite3_bind_parameter_index(stmt, "@room_attributes"); + int roomMaxSizeIdx = sqlite3_bind_parameter_index(stmt, "@room_max_size"); + int roomMessageIdIdx = sqlite3_bind_parameter_index(stmt, "@room_message_id"); + int createdAtIdx = sqlite3_bind_parameter_index(stmt, "@created_at"); + int nodeLevelIdx = sqlite3_bind_parameter_index(stmt, "@node_level"); + + sqlite3_bind_int(stmt, creatorIdIdx, room.creatorId_); + + auto creatorName = FromWideString(room.creatorName_); + sqlite3_bind_text(stmt, creatorNameIdx, creatorName.c_str(), -1, 0); + + auto creatorAddress = FromWideString(room.creatorAddress_); + sqlite3_bind_text(stmt, creatorAddressIdx, creatorAddress.c_str(), -1, 0); + + auto roomName = FromWideString(room.roomName_); + sqlite3_bind_text(stmt, roomNameIdx, roomName.c_str(), -1, 0); + + auto roomTopic = FromWideString(room.roomTopic_); + sqlite3_bind_text(stmt, roomTopicIdx, roomTopic.c_str(), -1, 0); + + auto roomPassword = FromWideString(room.roomPassword_); + sqlite3_bind_text(stmt, roomPasswordIdx, roomPassword.c_str(), -1, 0); + + auto roomPrefix = FromWideString(room.roomPrefix_); + sqlite3_bind_text(stmt, roomPrefixIdx, roomPrefix.c_str(), -1, 0); + + auto roomAddress = FromWideString(room.roomAddress_); + sqlite3_bind_text(stmt, roomAddressIdx, roomAddress.c_str(), -1, 0); + + sqlite3_bind_int(stmt, roomAttributesIdx, room.roomAttributes_); + sqlite3_bind_int(stmt, roomMaxSizeIdx, room.maxRoomSize_); + sqlite3_bind_int(stmt, roomMessageIdIdx, room.roomMessageId_); + sqlite3_bind_int(stmt, createdAtIdx, room.createTime_); + sqlite3_bind_int(stmt, nodeLevelIdx, room.nodeLevel_); + + if (sqlite3_step(stmt) != SQLITE_DONE) { + result = ChatResultCode::DBFAIL; + } else { + room.dbId_ = static_cast(sqlite3_last_insert_rowid(db_)); + } + } + + return result; +} + +std::vector ChatRoomService::GetRoomSummaries( + const std::u16string& startNode, const std::u16string& filter) { + std::vector rooms; + + for (auto& room : rooms_) { + auto& roomAddress = room->GetRoomAddress(); + if (roomAddress.compare(0, startNode.length(), startNode) == 0) { + if (!room->IsPrivate()) { + rooms.push_back(room.get()); + } + } + } + + return rooms; +} + +bool ChatRoomService::RoomExists(const std::u16string& roomAddress) const { + return std::find_if(std::begin(rooms_), std::end(rooms_), [roomAddress](auto& room) { + return roomAddress.compare(room->GetRoomAddress()) == 0; + }) != std::end(rooms_); +} + +ChatRoom* ChatRoomService::GetRoom(const std::u16string& roomAddress) { + ChatRoom* room = nullptr; + + auto find_iter = std::find_if(std::begin(rooms_), std::end(rooms_), + [roomAddress](auto& room) { return roomAddress.compare(room->GetRoomAddress()) == 0; }); + + if (find_iter != std::end(rooms_)) { + room = find_iter->get(); + } + + return room; +} + +void ChatRoomService::DeleteRoom(ChatRoom* room) { + sqlite3_stmt* stmt; + char sql[] = "DELETE FROM room WHERE id = @id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int idIdx = sqlite3_bind_parameter_index(stmt, "@id"); + sqlite3_bind_int(stmt, idIdx, room->dbId_); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatRoomService::LoadModerators(ChatRoom * room) { + sqlite3_stmt* stmt; + char sql[] = "SELECT moderator_avatar_id FROM room_moderator WHERE room_id = @room_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + sqlite3_bind_int(stmt, roomIdIdx, room->GetRoomId()); + + while (sqlite3_step(stmt) == SQLITE_ROW) { + uint32_t moderatorId = sqlite3_column_int(stmt, 0); + room->moderators_.push_back(avatarService_->GetAvatar(moderatorId)); + } +} + +void ChatRoomService::PersistModerator(uint32_t moderatorId, uint32_t roomId) { + sqlite3_stmt* stmt; + char sql[] = "INSERT OR IGNORE INTO room_moderator (moderator_avatar_id, room_id) VALUES (@moderator_avatar_id, @room_id)"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int moderatorAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@moderator_avatar_id"); + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + + sqlite3_bind_int(stmt, moderatorAvatarIdIdx, moderatorId); + sqlite3_bind_int(stmt, roomIdIdx, roomId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatRoomService::DeleteModerator(uint32_t moderatorId, uint32_t roomId) { + sqlite3_stmt* stmt; + char sql[] = "DELETE FROM room_moderator WHERE moderator_avatar_id = @moderator_avatar_id AND room_id = @room_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int moderatorAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@moderator_avatar_id"); + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + + sqlite3_bind_int(stmt, moderatorAvatarIdIdx, moderatorId); + sqlite3_bind_int(stmt, roomIdIdx, roomId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatRoomService::LoadAdministrators(ChatRoom * room) { + sqlite3_stmt* stmt; + char sql[] = "SELECT administrator_avatar_id FROM room_administrator WHERE room_id = @room_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + sqlite3_bind_int(stmt, roomIdIdx, room->GetRoomId()); + + while (sqlite3_step(stmt) == SQLITE_ROW) { + uint32_t administratorId = sqlite3_column_int(stmt, 0); + room->administrators_.push_back(avatarService_->GetAvatar(administratorId)); + } +} + +void ChatRoomService::PersistAdministrator(uint32_t administratorId, uint32_t roomId) { + sqlite3_stmt* stmt; + char sql[] = "INSERT OR IGNORE INTO room_administrator (administrator_avatar_id, room_id) VALUES (@administrator_avatar_id, @room_id)"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int administratorAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@administrator_avatar_id"); + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + + sqlite3_bind_int(stmt, administratorAvatarIdIdx, administratorId); + sqlite3_bind_int(stmt, roomIdIdx, roomId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatRoomService::DeleteAdministrator(uint32_t administratorId, uint32_t roomId) { + sqlite3_stmt* stmt; + char sql[] = "DELETE FROM room_administrator WHERE administrator_avatar_id = @administrator_avatar_id AND room_id = @room_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int administratorAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@administrator_avatar_id"); + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + + sqlite3_bind_int(stmt, administratorAvatarIdIdx, administratorId); + sqlite3_bind_int(stmt, roomIdIdx, roomId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatRoomService::LoadBanned(ChatRoom * room) { + sqlite3_stmt* stmt; + char sql[] = "SELECT banned_avatar_id FROM room_ban WHERE room_id = @room_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + sqlite3_bind_int(stmt, roomIdIdx, room->GetRoomId()); + + while (sqlite3_step(stmt) == SQLITE_ROW) { + uint32_t bannedId = sqlite3_column_int(stmt, 0); + room->banned_.push_back(avatarService_->GetAvatar(bannedId)); + } +} + +void ChatRoomService::PersistBanned(uint32_t bannedId, uint32_t roomId) { + sqlite3_stmt* stmt; + char sql[] = "INSERT OR IGNORE INTO room_ban (banned_avatar_id, room_id) VALUES (@banned_avatar_id, @room_id)"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int bannedAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@moderator_avatar_id"); + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + + sqlite3_bind_int(stmt, bannedAvatarIdIdx, bannedId); + sqlite3_bind_int(stmt, roomIdIdx, roomId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} + +void ChatRoomService::DeleteBanned(uint32_t bannedId, uint32_t roomId) { + sqlite3_stmt* stmt; + char sql[] = "DELETE FROM room_ban WHERE banned_avatar_id = @banned_avatar_id AND room_id = @room_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int bannedAvatarIdIdx = sqlite3_bind_parameter_index(stmt, "@banned_avatar_id"); + int roomIdIdx = sqlite3_bind_parameter_index(stmt, "@room_id"); + + sqlite3_bind_int(stmt, bannedAvatarIdIdx, bannedId); + sqlite3_bind_int(stmt, roomIdIdx, roomId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } +} diff --git a/src/ChatRoomService.hpp b/src/ChatRoomService.hpp new file mode 100644 index 0000000..dfd1cf1 --- /dev/null +++ b/src/ChatRoomService.hpp @@ -0,0 +1,57 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "ChatRoom.hpp" + +#include + +#include +#include +#include +#include + +struct sqlite3; + +class ChatAvatarService; + +class ChatRoomService { +public: + ChatRoomService(ChatAvatarService* avatarService, sqlite3* db); + ~ChatRoomService(); + + void LoadRoomsFromStorage(const std::u16string& baseAddress); + + ChatRoom* CreateRoom(const ChatAvatar* creator, + const std::u16string& roomName, const std::u16string& roomTopic, + const std::u16string& roomPassword, uint32_t roomAttributes, uint32_t maxRoomSize, + const std::u16string& roomAddress, const std::u16string& srcAddress); + + void DestroyRoom(ChatRoom* room); + + ChatResultCode PersistNewRoom(ChatRoom& avatar); + + std::vector GetRoomSummaries( + const std::u16string& startNode, const std::u16string& filter = u""); + + bool RoomExists(const std::u16string& roomAddress) const; + ChatRoom* GetRoom(const std::u16string& roomAddress); + +private: + friend class ChatRoom; + void DeleteRoom(ChatRoom* room); + void LoadModerators(ChatRoom* room); + void PersistModerator(uint32_t moderatorId, uint32_t roomId); + void DeleteModerator(uint32_t moderatorId, uint32_t roomId); + void LoadAdministrators(ChatRoom* room); + void PersistAdministrator(uint32_t administratorId, uint32_t roomId); + void DeleteAdministrator(uint32_t administratorId, uint32_t roomId); + void LoadBanned(ChatRoom* room); + void PersistBanned(uint32_t bannedId, uint32_t roomId); + void DeleteBanned(uint32_t bannedId, uint32_t roomId); + + uint32_t nextRoomId_ = 0; + std::vector> rooms_; + ChatAvatarService* avatarService_; + sqlite3* db_; +}; diff --git a/src/Contact.hpp b/src/Contact.hpp new file mode 100644 index 0000000..18c2789 --- /dev/null +++ b/src/Contact.hpp @@ -0,0 +1,38 @@ + +#pragma once + +#include "Serialization.hpp" + +#include + +class ChatAvatar; + +struct FriendContact { + FriendContact(const ChatAvatar* frnd_, const std::wstring& comment_) + : frnd{frnd_} + , comment{comment_} {} + + const ChatAvatar* frnd; + std::wstring comment = L""; +}; + +template +void write(StreamT& ar, const FriendContact& data) { + write(ar, data.frnd->GetName()); + write(ar, data.frnd->GetAddress()); + write(ar, data.comment); + write(ar, static_cast(data.frnd->IsOnline() ? 1 : 0)); +} + +struct IgnoreContact { + IgnoreContact(const ChatAvatar* ignored_) + : ignored{ignored_} {} + + const ChatAvatar* ignored; +}; + +template +void write(StreamT& ar, const IgnoreContact& data) { + write(ar, data.ignored->GetName()); + write(ar, data.ignored->GetAddress()); +} diff --git a/src/GatewayClient.cpp b/src/GatewayClient.cpp new file mode 100644 index 0000000..41c2626 --- /dev/null +++ b/src/GatewayClient.cpp @@ -0,0 +1,245 @@ + +#include "GatewayClient.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatEnums.hpp" +#include "ChatRoomService.hpp" +#include "GatewayNode.hpp" +#include "Message.hpp" +#include "PersistentMessageService.hpp" +#include "SQLite3.hpp" +#include "StationChatConfig.hpp" +#include "UdpLibrary.hpp" + +#include "protocol/AddBan.hpp" +#include "protocol/AddFriend.hpp" +#include "protocol/AddIgnore.hpp" +#include "protocol/AddInvite.hpp" +#include "protocol/AddModerator.hpp" +#include "protocol/CreateRoom.hpp" +#include "protocol/DestroyRoom.hpp" +#include "protocol/EnterRoom.hpp" +#include "protocol/FailoverReLoginAvatar.hpp" +#include "protocol/FriendStatus.hpp" +#include "protocol/GetAnyAvatar.hpp" +#include "protocol/GetPersistentHeaders.hpp" +#include "protocol/GetPersistentMessage.hpp" +#include "protocol/GetRoom.hpp" +#include "protocol/GetRoomSummaries.hpp" +#include "protocol/IgnoreStatus.hpp" +#include "protocol/KickAvatar.hpp" +#include "protocol/LeaveRoom.hpp" +#include "protocol/LoginAvatar.hpp" +#include "protocol/LogoutAvatar.hpp" +#include "protocol/RemoveBan.hpp" +#include "protocol/RemoveFriend.hpp" +#include "protocol/RemoveIgnore.hpp" +#include "protocol/RemoveInvite.hpp" +#include "protocol/RemoveModerator.hpp" +#include "protocol/SendInstantMessage.hpp" +#include "protocol/SendPersistentMessage.hpp" +#include "protocol/SendRoomMessage.hpp" +#include "protocol/SetApiVersion.hpp" +#include "protocol/SetAvatarAttributes.hpp" +#include "protocol/UpdatePersistentMessage.hpp" + +#include "easylogging++.h" + +GatewayClient::GatewayClient(UdpConnection* connection, GatewayNode* node) + : NodeClient(connection) + , node_{node} + , avatarService_{node->GetAvatarService()} + , roomService_{node->GetRoomService()} + , messageService_{node->GetMessageService()} { + connection->SetHandler(this); +} + +GatewayClient::~GatewayClient() {} + +void GatewayClient::OnIncoming(std::istringstream& istream) { + ChatRequestType request_type = ::read(istream); + + switch (request_type) { + case ChatRequestType::LOGINAVATAR: + HandleIncomingMessage(istream); + break; + case ChatRequestType::LOGOUTAVATAR: + HandleIncomingMessage(istream); + break; + case ChatRequestType::CREATEROOM: + HandleIncomingMessage(istream); + break; + case ChatRequestType::DESTROYROOM: + HandleIncomingMessage(istream); + break; + case ChatRequestType::SENDINSTANTMESSAGE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::SENDROOMMESSAGE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::ADDFRIEND: + HandleIncomingMessage(istream); + break; + case ChatRequestType::REMOVEFRIEND: + HandleIncomingMessage(istream); + break; + case ChatRequestType::FRIENDSTATUS: + HandleIncomingMessage(istream); + break; + case ChatRequestType::ADDIGNORE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::REMOVEIGNORE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::ENTERROOM: + HandleIncomingMessage(istream); + break; + case ChatRequestType::LEAVEROOM: + HandleIncomingMessage(istream); + break; + case ChatRequestType::ADDMODERATOR: + HandleIncomingMessage(istream); + break; + case ChatRequestType::REMOVEMODERATOR: + HandleIncomingMessage(istream); + break; + case ChatRequestType::ADDBAN: + HandleIncomingMessage(istream); + break; + case ChatRequestType::REMOVEBAN: + HandleIncomingMessage(istream); + break; + case ChatRequestType::ADDINVITE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::REMOVEINVITE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::KICKAVATAR: + HandleIncomingMessage(istream); + break; + case ChatRequestType::GETROOM: + HandleIncomingMessage(istream); + break; + case ChatRequestType::GETROOMSUMMARIES: + HandleIncomingMessage(istream); + break; + case ChatRequestType::SENDPERSISTENTMESSAGE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::GETPERSISTENTHEADERS: + HandleIncomingMessage(istream); + break; + case ChatRequestType::GETPERSISTENTMESSAGE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::UPDATEPERSISTENTMESSAGE: + HandleIncomingMessage(istream); + break; + case ChatRequestType::IGNORESTATUS: + HandleIncomingMessage(istream); + break; + case ChatRequestType::FAILOVER_RELOGINAVATAR: + HandleIncomingMessage(istream); + break; + case ChatRequestType::SETAPIVERSION: + HandleIncomingMessage(istream); + break; + case ChatRequestType::SETAVATARATTRIBUTES: + HandleIncomingMessage(istream); + break; + case ChatRequestType::GETANYAVATAR: + HandleIncomingMessage(istream); + break; + default: + LOG(INFO) << "Unknown request type received: " << static_cast(request_type); + break; + } +} + +void GatewayClient::SendFriendLoginUpdate( + const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar) { + node_->SendTo( + srcAvatar->GetAddress(), MFriendLogin{destAvatar, destAvatar->GetAddress(), + srcAvatar->GetAvatarId(), destAvatar->GetStatusMessage()}); +} + +void GatewayClient::SendFriendLoginUpdates(const ChatAvatar* avatar) { + auto as = node_->GetAvatarService(); + auto& onlineAvatars = as->GetOnlineAvatars(); + for (auto onlineAvatar : onlineAvatars) { + if (onlineAvatar->IsFriend(avatar)) { + SendFriendLoginUpdate(onlineAvatar, avatar); + } + } + + for (auto& contact : avatar->GetFriendList()) { + if (contact.frnd->IsOnline()) { + Send(MFriendLogin{contact.frnd, contact.frnd->GetAddress(), avatar->GetAvatarId(), + contact.frnd->GetStatusMessage()}); + } + } +} + +void GatewayClient::SendFriendLogoutUpdates(const ChatAvatar* avatar) { + auto& onlineAvatars = avatarService_->GetOnlineAvatars(); + for (auto onlineAvatar : onlineAvatars) { + if (onlineAvatar->IsFriend(avatar)) { + node_->SendTo(onlineAvatar->GetAddress(), + MFriendLogout{avatar, avatar->GetAddress(), onlineAvatar->GetAvatarId()}); + } + } +} + +void GatewayClient::SendDestroyRoomUpdate( + const ChatAvatar* srcAvatar, uint32_t roomId, std::vector targets) { + for (auto& address : targets) { + node_->SendTo(address, MDestroyRoom{srcAvatar, roomId}); + } +} + +void GatewayClient::SendInstantMessageUpdate(const ChatAvatar* srcAvatar, + const ChatAvatar* destAvatar, const std::u16string& message, const std::u16string& oob) { + node_->SendTo(destAvatar->GetAddress(), + MInstantMessage{srcAvatar, destAvatar->GetAvatarId(), message, oob}); +} + +void GatewayClient::SendRoomMessageUpdate(const ChatAvatar* srcAvatar, const ChatRoom* room, + uint32_t messageId, const std::u16string& message, const std::u16string& oob) { + auto connectedAddresses = room->GetConnectedAddresses(); + for (auto& address : connectedAddresses) { + node_->SendTo(address, MRoomMessage{srcAvatar, room->GetRoomId(), room->GetAvatarIds(), + message, oob, messageId}); + } +} + +void GatewayClient::SendEnterRoomUpdate(const ChatAvatar* srcAvatar, const ChatRoom* room) { + for (const auto& address : room->GetConnectedAddresses()) { + node_->SendTo(address, MEnterRoom{srcAvatar, room->GetRoomId()}); + } +} + +void GatewayClient::SendLeaveRoomUpdate( + const std::vector& addresses, uint32_t srcAvatarId, uint32_t roomId) { + for (const auto& address : addresses) { + node_->SendTo(address, MLeaveRoom{srcAvatarId, roomId}); + } +} + +void GatewayClient::SendPersistentMessageUpdate( + const ChatAvatar* destAvatar, const PersistentHeader& header) { + if (destAvatar) { + node_->SendTo( + destAvatar->GetAddress(), MPersistentMessage{destAvatar->GetAvatarId(), header}); + } +} + +void GatewayClient::SendKickAvatarUpdate(const std::vector& addresses, + const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar, const ChatRoom* room) { + for (const auto& address : addresses) { + node_->SendTo(address, + MKickAvatar{srcAvatar, destAvatar, room->GetRoomName(), room->GetRoomAddress()}); + } +} diff --git a/src/GatewayClient.hpp b/src/GatewayClient.hpp new file mode 100644 index 0000000..b65c5b0 --- /dev/null +++ b/src/GatewayClient.hpp @@ -0,0 +1,69 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "NodeClient.hpp" +#include "SQLite3.hpp" +#include "easylogging++.h" + +class ChatAvatar; +class ChatAvatarService; +class ChatRoom; +class ChatRoomService; +class GatewayNode; +class PersistentMessageService; +class UdpConnection; + +struct PersistentHeader; + +struct ReqSetAvatarAttributes; +struct ReqGetAnyAvatar; + +class GatewayClient : public NodeClient { +public: + GatewayClient(UdpConnection* connection, GatewayNode* node); + virtual ~GatewayClient(); + + GatewayNode* GetNode() { return node_; } + + void SendFriendLoginUpdate(const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar); + void SendFriendLoginUpdates(const ChatAvatar* avatar); + void SendFriendLogoutUpdates(const ChatAvatar* avatar); + void SendDestroyRoomUpdate(const ChatAvatar* srcAvatar, uint32_t roomId, std::vector targets); + void SendInstantMessageUpdate(const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar, const std::u16string& message, const std::u16string& oob); + void SendRoomMessageUpdate(const ChatAvatar* srcAvatar, const ChatRoom* room, uint32_t messageId, const std::u16string& message, const std::u16string& oob); + void SendEnterRoomUpdate(const ChatAvatar* srcAvatar, const ChatRoom* room); + void SendLeaveRoomUpdate(const std::vector& addresses, uint32_t srcAvatarId, uint32_t roomId); + void SendPersistentMessageUpdate(const ChatAvatar* destAvatar, const PersistentHeader& header); + void SendKickAvatarUpdate(const std::vector& addresses, const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar, const ChatRoom* room); + +private: + void OnIncoming(std::istringstream& istream) override; + + template + void HandleIncomingMessage(StreamT& istream) { + typedef typename HandlerT::RequestType RequestT; + typedef typename HandlerT::ResponseType ResponseT; + + RequestT request; + read(istream, request); + ResponseT response(request.track); + + try { + HandlerT(this, request, response); + } catch (const ChatResultException& e) { + response.result = e.code; + LOG(ERROR) << "ChatAPI Error: [" << ToString(e.code) << "] " << e.message; + } catch (const SQLite3Exception& e) { + response.result = ChatResultCode::DATABASE; + LOG(ERROR) << "Database Error: [" << e.code << "] " << e.message; + } + + Send(response); + } + + GatewayNode* node_; + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; + PersistentMessageService* messageService_; +}; diff --git a/src/GatewayNode.cpp b/src/GatewayNode.cpp new file mode 100644 index 0000000..eb730b4 --- /dev/null +++ b/src/GatewayNode.cpp @@ -0,0 +1,39 @@ + +#include "GatewayNode.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "PersistentMessageService.hpp" +#include "StationChatConfig.hpp" + +#include + +GatewayNode::GatewayNode(StationChatConfig& config) + : Node(this, config.gatewayAddress, config.gatewayPort) + , config_{config} { + if (sqlite3_open(config.chatDatabasePath.c_str(), &db_) != SQLITE_OK) { + throw std::runtime_error("Can't open database: " + std::string{sqlite3_errmsg(db_)}); + } + + avatarService_ = std::make_unique(db_); + roomService_ = std::make_unique(avatarService_.get(), db_); + messageService_ = std::make_unique(db_); +} + +GatewayNode::~GatewayNode() { sqlite3_close(db_); } + +ChatAvatarService* GatewayNode::GetAvatarService() { return avatarService_.get(); } + +ChatRoomService* GatewayNode::GetRoomService() { return roomService_.get(); } + +PersistentMessageService* GatewayNode::GetMessageService() { + return messageService_.get(); +} + +StationChatConfig& GatewayNode::GetConfig() { return config_; } + +void GatewayNode::RegisterClientAddress(const std::u16string & address, GatewayClient * client) { + clientAddressMap_[address] = client; +} + +void GatewayNode::OnTick() {} diff --git a/src/GatewayNode.hpp b/src/GatewayNode.hpp new file mode 100644 index 0000000..c53f32b --- /dev/null +++ b/src/GatewayNode.hpp @@ -0,0 +1,45 @@ + +#pragma once + +#include "Node.hpp" +#include "GatewayClient.hpp" + +#include +#include + +class ChatAvatarService; +class ChatRoomService; +class PersistentMessageService; +struct StationChatConfig; +struct sqlite3; + +class GatewayNode : public Node { +public: + explicit GatewayNode(StationChatConfig& config); + ~GatewayNode(); + + ChatAvatarService* GetAvatarService(); + ChatRoomService* GetRoomService(); + PersistentMessageService* GetMessageService(); + StationChatConfig& GetConfig(); + + void RegisterClientAddress(const std::u16string& address, GatewayClient* client); + + template + void SendTo(const std::u16string& address, const MessageT& message) { + auto find_iter = clientAddressMap_.find(address); + if (find_iter != std::end(clientAddressMap_)) { + find_iter->second->Send(message); + } + } + +private: + void OnTick() override; + + std::unique_ptr avatarService_; + std::unique_ptr roomService_; + std::unique_ptr messageService_; + std::map clientAddressMap_; + StationChatConfig& config_; + sqlite3* db_; +}; diff --git a/src/Message.hpp b/src/Message.hpp new file mode 100644 index 0000000..052647d --- /dev/null +++ b/src/Message.hpp @@ -0,0 +1,298 @@ + +#pragma once + +#include "ChatAvatar.hpp" +#include "PersistentMessage.hpp" + +#include +#include + +enum class ChatMessageType : uint16_t { + // ChatAvatar message types + INSTANTMESSAGE = 0, // 0 + ROOMMESSAGE, + BROADCASTMESSAGE, + FRIENDLOGIN, + FRIENDLOGOUT, + KICKROOM, // 5 + + // ChatRoom message types + ADDMODERATORROOM, + REMOVEMODERATORROOM, + REMOVEMODERATORAVATAR, + ADDBANROOM, + REMOVEBANROOM, // 10 + REMOVEBANAVATAR, + ADDINVITEROOM, + ADDINVITEAVATAR, + REMOVEINVITEROOM, + REMOVEINVITEAVATAR, // 15 + ENTERROOM, + LEAVEROOM, + DESTROYROOM, + SETROOMPARAMS, + PERSISTENTMESSAGE, // 20 + FORCEDLOGOUT, + UNREGISTERROOMREADY, + KICKAVATAR, + ADDMODERATORAVATAR, + ADDBANAVATAR, // 25 + ADDADMIN, + REMOVEADMIN, + FRIENDCONFIRMREQUEST, + FRIENDCONFIRMRESPONSE, + CHANGEROOMOWNER, // 30 + FORCEROOMFAILOVER, + ADDTEMPORARYMODERATORROOM, + ADDTEMPORARYMODERATORAVATAR, + REMOVETEMPORARYMODERATORROOM, + REMOVETEMPORARYMODERATORAVATAR, // 35 + GRANTVOICEROOM, + GRANTVOICEAVATAR, + REVOKEVOICEROOM, + REVOKEVOICEAVATAR, + SNOOP, // 40 + UIDLIST, + REQUESTROOMENTRY, + DELAYEDROOMENTRY, + DENIEDROOMENTRY, + FRIENDSTATUS, // 45 + FRIENDCONFIRMRECIPROCATE_REQUEST, + FRIENDCONFIRMRECIPROCATE_RESPONSE, + FILTERMESSAGE, + FAILOVER_AVATAR_LIST, + NOTIFY_FRIENDS_LIST_CHANGE, // 50 + NOTIFY_FRIEND_IS_REMOVED +}; + +/** Begin INSTANTMESSAGE */ + +struct MInstantMessage { + MInstantMessage(const ChatAvatar* srcAvatar_, uint32_t destAvatarId_, + const std::u16string& message_, const std::u16string& oob_) + : srcAvatar{srcAvatar_} + , destAvatarId{destAvatarId_} + , message{message_} + , oob{oob_} {} + + const ChatMessageType type = ChatMessageType::INSTANTMESSAGE; + const uint32_t track = 0; + const ChatAvatar* srcAvatar; + uint32_t destAvatarId; + std::u16string message; + std::u16string oob; +}; + +template +void write(StreamT& ar, const MInstantMessage& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.srcAvatar); + write(ar, data.destAvatarId); + write(ar, data.message); + write(ar, data.oob); +} + +/** Begin ROOMMESSAGE */ + +struct MRoomMessage { + MRoomMessage(const ChatAvatar* srcAvatar_, uint32_t roomId_, std::vector destList_, + const std::u16string& message_, const std::u16string& oob_, uint32_t messageId_) + : srcAvatar{srcAvatar_} + , roomId{roomId_} + , destList{destList_} + , message{message_} + , oob{oob_} + , messageId{messageId_} {} + + const ChatMessageType type = ChatMessageType::ROOMMESSAGE; + const uint32_t track = 0; + const ChatAvatar* srcAvatar; + uint32_t roomId; + std::vector destList; // list of destination avatars to see the message + std::u16string message; + std::u16string oob; + uint32_t messageId = 0; +}; + +template +void write(StreamT& ar, const MRoomMessage& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.srcAvatar); + write(ar, data.roomId); + + write(ar, static_cast(data.destList.size())); + for (auto destAvatarId : data.destList) { + write(ar, destAvatarId); + } + + write(ar, data.message); + write(ar, data.oob); + write(ar, data.messageId); +} + +/** Begin FRIENDLOGIN */ + +struct MFriendLogin { + MFriendLogin(const ChatAvatar* avatar_, const std::u16string& friendAddress_, + uint32_t destAvatarId_, const std::u16string& friendStatus_) + : avatar{avatar_} + , friendAddress{friendAddress_} + , destAvatarId{destAvatarId_} + , friendStatus{friendStatus_} {} + + const ChatMessageType type = ChatMessageType::FRIENDLOGIN; + const uint32_t track = 0; + const ChatAvatar* avatar; + std::u16string friendAddress; + uint32_t destAvatarId; + std::u16string friendStatus; +}; + +template +void write(StreamT& ar, const MFriendLogin& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.avatar); + write(ar, data.friendAddress); + write(ar, data.destAvatarId); + write(ar, data.friendStatus); +} + +/** Begin FRIENDLOGOUT */ + +struct MFriendLogout { + MFriendLogout( + const ChatAvatar* avatar_, const std::u16string& friendAddress_, uint32_t destAvatarId_) + : avatar{avatar_} + , friendAddress{friendAddress_} + , destAvatarId{destAvatarId_} {} + + const ChatMessageType type = ChatMessageType::FRIENDLOGOUT; + const uint32_t track = 0; + const ChatAvatar* avatar; + uint32_t destAvatarId; + std::u16string friendAddress; +}; + +template +void write(StreamT& ar, const MFriendLogout& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.avatar); + write(ar, data.friendAddress); + write(ar, data.destAvatarId); +} + +/** Begin ENTERROOM */ + +struct MEnterRoom { + MEnterRoom(const ChatAvatar* srcAvatar_, uint32_t roomId_) + : srcAvatar{srcAvatar_} + , roomId{roomId_} {} + + const ChatMessageType type = ChatMessageType::ENTERROOM; + const uint32_t track = 0; + const ChatAvatar* srcAvatar; + uint32_t roomId; +}; + +template +void write(StreamT& ar, const MEnterRoom& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.srcAvatar); + write(ar, data.roomId); +} + +/** Begin LEAVEROOM */ + +struct MLeaveRoom { + MLeaveRoom(uint32_t avatarId_, uint32_t roomId_) + : avatarId{avatarId_} + , roomId{roomId_} {} + + const ChatMessageType type = ChatMessageType::LEAVEROOM; + const uint32_t track = 0; + uint32_t avatarId; + uint32_t roomId; +}; + +template +void write(StreamT& ar, const MLeaveRoom& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.avatarId); + write(ar, data.roomId); +} + +/** Begin DESTROYROOM */ + +struct MDestroyRoom { + MDestroyRoom(const ChatAvatar* srcAvatar_, uint32_t roomId_) + : srcAvatar{srcAvatar_} + , roomId{roomId_} {} + + const ChatMessageType type = ChatMessageType::DESTROYROOM; + const uint32_t track = 0; + const ChatAvatar* srcAvatar; + uint32_t roomId; +}; + +template +void write(StreamT& ar, const MDestroyRoom& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.srcAvatar); + write(ar, data.roomId); +} + +/** Begin PERSISTENTMESSAGE */ + +struct MPersistentMessage { + MPersistentMessage(uint32_t destAvatarId_, PersistentHeader header_) + : destAvatarId{destAvatarId_} + , header{header_} {} + + const ChatMessageType type = ChatMessageType::PERSISTENTMESSAGE; + const uint32_t track = 0; + uint32_t destAvatarId; + PersistentHeader header; +}; + +template +void write(StreamT& ar, const MPersistentMessage& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.destAvatarId); + write(ar, data.header); +} + +/** Begin KICKAVATAR */ + +struct MKickAvatar { + MKickAvatar(const ChatAvatar* srcAvatar_, const ChatAvatar* destAvatar_, + const std::u16string& roomName_, const std::u16string& roomAddress_) + : srcAvatar{srcAvatar_} + , destAvatar{destAvatar_} + , roomName{roomName_} + , roomAddress{roomAddress_} {} + + const ChatMessageType type = ChatMessageType::KICKAVATAR; + const uint32_t track = 0; + const ChatAvatar* srcAvatar; + const ChatAvatar* destAvatar; + std::u16string roomName; + std::u16string roomAddress; +}; + +template +void write(StreamT& ar, const MKickAvatar& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.srcAvatar); + write(ar, data.destAvatar); + write(ar, data.roomName); + write(ar, data.roomAddress); +} diff --git a/src/Node.hpp b/src/Node.hpp new file mode 100644 index 0000000..6d3d451 --- /dev/null +++ b/src/Node.hpp @@ -0,0 +1,52 @@ + +#pragma once + +#include "UdpLibrary.hpp" + +#include +#include +#include +#include + +template +class Node : public UdpManagerHandler { +public: + explicit Node(NodeT* node, const std::string& listenAddress, uint16_t listenPort) + : node_{node} { + + UdpManager::Params params; + params.handler = this; + params.port = listenPort; + + udpManager_ = new UdpManager(¶ms); + } + + virtual ~Node() { udpManager_->Release(); } + + void Tick() { + udpManager_->GiveTime(); + + auto remove_iter + = std::remove_if(std::begin(clients_), std::end(clients_), [](auto& client) { + return client->GetConnection()->GetStatus() == UdpConnection::cStatusDisconnected; + }); + + if (remove_iter != std::end(clients_)) + clients_.erase(remove_iter); + + OnTick(); + } + +private: + virtual void OnTick() = 0; + + void OnConnectRequest(UdpConnection* connection) override { + AddClient(std::make_unique(connection, node_)); + } + + void AddClient(std::unique_ptr client) { clients_.push_back(std::move(client)); } + + std::vector> clients_; + NodeT* node_; + UdpManager* udpManager_; +}; diff --git a/src/NodeClient.cpp b/src/NodeClient.cpp new file mode 100644 index 0000000..e8d3fd0 --- /dev/null +++ b/src/NodeClient.cpp @@ -0,0 +1,30 @@ + +#include "NodeClient.hpp" +#include "StreamUtils.hpp" + +NodeClient::NodeClient(UdpConnection* connection) + : connection_{connection} + , ostream_{std::stringstream::out | std::stringstream::binary} + , istream_{std::stringstream::in | std::stringstream::binary} { + connection_->AddRef(); +} + +NodeClient::~NodeClient() { + connection_->SetHandler(nullptr); + connection_->Disconnect(); + connection_->Release(); +} + +void NodeClient::Send(const char* data, uint32_t length) { + logNetworkMessage( + connection_, "Message To ->", reinterpret_cast(data), length); + connection_->Send(cUdpChannelReliable1, data, length); +} + +void NodeClient::OnRoutePacket(UdpConnection* connection, const uchar* data, int length) { + logNetworkMessage(connection, "Message From <-", data, length); + + istream_.clear(); + istream_.str({reinterpret_cast(data), static_cast(length)}); + OnIncoming(istream_); +} diff --git a/src/NodeClient.hpp b/src/NodeClient.hpp new file mode 100644 index 0000000..c779266 --- /dev/null +++ b/src/NodeClient.hpp @@ -0,0 +1,35 @@ + +#pragma once + +#include "UdpLibrary.hpp" + +#include + +class NodeClient : public UdpConnectionHandler { +public: + explicit NodeClient(UdpConnection* connection); + + virtual ~NodeClient(); + + template + void Send(const T& message) { + ostream_.clear(); + ostream_.str(""); + write(ostream_, message); + auto data = ostream_.str(); + Send(data.c_str(), data.length()); + } + + UdpConnection* GetConnection() { return connection_; } + +private: + void Send(const char* data, uint32_t length); + + virtual void OnIncoming(std::istringstream& istream) = 0; + + void OnRoutePacket(UdpConnection* connection, const uchar* data, int length) override; + + std::ostringstream ostream_; + std::istringstream istream_; + UdpConnection* connection_; +}; diff --git a/src/PersistentMessage.hpp b/src/PersistentMessage.hpp new file mode 100644 index 0000000..2e5d0f2 --- /dev/null +++ b/src/PersistentMessage.hpp @@ -0,0 +1,51 @@ + +#pragma once + +#include +#include + +enum class PersistentState : uint32_t { + NEW = 1, + UNREAD, + READ, + TRASH, + DELETED +}; + +struct PersistentHeader { + uint32_t messageId = 0; + uint32_t avatarId; + std::u16string fromName; + std::u16string fromAddress; + std::u16string subject; + uint32_t sentTime = 0; + PersistentState status = PersistentState::NEW; + std::u16string folder = u""; + std::u16string category = u""; +}; + +struct PersistentMessage { + PersistentHeader header; + std::u16string message; + std::u16string oob; +}; + + +template +void write(StreamT& ar, const PersistentHeader& data) { + write(ar, data.messageId); + write(ar, data.avatarId); + write(ar, data.fromName); + write(ar, data.fromAddress); + write(ar, data.subject); + write(ar, data.sentTime); + write(ar, data.status); +} + + +template +void write(StreamT& ar, const PersistentMessage& data) { + write(ar, data.header); + write(ar, data.message); + write(ar, data.oob); +} diff --git a/src/PersistentMessageService.cpp b/src/PersistentMessageService.cpp new file mode 100644 index 0000000..3f22d3d --- /dev/null +++ b/src/PersistentMessageService.cpp @@ -0,0 +1,210 @@ +#include "PersistentMessageService.hpp" + +#include "SQLite3.hpp" +#include "StringUtils.hpp" + + +PersistentMessageService::PersistentMessageService(sqlite3* db) + : db_{db} {} + +PersistentMessageService::~PersistentMessageService() {} + +void PersistentMessageService::StoreMessage(PersistentMessage& message) { + sqlite3_stmt* stmt; + + char sql[] = "INSERT INTO persistent_message (avatar_id, from_name, from_address, subject, " + "sent_time, status, " + "folder, category, message, oob) VALUES (@avatar_id, @from_name, @from_address, " + "@subject, @sent_time, @status, @folder, @category, @message, @oob)"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + int fromNameIdx = sqlite3_bind_parameter_index(stmt, "@from_name"); + int fromAddressIdx = sqlite3_bind_parameter_index(stmt, "@from_address"); + int subjectIdx = sqlite3_bind_parameter_index(stmt, "@subject"); + int sentTimeIdx = sqlite3_bind_parameter_index(stmt, "@sent_time"); + int statusIdx = sqlite3_bind_parameter_index(stmt, "@status"); + int folderIdx = sqlite3_bind_parameter_index(stmt, "@folder"); + int categoryIdx = sqlite3_bind_parameter_index(stmt, "@category"); + int messageIdx = sqlite3_bind_parameter_index(stmt, "@message"); + int oobIdx = sqlite3_bind_parameter_index(stmt, "@oob"); + + sqlite3_bind_int(stmt, avatarIdIdx, message.header.avatarId); + + std::string fromName = FromWideString(message.header.fromName); + sqlite3_bind_text(stmt, fromNameIdx, fromName.c_str(), -1, 0); + + std::string fromAddress = FromWideString(message.header.fromAddress); + sqlite3_bind_text(stmt, fromAddressIdx, fromAddress.c_str(), -1, 0); + + std::string subject = FromWideString(message.header.subject); + sqlite3_bind_text(stmt, subjectIdx, subject.c_str(), -1, 0); + + sqlite3_bind_int(stmt, sentTimeIdx, message.header.sentTime); + sqlite3_bind_int(stmt, statusIdx, static_cast(message.header.status)); + + std::string folder = FromWideString(message.header.folder); + sqlite3_bind_text(stmt, folderIdx, folder.c_str(), -1, 0); + + std::string category = FromWideString(message.header.category); + sqlite3_bind_text(stmt, categoryIdx, category.c_str(), -1, 0); + + std::string msg = FromWideString(message.message); + sqlite3_bind_text(stmt, messageIdx, msg.c_str(), -1, 0); + + sqlite3_bind_blob(stmt, oobIdx, reinterpret_cast(message.oob.data()), message.oob.size() * 2, SQLITE_STATIC); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + message.header.messageId = static_cast(sqlite3_last_insert_rowid(db_)); +} + +std::vector PersistentMessageService::GetMessageHeaders(uint32_t avatarId) { + std::vector headers; + sqlite3_stmt* stmt; + + char sql[] = "SELECT id, avatar_id, from_name, from_address, subject, sent_time, status, " + "folder, category, message, oob FROM persistent_message WHERE avatar_id = " + "@avatar_id AND status IN (1, 2, 3)"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + + sqlite3_bind_int(stmt, avatarIdIdx, avatarId); + + while (sqlite3_step(stmt) == SQLITE_ROW) { + PersistentHeader header; + + header.messageId = sqlite3_column_int(stmt, 0); + header.avatarId = sqlite3_column_int(stmt, 1); + + auto tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 2))); + header.fromName = std::u16string(std::begin(tmp), std::end(tmp)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 3))); + header.fromAddress = std::u16string(std::begin(tmp), std::end(tmp)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 4))); + header.subject = std::u16string(std::begin(tmp), std::end(tmp)); + + header.sentTime = sqlite3_column_int(stmt, 5); + header.status = static_cast(sqlite3_column_int(stmt, 6)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 7))); + header.folder = std::u16string(std::begin(tmp), std::end(tmp)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 8))); + header.category = std::u16string(std::begin(tmp), std::end(tmp)); + + headers.push_back(std::move(header)); + } + + return headers; +} + +PersistentMessage PersistentMessageService::GetPersistentMessage( + uint32_t avatarId, uint32_t messageId) { + sqlite3_stmt* stmt; + + char sql[] = "SELECT id, avatar_id, from_name, from_address, subject, sent_time, status, " + "folder, category, message, oob FROM persistent_message WHERE id = @message_id " + "AND avatar_id = @avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int messageIdIdx = sqlite3_bind_parameter_index(stmt, "@message_id"); + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + + sqlite3_bind_int(stmt, messageIdIdx, messageId); + sqlite3_bind_int(stmt, avatarIdIdx, avatarId); + + if (sqlite3_step(stmt) != SQLITE_ROW) { + throw ChatResultException{ChatResultCode::PMSGNOTFOUND}; + } + + std::string tmp; + + PersistentMessage message; + message.header.messageId = messageId; + message.header.avatarId = avatarId; + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 2))); + message.header.fromName = std::u16string(std::begin(tmp), std::end(tmp)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 3))); + message.header.fromAddress = std::u16string(std::begin(tmp), std::end(tmp)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 4))); + message.header.subject = std::u16string(std::begin(tmp), std::end(tmp)); + + message.header.sentTime = sqlite3_column_int(stmt, 5); + message.header.status = static_cast(sqlite3_column_int(stmt, 6)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 7))); + message.header.folder = std::u16string(std::begin(tmp), std::end(tmp)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 8))); + message.header.category = std::u16string(std::begin(tmp), std::end(tmp)); + + tmp = std::string(reinterpret_cast(sqlite3_column_text(stmt, 9))); + message.message = std::u16string(std::begin(tmp), std::end(tmp)); + + int size = sqlite3_column_bytes(stmt, 10); + const uint8_t* data = reinterpret_cast(sqlite3_column_blob(stmt, 10)); + + message.oob.resize(size / 2); + for (int i = 0; i < size/2; ++i) { + message.oob[i] = *reinterpret_cast(data + i*2); + } + + sqlite3_finalize(stmt); + + if (message.header.status == PersistentState::NEW) { + UpdateMessageStatus( + message.header.avatarId, message.header.messageId, PersistentState::READ); + } + + return message; +} + +void PersistentMessageService::UpdateMessageStatus( + uint32_t avatarId, uint32_t messageId, PersistentState status) { + sqlite3_stmt* stmt; + + char sql[] = "UPDATE persistent_message SET status = @status WHERE id = @message_id AND " + "avatar_id = @avatar_id"; + + auto result = sqlite3_prepare_v2(db_, sql, -1, &stmt, 0); + if (result != SQLITE_OK) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + int statusIdx = sqlite3_bind_parameter_index(stmt, "@status"); + int messageIdIdx = sqlite3_bind_parameter_index(stmt, "@message_id"); + int avatarIdIdx = sqlite3_bind_parameter_index(stmt, "@avatar_id"); + + sqlite3_bind_int(stmt, statusIdx, static_cast(status)); + sqlite3_bind_int(stmt, messageIdIdx, messageId); + sqlite3_bind_int(stmt, avatarIdIdx, avatarId); + + result = sqlite3_step(stmt); + if (result != SQLITE_DONE) { + throw SQLite3Exception{result, sqlite3_errmsg(db_)}; + } + + sqlite3_finalize(stmt); +} diff --git a/src/PersistentMessageService.hpp b/src/PersistentMessageService.hpp new file mode 100644 index 0000000..a61a812 --- /dev/null +++ b/src/PersistentMessageService.hpp @@ -0,0 +1,30 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "PersistentMessage.hpp" + +#include + +#include +#include + +struct sqlite3; + +class PersistentMessageService { +public: + explicit PersistentMessageService(sqlite3* db); + ~PersistentMessageService(); + + void StoreMessage(PersistentMessage& message); + + std::vector GetMessageHeaders(uint32_t avatarId); + + PersistentMessage GetPersistentMessage(uint32_t avatarId, uint32_t messageId); + + void UpdateMessageStatus( + uint32_t avatarId, uint32_t messageId, PersistentState status); + +private: + sqlite3* db_; +}; diff --git a/src/RegistrarClient.cpp b/src/RegistrarClient.cpp new file mode 100644 index 0000000..6ed137c --- /dev/null +++ b/src/RegistrarClient.cpp @@ -0,0 +1,45 @@ +#include "RegistrarClient.hpp" + +#include "ChatEnums.hpp" +#include "RegistrarNode.hpp" +#include "Serialization.hpp" +#include "StationChatConfig.hpp" +#include "StringUtils.hpp" + +#include "protocol/RegistrarGetChatServer.hpp" + +#include "easylogging++.h" + +RegistrarClient::RegistrarClient(UdpConnection* connection, RegistrarNode* node) + : NodeClient(connection) + , node_{node} { + connection->SetHandler(this); +} + +RegistrarClient::~RegistrarClient() {} + +RegistrarNode* RegistrarClient::GetNode() { return node_; } + +void RegistrarClient::OnIncoming(std::istringstream& istream) { + ChatRequestType request_type = ::read(istream); + + switch (request_type) { + case ChatRequestType::REGISTRAR_GETCHATSERVER: { + auto request = ::read(istream); + RegistrarGetChatServer::ResponseType response{request.track}; + + try { + RegistrarGetChatServer(this, request, response); + } catch (const ChatResultException& e) { + response.result = e.code; + LOG(ERROR) << "ChatAPI Error: [" << static_cast(e.code) << "] " << e.message; + } + + Send(response); + } break; + default: + LOG(ERROR) << "Invalid registrar message type received: " + << static_cast(request_type); + break; + } +} diff --git a/src/RegistrarClient.hpp b/src/RegistrarClient.hpp new file mode 100644 index 0000000..3a259c2 --- /dev/null +++ b/src/RegistrarClient.hpp @@ -0,0 +1,22 @@ + +#pragma once + +#include "NodeClient.hpp" + +class RegistrarNode; +class UdpConnection; + +struct ReqRegistrarGetChatServer; + +class RegistrarClient : public NodeClient { +public: + RegistrarClient(UdpConnection* connection, RegistrarNode* node); + virtual ~RegistrarClient(); + + RegistrarNode* GetNode(); + +private: + void OnIncoming(std::istringstream& istream) override; + + RegistrarNode* node_; +}; diff --git a/src/RegistrarNode.cpp b/src/RegistrarNode.cpp new file mode 100644 index 0000000..be77d72 --- /dev/null +++ b/src/RegistrarNode.cpp @@ -0,0 +1,17 @@ + +#include "RegistrarNode.hpp" + +#include "StationChatConfig.hpp" + +RegistrarNode::RegistrarNode(StationChatConfig& config) + : Node(this, config.registrarAddress, config.registrarPort) + , config_{config} {} + +RegistrarNode::~RegistrarNode() {} + +StationChatConfig& RegistrarNode::GetConfig() { + return config_; +} + +void RegistrarNode::OnTick() {} + diff --git a/src/RegistrarNode.hpp b/src/RegistrarNode.hpp new file mode 100644 index 0000000..10d35b8 --- /dev/null +++ b/src/RegistrarNode.hpp @@ -0,0 +1,20 @@ + +#pragma once + +#include "Node.hpp" +#include "RegistrarClient.hpp" + +struct StationChatConfig; + +class RegistrarNode : public Node { +public: + explicit RegistrarNode(StationChatConfig& config); + ~RegistrarNode(); + + StationChatConfig& GetConfig(); + +private: + void OnTick() override; + + StationChatConfig& config_; +}; diff --git a/src/SQLite3.hpp b/src/SQLite3.hpp new file mode 100644 index 0000000..924ee73 --- /dev/null +++ b/src/SQLite3.hpp @@ -0,0 +1,14 @@ + +#pragma once + +#include +#include + +struct SQLite3Exception { + int code; + std::string message; + + SQLite3Exception(const int result, char const * text) + : code{result} + , message{text} {} +}; diff --git a/src/Serialization.hpp b/src/Serialization.hpp new file mode 100644 index 0000000..7158fbd --- /dev/null +++ b/src/Serialization.hpp @@ -0,0 +1,119 @@ + +#pragma once + +#include +#include + +// integral types + +template ::value, int> = 0> +void read(StreamT& istream, T& value) { + istream.read(reinterpret_cast(&value), sizeof(T)); +} + +template ::value, int> = 0> +void write(StreamT& ostream, const T& value) { + ostream.write(reinterpret_cast(&value), sizeof(T)); +} + +// enumeration types with integral underlying types + +template ::value, int> = 0> + void read(StreamT& istream, T& value) { + istream.read(reinterpret_cast(&value), sizeof(T)); +} + +template ::value, int> = 0> + void write(StreamT& ostream, const T& value) { + ostream.write(reinterpret_cast(&value), sizeof(T)); +} + +// boolean types + +template +void read(StreamT& istream, bool& value) { + uint8_t boolAsInt; + read(istream, boolAsInt); + value = (boolAsInt != 0); +} + +template +void write(StreamT& ostream, const bool& value) { + uint8_t boolAsInt = value ? 1 : 0; + write(ostream, boolAsInt); +} + +// std::string types + +template +void read(StreamT& istream, std::string& value) { + uint16_t length; + read(istream, length); + + value.resize(length); + + istream.read(&value[0], length); +} + +template +void write(StreamT& ostream, const std::string& value) { + uint16_t length = static_cast(value.length()); + write(ostream, length); + + ostream.write(&value[0], length); +} + +// std::u16string types + +template +void read(StreamT& istream, std::u16string& value) { + uint32_t length; + read(istream, length); + + value.resize(length); + uint16_t tmp; + for (uint32_t i = 0; i < length; ++i) { + istream.read(reinterpret_cast(&tmp), sizeof(uint16_t)); + value[i] = tmp; + } +} + +template +void write(StreamT& ostream, const std::u16string& value) { + uint32_t length = static_cast(value.length()); + write(ostream, length); + + uint16_t tmp; + for (uint32_t i = 0; i < length; ++i) { + tmp = static_cast(value[i]); + ostream.write(reinterpret_cast(&tmp), sizeof(uint16_t)); + } +} + +// Specialized Read Types + +template +T read(StreamT& istream) { + T tmp; + read(istream, tmp); + return tmp; +} + +template +T readAt(StreamT& istream, size_t offset) { + istream.seekg(offset); + return read(istream); +} + +// Similar to readAt, but preserves the read position of the stream +template +T peekAt(StreamT& istream, size_t offset) { + auto pos = istream.tellg(); + T val = readAt(istream, offset); + istream.seekg(pos); + return val; +} diff --git a/src/StationChatApp.cpp b/src/StationChatApp.cpp new file mode 100644 index 0000000..8fe36f0 --- /dev/null +++ b/src/StationChatApp.cpp @@ -0,0 +1,17 @@ +#include "StationChatApp.hpp" + +#include "easylogging++.h" + +StationChatApp::StationChatApp(StationChatConfig config) + : config_{std::move(config)} { + registrarNode_ = std::make_unique(config_); + LOG(INFO) << "Registrar listening @" << config_.registrarAddress << ":" << config_.registrarPort; + + gatewayNode_ = std::make_unique(config_); + LOG(INFO) << "Gateway listening @" << config_.gatewayAddress << ":" << config_.gatewayPort; +} + +void StationChatApp::Tick() { + registrarNode_->Tick(); + gatewayNode_->Tick(); +} diff --git a/src/StationChatApp.hpp b/src/StationChatApp.hpp new file mode 100644 index 0000000..88c6d51 --- /dev/null +++ b/src/StationChatApp.hpp @@ -0,0 +1,25 @@ + +#pragma once + +#include "GatewayNode.hpp" +#include "RegistrarNode.hpp" +#include "StationChatConfig.hpp" + +#include +#include +#include + +class StationChatApp { +public: + explicit StationChatApp(StationChatConfig config); + + bool IsRunning() const { return isRunning_; } + + void Tick(); + +private: + StationChatConfig config_; + bool isRunning_ = true; + std::unique_ptr gatewayNode_; + std::unique_ptr registrarNode_; +}; diff --git a/src/StationChatConfig.hpp b/src/StationChatConfig.hpp new file mode 100644 index 0000000..3edc166 --- /dev/null +++ b/src/StationChatConfig.hpp @@ -0,0 +1,24 @@ + +#pragma once + +#include +#include + +struct StationChatConfig { + StationChatConfig() = default; + StationChatConfig(const std::string& gatewayAddress_, uint16_t gatewayPort_, + const std::string& registrarAddress_, uint16_t registrarPort_, const std::string& chatDatabasePath_) + : gatewayAddress{gatewayAddress_} + , gatewayPort{gatewayPort_} + , registrarAddress{registrarAddress_} + , registrarPort{registrarPort_} + , chatDatabasePath{chatDatabasePath_} {} + + const uint32_t version = 2; + std::string gatewayAddress; + uint16_t gatewayPort; + std::string registrarAddress; + uint16_t registrarPort; + std::string chatDatabasePath; + std::string loggerConfig; +}; diff --git a/src/StreamUtils.cpp b/src/StreamUtils.cpp new file mode 100644 index 0000000..912995c --- /dev/null +++ b/src/StreamUtils.cpp @@ -0,0 +1,75 @@ + +#include "StreamUtils.hpp" +#include "UdpLibrary.hpp" + +#include "easylogging++.h" + +#include + +std::ostream& operator<<(std::ostream& os, const BinaryData& bd) { + auto length = bd.length(); + auto data = bd.data(); + + if (length == 0) + return os; + + // Calculate the number of lines and extra bits. + auto lines = static_cast(length / 16); + auto extra = static_cast(length % 16); + + // Save the formatting state of the stream. + auto flags = os.flags(os.hex); + auto fill = os.fill('0'); + auto width = os.width(2); + + // The byte buffer should be printed out in lines of 16 characters and display + // both hex and ascii values for each character, see most hex editors for + // reference. + char ascii[17] = {0}; + unsigned char c; + for (int16_t i = 0; i <= lines; i++) { + // Print out a line number. + os << std::setw(4) << (i * 16) << ": "; + + for (int16_t j = 0; j < 16; ++j) { // Loop through the characters of this line (max 16) + // For the last line there may not be 16 characters. In this case filler + // whitespace should be added to keep column widths consistent. + if (i == lines && j >= extra) { + os << " "; + ascii[j] = ' '; + } else { + c = data[(i * 16) + j]; + + os << std::setw(2) << static_cast(c) << " "; + + // If an ascii char print it, otherwise print a . instead of gibberish + ascii[j] = (c < ' ' || c > '~') ? '.' : c; + } + } + + os << " " << ascii << "\n"; + } + + // Return formatting of stream to its previous state. + os.flags(flags); + os.fill(fill); + os.width(width); + + return os; +} + +void logNetworkMessage( + UdpConnection* connection, std::string message, const unsigned char* data, int length) { + char hold[256]; + + VLOG(1) << "\n" + << message << " " << connection->GetDestinationIp().GetAddress(hold) << ":" + << connection->GetDestinationPort() << " length: " << length << "\n" + << BinaryData{data, length}; +} + +std::ostream& operator<<(std::ostream& os, const std::u16string& data) { + os << std::string{std::begin(data), std::end(data)}; + + return os; +} diff --git a/src/StreamUtils.hpp b/src/StreamUtils.hpp new file mode 100644 index 0000000..7cda2f8 --- /dev/null +++ b/src/StreamUtils.hpp @@ -0,0 +1,28 @@ + +#pragma once + +#include +#include + +class UdpConnection; + +class BinaryData { +public: + BinaryData(const unsigned char* data, int length) + : data_{ data } + , length_{ length } + {} + + const unsigned char* data() const { return data_; } + int length() const { return length_; } + +private: + const unsigned char* data_; + int length_; +}; + +std::ostream& operator<<(std::ostream& os, const BinaryData& data); + +std::ostream& operator<<(std::ostream& os, const std::u16string& data); + +void logNetworkMessage(UdpConnection* connection, std::string message, const unsigned char* data, int length); diff --git a/src/StringUtils.cpp b/src/StringUtils.cpp new file mode 100644 index 0000000..4bf260f --- /dev/null +++ b/src/StringUtils.cpp @@ -0,0 +1,10 @@ + +#include "StreamUtils.hpp" + +std::string FromWideString(const std::u16string& str) { + return std::string{std::begin(str), std::end(str)}; +} + +std::u16string ToWideString(const std::string& str) { + return std::u16string{std::begin(str), std::end(str)}; +} diff --git a/src/StringUtils.hpp b/src/StringUtils.hpp new file mode 100644 index 0000000..94e3a99 --- /dev/null +++ b/src/StringUtils.hpp @@ -0,0 +1,8 @@ + +#pragma once + +#include + +std::string FromWideString(const std::u16string& str); + +std::u16string ToWideString(const std::string& str); diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..05da205 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,91 @@ + + +#define ELPP_DISABLE_DEFAULT_CRASH_HANDLING 1 +#define ELPP_DEFAULT_LOG_FILE "logs/swgchat.log" + +#include "easylogging++.h" + +#include "StationChatApp.hpp" + +#include + +#include +#include +#include +#include + +INITIALIZE_EASYLOGGINGPP + +StationChatConfig BuildConfiguration(int argc, char* argv[]); + +int main(int argc, char* argv[]) { + auto config = BuildConfiguration(argc, argv); + + el::Loggers::setDefaultConfigurations(config.loggerConfig, true); + START_EASYLOGGINGPP(argc, argv); + + StationChatApp app{config}; + + while (app.IsRunning()) { + app.Tick(); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + + return 0; +} + +StationChatConfig BuildConfiguration(int argc, char* argv[]) { + namespace po = boost::program_options; + StationChatConfig config; + std::string configFile; + + // Declare a group of options that will be + // allowed only on command line + po::options_description generic("Generic options"); + generic.add_options() + ("help,h", "produces help message") + ("config,c", po::value(&configFile)->default_value("swgchat.cfg"), + "sets path to the configuration file") + ("logger_config", po::value(&config.loggerConfig)->default_value("logger.cfg"), + "setspath to the logger configuration file") + ; + + po::options_description options("Configuration"); + options.add_options() + ("gateway_address", po::value(&config.gatewayAddress)->default_value("127.0.0.1"), + "address for gateway connections") + ("gateway_port", po::value(&config.gatewayPort)->default_value(5001), + "port for gateway connections") + ("registrar_address", po::value(&config.registrarAddress)->default_value("127.0.0.1"), + "address for registrar connections") + ("registrar_port", po::value(&config.registrarPort)->default_value(5000), + "port for registrar connections") + ("database_path", po::value(&config.chatDatabasePath)->default_value("chat.db"), + "path to the sqlite3 database file") + ; + + po::options_description cmdline_options; + cmdline_options.add(generic).add(options); + + po::options_description config_file_options; + config_file_options.add(options); + + po::variables_map vm; + po::store(po::command_line_parser(argc, argv).options(cmdline_options).allow_unregistered().run(), vm); + po::notify(vm); + + std::ifstream ifs(configFile.c_str()); + if (!ifs) { + throw std::runtime_error("Cannot open configuration file: " + configFile); + } + + po::store(po::parse_config_file(ifs, config_file_options), vm); + po::notify(vm); + + if (vm.count("help")) { + std::cout << cmdline_options << "\n"; + exit(EXIT_SUCCESS); + } + + return config; +} diff --git a/src/protocol/AddBan.cpp b/src/protocol/AddBan.cpp new file mode 100644 index 0000000..b7d2244 --- /dev/null +++ b/src/protocol/AddBan.cpp @@ -0,0 +1,38 @@ +#include "AddBan.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +AddBan::AddBan(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "ADDBAN request received - adding ban for: " + << FromWideString(request.destAvatarName) << "@" + << FromWideString(request.destAvatarAddress) << " to " + << FromWideString(request.destRoomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto bannedAvatar + = avatarService_->GetAvatar(request.destAvatarName, request.destAvatarAddress); + if (!bannedAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + auto room = roomService_->GetRoom(request.destRoomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.destRoomId = room->GetRoomId(); + + room->AddBanned(srcAvatar->GetAvatarId(), bannedAvatar); +} diff --git a/src/protocol/AddBan.hpp b/src/protocol/AddBan.hpp new file mode 100644 index 0000000..8d4991f --- /dev/null +++ b/src/protocol/AddBan.hpp @@ -0,0 +1,63 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin ADDBAN */ + +struct ReqAddBan { + const ChatRequestType type = ChatRequestType::ADDBAN; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destAvatarName; + std::u16string destAvatarAddress; + std::u16string destRoomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqAddBan& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destAvatarName); + read(ar, data.destAvatarAddress); + read(ar, data.destRoomAddress); + read(ar, data.srcAddress); +} + +/** Begin ADDBAN */ + +struct ResAddBan { + explicit ResAddBan(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::ADDBAN; + uint32_t track; + ChatResultCode result; + uint32_t destRoomId; +}; + +template +void write(StreamT& ar, const ResAddBan& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.destRoomId); +} + +class AddBan { +public: + using RequestType = ReqAddBan; + using ResponseType = ResAddBan; + + AddBan(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/AddFriend.cpp b/src/protocol/AddFriend.cpp new file mode 100644 index 0000000..ce406a3 --- /dev/null +++ b/src/protocol/AddFriend.cpp @@ -0,0 +1,30 @@ +#include "AddFriend.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +AddFriend::AddFriend(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "ADDFRIEND request received - adding: " << FromWideString(request.destName) << "@" + << FromWideString(request.destAddress) << " to " << request.srcAvatarId << "@" + << FromWideString(request.srcAddress); + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto destAvatar = avatarService_->GetAvatar(request.destName, request.destAddress); + if (!destAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + srcAvatar->AddFriend(destAvatar); + + if (destAvatar->IsOnline()) { + client->SendFriendLoginUpdate(srcAvatar, destAvatar); + } +} diff --git a/src/protocol/AddFriend.hpp b/src/protocol/AddFriend.hpp new file mode 100644 index 0000000..903dbae --- /dev/null +++ b/src/protocol/AddFriend.hpp @@ -0,0 +1,62 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin ADDFRIEND */ + +struct ReqAddFriend { + const ChatRequestType type = ChatRequestType::ADDFRIEND; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destName; + std::u16string destAddress; + std::u16string comment; + bool confirm; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqAddFriend& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destName); + read(ar, data.destAddress); + read(ar, data.comment); + read(ar, data.confirm); + read(ar, data.srcAddress); +} + +/** Begin ADDFRIEND */ + +struct ResAddFriend { + ResAddFriend(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::ADDFRIEND; + uint32_t track; + ChatResultCode result; +}; + +template +void write(StreamT& ar, const ResAddFriend& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} + +class AddFriend { +public: + using RequestType = ReqAddFriend; + using ResponseType = ResAddFriend; + + AddFriend(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; +}; diff --git a/src/protocol/AddIgnore.cpp b/src/protocol/AddIgnore.cpp new file mode 100644 index 0000000..80f42c3 --- /dev/null +++ b/src/protocol/AddIgnore.cpp @@ -0,0 +1,26 @@ +#include "AddIgnore.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +AddIgnore::AddIgnore(GatewayClient * client, const RequestType & request, ResponseType & response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "ADDIGNORE request received - adding: " << FromWideString(request.destName) << "@" + << FromWideString(request.destAddress) << " to " << request.srcAvatarId << "@" + << FromWideString(request.srcAddress); + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto destAvatar = avatarService_->GetAvatar(request.destName, request.destAddress); + if (!destAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + srcAvatar->AddIgnore(destAvatar); +} diff --git a/src/protocol/AddIgnore.hpp b/src/protocol/AddIgnore.hpp new file mode 100644 index 0000000..6c0abcb --- /dev/null +++ b/src/protocol/AddIgnore.hpp @@ -0,0 +1,58 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin ADDIGNORE */ + +struct ReqAddIgnore { + const ChatRequestType type = ChatRequestType::ADDIGNORE; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destName; + std::u16string destAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqAddIgnore& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destName); + read(ar, data.destAddress); + read(ar, data.srcAddress); +} + +/** Begin ADDIGNORE */ + +struct ResAddIgnore { + ResAddIgnore(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::ADDIGNORE; + uint32_t track; + ChatResultCode result; +}; + +template +void write(StreamT& ar, const ResAddIgnore& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} + +class AddIgnore { +public: + using RequestType = ReqAddIgnore; + using ResponseType = ResAddIgnore; + + AddIgnore(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; +}; diff --git a/src/protocol/AddInvite.cpp b/src/protocol/AddInvite.cpp new file mode 100644 index 0000000..9929c95 --- /dev/null +++ b/src/protocol/AddInvite.cpp @@ -0,0 +1,38 @@ +#include "AddInvite.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +AddInvite::AddInvite(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "ADDINVITE request received - adding invitation for: " + << FromWideString(request.destAvatarName) << "@" + << FromWideString(request.destAvatarAddress) << " to " + << FromWideString(request.destRoomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto invitedAvatar + = avatarService_->GetAvatar(request.destAvatarName, request.destAvatarAddress); + if (!invitedAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + auto room = roomService_->GetRoom(request.destRoomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.destRoomId = room->GetRoomId(); + + room->AddInvite(srcAvatar->GetAvatarId(), invitedAvatar); +} diff --git a/src/protocol/AddInvite.hpp b/src/protocol/AddInvite.hpp new file mode 100644 index 0000000..efa7234 --- /dev/null +++ b/src/protocol/AddInvite.hpp @@ -0,0 +1,63 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin ADDINVITE */ + +struct ReqAddInvite { + const ChatRequestType type = ChatRequestType::ADDINVITE; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destAvatarName; + std::u16string destAvatarAddress; + std::u16string destRoomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqAddInvite& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destAvatarName); + read(ar, data.destAvatarAddress); + read(ar, data.destRoomAddress); + read(ar, data.srcAddress); +} + +/** Begin ADDINVITE */ + +struct ResAddInvite { + explicit ResAddInvite(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::ADDINVITE; + uint32_t track; + ChatResultCode result; + uint32_t destRoomId; +}; + +template +void write(StreamT& ar, const ResAddInvite& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.destRoomId); +} + +class AddInvite { +public: + using RequestType = ReqAddInvite; + using ResponseType = ResAddInvite; + + AddInvite(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/AddModerator.cpp b/src/protocol/AddModerator.cpp new file mode 100644 index 0000000..c9b7cbd --- /dev/null +++ b/src/protocol/AddModerator.cpp @@ -0,0 +1,39 @@ +#include "AddModerator.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +AddModerator::AddModerator( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "ADDMODERATOR request recieved - adding: " + << FromWideString(request.destAvatarName) << "@" + << FromWideString(request.destAvatarAddress) << " to " + << FromWideString(request.destRoomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto moderatorAvatar + = avatarService_->GetAvatar(request.destAvatarName, request.destAvatarAddress); + if (!moderatorAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + auto room = roomService_->GetRoom(request.destRoomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.destRoomId = room->GetRoomId(); + + room->AddModerator(srcAvatar->GetAvatarId(), moderatorAvatar); +} diff --git a/src/protocol/AddModerator.hpp b/src/protocol/AddModerator.hpp new file mode 100644 index 0000000..3dbc03f --- /dev/null +++ b/src/protocol/AddModerator.hpp @@ -0,0 +1,63 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin ADDMODERATOR */ + +struct ReqAddModerator { + const ChatRequestType type = ChatRequestType::ADDMODERATOR; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destAvatarName; + std::u16string destAvatarAddress; + std::u16string destRoomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqAddModerator& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destAvatarName); + read(ar, data.destAvatarAddress); + read(ar, data.destRoomAddress); + read(ar, data.srcAddress); +} + +/** Begin ADDMODERATOR */ + +struct ResAddModerator { + ResAddModerator(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::ADDMODERATOR; + uint32_t track; + ChatResultCode result; + uint32_t destRoomId; +}; + +template +void write(StreamT& ar, const ResAddModerator& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.destRoomId); +} + +class AddModerator { +public: + using RequestType = ReqAddModerator; + using ResponseType = ResAddModerator; + + AddModerator(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/CreateRoom.cpp b/src/protocol/CreateRoom.cpp new file mode 100644 index 0000000..bd95ebb --- /dev/null +++ b/src/protocol/CreateRoom.cpp @@ -0,0 +1,21 @@ +#include "CreateRoom.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +CreateRoom::CreateRoom(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "CREATEROOM request received - creator: " << request.creatorId << "@" + << FromWideString(request.srcAddress) + << " room: " << FromWideString(request.roomAddress); + + response.room = roomService_->CreateRoom(avatarService_->GetAvatar(request.creatorId), + request.roomName, request.roomTopic, request.roomPassword, request.roomAttributes, + request.roomMaxSize, request.roomAddress, request.srcAddress); +} diff --git a/src/protocol/CreateRoom.hpp b/src/protocol/CreateRoom.hpp new file mode 100644 index 0000000..1f0ffde --- /dev/null +++ b/src/protocol/CreateRoom.hpp @@ -0,0 +1,83 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "ChatRoom.hpp" + +#include +#include +#include + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin CREATEROOM */ + +struct ReqCreateRoom { + const ChatRequestType type = ChatRequestType::CREATEROOM; + uint32_t track; + uint32_t creatorId; + std::u16string roomName; + std::u16string roomTopic; + std::u16string roomPassword; + uint32_t roomAttributes; + uint32_t roomMaxSize; + std::u16string roomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqCreateRoom& data) { + read(ar, data.track); + read(ar, data.creatorId); + read(ar, data.roomName); + read(ar, data.roomTopic); + read(ar, data.roomPassword); + read(ar, data.roomAttributes); + read(ar, data.roomMaxSize); + read(ar, data.roomAddress); + read(ar, data.srcAddress); +} + +/** Begin CREATEROOM */ + +struct ResCreateRoom { + explicit ResCreateRoom(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::CREATEROOM; + uint32_t track; + ChatResultCode result; + ChatRoom* room; + std::vector extraRooms; +}; + +template +void write(StreamT& ar, const ResCreateRoom& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + if (data.result == ChatResultCode::SUCCESS) { + write(ar, *data.room); + + write(ar, static_cast(data.extraRooms.size())); + for (auto room : data.extraRooms) { + write(ar, *room); + } + } +} + +class CreateRoom { +public: + using RequestType = ReqCreateRoom; + using ResponseType = ResCreateRoom; + + CreateRoom(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/DestroyAvatar.cpp b/src/protocol/DestroyAvatar.cpp new file mode 100644 index 0000000..a39b377 --- /dev/null +++ b/src/protocol/DestroyAvatar.cpp @@ -0,0 +1,29 @@ +#include "DestroyAvatar.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" + +#include "easylogging++.h" + +DestroyAvatar::DestroyAvatar( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + auto avatar = avatarService_->GetAvatar(request.avatarId); + if (!avatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + // Remove From All Rooms + for (auto room : avatar->GetJoinedRooms()) { + auto addresses = room->GetConnectedAddresses(); + room->LeaveRoom(avatar); + + client->SendLeaveRoomUpdate(addresses, avatar->GetAvatarId(), room->GetRoomId()); + } + + // Destroy avatar + avatarService_->DestroyAvatar(avatar); +} diff --git a/src/protocol/DestroyAvatar.hpp b/src/protocol/DestroyAvatar.hpp new file mode 100644 index 0000000..83ac28d --- /dev/null +++ b/src/protocol/DestroyAvatar.hpp @@ -0,0 +1,55 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin DESTROYAVATAR */ + +struct ReqDestroyAvatar { + const ChatRequestType type = ChatRequestType::LOGOUTAVATAR; + uint32_t track; + uint32_t avatarId; + std::u16string address; +}; + +template +void read(StreamT& ar, ReqDestroyAvatar& data) { + read(ar, data.track); + read(ar, data.avatarId); + read(ar, data.address); +} + +/** Begin DESTROYAVATAR */ + +struct ResDestroyAvatar { + explicit ResDestroyAvatar(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::DESTROYAVATAR; + uint32_t track; + ChatResultCode result; +}; + +template +void write(StreamT& ar, const ResDestroyAvatar& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} + +class DestroyAvatar { +public: + using RequestType = ReqDestroyAvatar; + using ResponseType = ResDestroyAvatar; + + DestroyAvatar(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/DestroyRoom.cpp b/src/protocol/DestroyRoom.cpp new file mode 100644 index 0000000..56aa1dc --- /dev/null +++ b/src/protocol/DestroyRoom.cpp @@ -0,0 +1,42 @@ +#include "DestroyRoom.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +DestroyRoom::DestroyRoom(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "DESTROYROOM request received " << request.srcAvatarId << "@" + << FromWideString(request.srcAddress) + << " room: " << FromWideString(request.roomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException(ChatResultCode::SRCAVATARDOESNTEXIST); + } + + auto room = roomService_->GetRoom(request.roomAddress); + if (!room) { + throw ChatResultException(ChatResultCode::ADDRESSNOTROOM); + } + + auto addresses = room->GetRemoteAddresses(); + auto roomId = room->GetRoomId(); + + response.roomId = roomId; + + for (auto roomAvatar : room->GetAvatars()) { + auto roomAddresses = room->GetConnectedAddresses(); + room->LeaveRoom(roomAvatar); + client->SendLeaveRoomUpdate(roomAddresses, roomAvatar->GetAvatarId(), roomId); + } + + roomService_->DestroyRoom(room); + + client->SendDestroyRoomUpdate(srcAvatar, roomId, addresses); +} diff --git a/src/protocol/DestroyRoom.hpp b/src/protocol/DestroyRoom.hpp new file mode 100644 index 0000000..cc88e83 --- /dev/null +++ b/src/protocol/DestroyRoom.hpp @@ -0,0 +1,59 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin DESTROYROOM */ + +struct ReqDestroyRoom { + const ChatRequestType type = ChatRequestType::DESTROYROOM; + uint32_t track; + uint32_t srcAvatarId; + std::u16string roomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqDestroyRoom& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.roomAddress); + read(ar, data.srcAddress); +} + +/** Begin DESTROYROOM */ + +struct ResDestroyRoom { + explicit ResDestroyRoom(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::DESTROYROOM; + uint32_t track; + ChatResultCode result; + uint32_t roomId; +}; + +template +void write(StreamT& ar, const ResDestroyRoom& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.roomId); +} + +class DestroyRoom { +public: + using RequestType = ReqDestroyRoom; + using ResponseType = ResDestroyRoom; + + DestroyRoom(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/EnterRoom.cpp b/src/protocol/EnterRoom.cpp new file mode 100644 index 0000000..4ce168f --- /dev/null +++ b/src/protocol/EnterRoom.cpp @@ -0,0 +1,33 @@ +#include "EnterRoom.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoom.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +EnterRoom::EnterRoom(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "ENTERROOM request received - avatar: " << request.srcAvatarId << "@" + << FromWideString(request.srcAddress) + << " room: " << FromWideString(request.roomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + response.room = roomService_->GetRoom(request.roomAddress); + if (!response.room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.roomId = response.room->GetRoomId(); + response.room->EnterRoom(srcAvatar, request.roomPassword); + + client->SendEnterRoomUpdate(srcAvatar, response.room); +} diff --git a/src/protocol/EnterRoom.hpp b/src/protocol/EnterRoom.hpp new file mode 100644 index 0000000..fc0120b --- /dev/null +++ b/src/protocol/EnterRoom.hpp @@ -0,0 +1,89 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "ChatRoom.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin ENTERROOM */ + +struct ReqEnterRoom { + const ChatRequestType type = ChatRequestType::ENTERROOM; + uint32_t track; + uint32_t srcAvatarId; + std::u16string roomAddress; + std::u16string roomPassword; + bool passiveCreate; + std::u16string paramRoomTopic; + uint32_t paramRoomAttributes; + uint32_t paramRoomMaxSize; + bool requestingEntry; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqEnterRoom& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.roomAddress); + read(ar, data.roomPassword); + read(ar, data.passiveCreate); + + if (data.passiveCreate) { + read(ar, data.paramRoomTopic); + read(ar, data.paramRoomAttributes); + read(ar, data.paramRoomMaxSize); + } + + read(ar, data.requestingEntry); + read(ar, data.srcAddress); +} + +/** Begin ENTERROOM */ + +struct ResEnterRoom { + ResEnterRoom(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::ENTERROOM; + uint32_t track; + ChatResultCode result; + uint32_t roomId; + bool gotRoomObj = false; + ChatRoom* room = nullptr; + std::vector extraRooms; +}; + +template +void write(StreamT& ar, const ResEnterRoom& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.roomId); + write(ar, data.gotRoomObj); + + if (data.gotRoomObj) { + write(ar, *data.room); + + write(ar, static_cast(data.extraRooms.size())); + for (auto room : data.extraRooms) { + write(ar, *room); + } + } +} + +class EnterRoom { +public: + using RequestType = ReqEnterRoom; + using ResponseType = ResEnterRoom; + + EnterRoom(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/FailoverReLoginAvatar.cpp b/src/protocol/FailoverReLoginAvatar.cpp new file mode 100644 index 0000000..562964f --- /dev/null +++ b/src/protocol/FailoverReLoginAvatar.cpp @@ -0,0 +1,38 @@ +#include "FailoverReLoginAvatar.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +FailoverReLoginAvatar::FailoverReLoginAvatar( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "FAILOVER_RELOGINAVATAR request received " << FromWideString(request.name) << "@" + << FromWideString(request.address); + + auto avatar = avatarService_->GetAvatar(request.name, request.address); + if (!avatar) { + LOG(INFO) << "Login avatar does not exist, creating a new one " << FromWideString(request.name) << "@" + << FromWideString(request.address); + avatar = avatarService_->CreateAvatar(request.name, request.address, request.userId, + request.attributes, request.loginLocation); + } + + avatarService_->LoginAvatar(CHECK_NOTNULL(avatar)); + + if (avatar->GetName().compare(u"SYSTEM") == 0) { + client->GetNode()->RegisterClientAddress(avatar->GetAddress(), client); + roomService_->LoadRoomsFromStorage(request.address); + } else { + client->SendFriendLoginUpdates(avatar); + } + + for (auto room : avatar->GetJoinedRooms()) { + client->SendEnterRoomUpdate(avatar, room); + } +} diff --git a/src/protocol/FailoverReLoginAvatar.hpp b/src/protocol/FailoverReLoginAvatar.hpp new file mode 100644 index 0000000..a4629ea --- /dev/null +++ b/src/protocol/FailoverReLoginAvatar.hpp @@ -0,0 +1,64 @@ + +#pragma once + +#include "ChatEnums.hpp" + +#include +#include + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +struct ReqFailoverReLoginAvatar{ + const ChatRequestType type = ChatRequestType::FAILOVER_RELOGINAVATAR; + uint32_t track; + uint32_t avatarId; + uint32_t userId; + std::u16string name; + std::u16string address; + std::u16string loginLocation; + int32_t loginPriority; + uint32_t attributes; +}; + +struct ResFailoverReLoginAvatar { + ResFailoverReLoginAvatar(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::FAILOVER_RELOGINAVATAR; + uint32_t track; + ChatResultCode result; +}; + +class FailoverReLoginAvatar { +public: + using RequestType = ReqFailoverReLoginAvatar; + using ResponseType = ResFailoverReLoginAvatar; + + FailoverReLoginAvatar(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; + +template +void read(StreamT& ar, ReqFailoverReLoginAvatar& data) { + read(ar, data.track); + read(ar, data.avatarId); + read(ar, data.userId); + read(ar, data.name); + read(ar, data.address); + read(ar, data.loginLocation); + read(ar, data.loginPriority); + read(ar, data.attributes); +} + +template +void write(StreamT& ar, const ResFailoverReLoginAvatar& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} \ No newline at end of file diff --git a/src/protocol/FriendStatus.cpp b/src/protocol/FriendStatus.cpp new file mode 100644 index 0000000..22fcbc4 --- /dev/null +++ b/src/protocol/FriendStatus.cpp @@ -0,0 +1,22 @@ +#include "FriendStatus.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +FriendStatus::FriendStatus( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "FRIENDSTATUS request received - for " << request.srcAvatarId << "@" + << FromWideString(request.srcAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + response.srcAvatar = srcAvatar; +} diff --git a/src/protocol/FriendStatus.hpp b/src/protocol/FriendStatus.hpp new file mode 100644 index 0000000..ac6c8f0 --- /dev/null +++ b/src/protocol/FriendStatus.hpp @@ -0,0 +1,70 @@ + +#pragma once + +#include "ChatAvatar.hpp" +#include "ChatEnums.hpp" + +#include + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin FRIENDSTATUS */ + +struct ReqFriendStatus { + const ChatRequestType type = ChatRequestType::FRIENDSTATUS; + uint32_t track; + uint32_t srcAvatarId; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqFriendStatus& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.srcAddress); +} + +/** Begin FRIENDSTATUS */ + +struct ResFriendStatus { + ResFriendStatus(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::FRIENDSTATUS; + uint32_t track; + ChatResultCode result; + const ChatAvatar* srcAvatar; +}; + +template +void write(StreamT& ar, const ResFriendStatus& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + if (data.result == ChatResultCode::SUCCESS && data.srcAvatar) { + const auto& friends = data.srcAvatar->GetFriendList(); + + write(ar, static_cast(friends.size())); + for (auto& friendContact : friends) { + write(ar, friendContact); + } + } else { + write(ar, static_cast(0)); + } +} + +class FriendStatus { +public: + using RequestType = ReqFriendStatus; + using ResponseType = ResFriendStatus; + + FriendStatus(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/GetAnyAvatar.cpp b/src/protocol/GetAnyAvatar.cpp new file mode 100644 index 0000000..228354a --- /dev/null +++ b/src/protocol/GetAnyAvatar.cpp @@ -0,0 +1,24 @@ +#include "GetAnyAvatar.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +GetAnyAvatar::GetAnyAvatar( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "GETANYAVATAR request received - avatar: " << FromWideString(request.name) << "@" + << FromWideString(request.address); + + auto avatar = avatarService_->GetAvatar(request.name, request.address); + if (!avatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + response.isOnline = avatar->IsOnline(); + response.avatar = avatar; +} diff --git a/src/protocol/GetAnyAvatar.hpp b/src/protocol/GetAnyAvatar.hpp new file mode 100644 index 0000000..6e31e15 --- /dev/null +++ b/src/protocol/GetAnyAvatar.hpp @@ -0,0 +1,68 @@ + +#pragma once + +#include "ChatAvatar.hpp" +#include "ChatEnums.hpp" + +class ChatAvatarService; +class GatewayClient; + +/** Begin GETANYAVATAR */ + +struct ReqGetAnyAvatar { + const ChatRequestType type = ChatRequestType::GETANYAVATAR; + uint32_t track; + std::u16string name; + std::u16string address; +}; + +template +void read(StreamT& ar, ReqGetAnyAvatar& data) { + read(ar, data.track); + read(ar, data.name); + read(ar, data.address); +} + +/** Begin GETANYAVATAR */ + +struct ResGetAnyAvatar { + explicit ResGetAnyAvatar(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + ResGetAnyAvatar(uint32_t track_, ChatResultCode result_, bool isOnline_, + const ChatAvatar* avatar_) + : track{track_} + , result{result_} + , isOnline{isOnline_} + , avatar{avatar_} {} + + const ChatResponseType type = ChatResponseType::GETANYAVATAR; + uint32_t track; + ChatResultCode result; + bool isOnline; + const ChatAvatar* avatar; +}; + +template +void write(StreamT& ar, const ResGetAnyAvatar& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.isOnline); + + if (data.result == ChatResultCode::SUCCESS) { + write(ar, data.avatar); + } +} + +class GetAnyAvatar { +public: + using RequestType = ReqGetAnyAvatar; + using ResponseType = ResGetAnyAvatar; + + GetAnyAvatar(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; +}; diff --git a/src/protocol/GetPersistentHeaders.cpp b/src/protocol/GetPersistentHeaders.cpp new file mode 100644 index 0000000..4a39c0d --- /dev/null +++ b/src/protocol/GetPersistentHeaders.cpp @@ -0,0 +1,17 @@ +#include "GetPersistentHeaders.hpp" + +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "PersistentMessageService.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +GetPersistentHeaders::GetPersistentHeaders( + GatewayClient* client, const RequestType& request, ResponseType& response) + : messageService_{client->GetNode()->GetMessageService()} { + LOG(INFO) << "GETPERSISTENTHEADERS request recieved - avatar: " << request.avatarId + << " category: " << FromWideString(request.category); + + response.headers = messageService_->GetMessageHeaders(request.avatarId); +} diff --git a/src/protocol/GetPersistentHeaders.hpp b/src/protocol/GetPersistentHeaders.hpp new file mode 100644 index 0000000..35a1952 --- /dev/null +++ b/src/protocol/GetPersistentHeaders.hpp @@ -0,0 +1,62 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "PersistentMessage.hpp" + +#include + +class PersistentMessageService; +class GatewayClient; + +/** Begin GETPERSISTENTHEADERS */ + +struct ReqGetPersistentHeaders { + const ChatRequestType type = ChatRequestType::GETPERSISTENTHEADERS; + uint32_t track; + uint32_t avatarId; + std::u16string category; +}; + +template +void read(StreamT& ar, ReqGetPersistentHeaders& data) { + read(ar, data.track); + read(ar, data.avatarId); + read(ar, data.category); +} + +/** Begin GETPERSISTENTHEADERS */ + +struct ResGetPersistentHeaders { + ResGetPersistentHeaders(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::GETPERSISTENTHEADERS; + uint32_t track; + ChatResultCode result; + std::vector headers; +}; + +template +void write(StreamT& ar, const ResGetPersistentHeaders& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, static_cast(data.headers.size())); + + for (auto& header : data.headers) { + write(ar, header); + } +} + +class GetPersistentHeaders { +public: + using RequestType = ReqGetPersistentHeaders; + using ResponseType = ResGetPersistentHeaders; + + GetPersistentHeaders(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + PersistentMessageService* messageService_; +}; diff --git a/src/protocol/GetPersistentMessage.cpp b/src/protocol/GetPersistentMessage.cpp new file mode 100644 index 0000000..8f925fa --- /dev/null +++ b/src/protocol/GetPersistentMessage.cpp @@ -0,0 +1,17 @@ +#include "GetPersistentMessage.hpp" + +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "PersistentMessageService.hpp" + +#include "easylogging++.h" + +GetPersistentMessage::GetPersistentMessage( + GatewayClient* client, const RequestType& request, ResponseType& response) + : messageService_{client->GetNode()->GetMessageService()} { + LOG(INFO) << "GETPERSISTENTMESSAGE request received - avatar: " << request.srcAvatarId + << " message: " << request.messageId; + + response.message + = messageService_->GetPersistentMessage(request.srcAvatarId, request.messageId); +} diff --git a/src/protocol/GetPersistentMessage.hpp b/src/protocol/GetPersistentMessage.hpp new file mode 100644 index 0000000..a5f3101 --- /dev/null +++ b/src/protocol/GetPersistentMessage.hpp @@ -0,0 +1,60 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "PersistentMessage.hpp" + +class PersistentMessageService; +class GatewayClient; + +/** Begin GETPERSISTENTMESSAGE */ + +struct ReqGetPersistentMessage { + const ChatRequestType type = ChatRequestType::GETPERSISTENTMESSAGE; + uint32_t track; + uint32_t srcAvatarId; + uint32_t messageId; +}; + +template +void read(StreamT& ar, ReqGetPersistentMessage& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.messageId); +} + +/** Begin GETPERSISTENTMESSAGE */ + +struct ResGetPersistentMessage { + ResGetPersistentMessage( + uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::GETPERSISTENTMESSAGE; + uint32_t track; + ChatResultCode result; + PersistentMessage message; +}; + +template +void write(StreamT& ar, const ResGetPersistentMessage& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + if (data.result == ChatResultCode::SUCCESS) { + write(ar, data.message); + } +} + +class GetPersistentMessage { +public: + using RequestType = ReqGetPersistentMessage; + using ResponseType = ResGetPersistentMessage; + + GetPersistentMessage(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + PersistentMessageService* messageService_; +}; diff --git a/src/protocol/GetRoom.cpp b/src/protocol/GetRoom.cpp new file mode 100644 index 0000000..c61ed43 --- /dev/null +++ b/src/protocol/GetRoom.cpp @@ -0,0 +1,20 @@ +#include "GetRoom.hpp" + +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +GetRoom::GetRoom(GatewayClient* client, const RequestType& request, ResponseType& response) + : roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "GETROOM request received - room: " << FromWideString(request.roomAddress); + + auto room = roomService_->GetRoom(request.roomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSDOESNTEXIST}; + } + + response.room = room; +} diff --git a/src/protocol/GetRoom.hpp b/src/protocol/GetRoom.hpp new file mode 100644 index 0000000..0d97baf --- /dev/null +++ b/src/protocol/GetRoom.hpp @@ -0,0 +1,65 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "ChatRoom.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin GETROOM */ + +struct ReqGetRoom { + const ChatRequestType type = ChatRequestType::GETROOMSUMMARIES; + uint32_t track; + std::u16string roomAddress; +}; + +template +void read(StreamT& ar, ReqGetRoom& data) { + read(ar, data.track); + read(ar, data.roomAddress); +} + +/** Begin GETROOM */ + +struct ResGetRoom { + ResGetRoom(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} + , room{nullptr} {} + + const ChatResponseType type = ChatResponseType::GETROOM; + uint32_t track; + ChatResultCode result; + ChatRoom* room; + std::vector extraRooms; +}; + +template +void write(StreamT& ar, const ResGetRoom& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + if (data.result == ChatResultCode::SUCCESS) { + write(ar, *data.room); + + write(ar, static_cast(data.extraRooms.size())); + for (auto room : data.extraRooms) { + write(ar, *room); + } + } +} + +class GetRoom { +public: + using RequestType = ReqGetRoom; + using ResponseType = ResGetRoom; + + GetRoom(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatRoomService* roomService_; +}; diff --git a/src/protocol/GetRoomSummaries.cpp b/src/protocol/GetRoomSummaries.cpp new file mode 100644 index 0000000..6f3b384 --- /dev/null +++ b/src/protocol/GetRoomSummaries.cpp @@ -0,0 +1,18 @@ +#include "GetRoomSummaries.hpp" + +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +GetRoomSummaries::GetRoomSummaries( + GatewayClient* client, const RequestType& request, ResponseType& response) + : roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "GETROOMSUMMARIES request received - start node: " + << FromWideString(request.startNodeAddress) + << " filter: " << FromWideString(request.roomFilter); + + response.rooms = roomService_->GetRoomSummaries(request.startNodeAddress, request.roomFilter); +} diff --git a/src/protocol/GetRoomSummaries.hpp b/src/protocol/GetRoomSummaries.hpp new file mode 100644 index 0000000..96727e3 --- /dev/null +++ b/src/protocol/GetRoomSummaries.hpp @@ -0,0 +1,67 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "ChatRoom.hpp" + +#include + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin GETROOMSUMMARIES */ + +struct ReqGetRoomSummaries { + const ChatRequestType type = ChatRequestType::GETROOMSUMMARIES; + uint32_t track; + std::u16string startNodeAddress; + std::u16string roomFilter; +}; + +template +void read(StreamT& ar, ReqGetRoomSummaries& data) { + read(ar, data.track); + read(ar, data.startNodeAddress); + read(ar, data.roomFilter); +} + +/** Begin GETROOMSUMMARIES */ + +struct ResGetRoomSummaries { + ResGetRoomSummaries(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::GETROOMSUMMARIES; + uint32_t track; + ChatResultCode result; + std::vector rooms; +}; + +template +void write(StreamT& ar, const ResGetRoomSummaries& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + write(ar, static_cast(data.rooms.size())); + for (auto room : data.rooms) { + write(ar, room->GetRoomAddress()); + write(ar, room->GetRoomTopic()); + write(ar, room->GetRoomAttributes()); + write(ar, room->GetCurrentRoomSize()); + write(ar, room->GetMaxRoomSize()); + } +} + +class GetRoomSummaries { +public: + using RequestType = ReqGetRoomSummaries; + using ResponseType = ResGetRoomSummaries; + + GetRoomSummaries(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatRoomService* roomService_; +}; diff --git a/src/protocol/IgnoreStatus.cpp b/src/protocol/IgnoreStatus.cpp new file mode 100644 index 0000000..67bdd4b --- /dev/null +++ b/src/protocol/IgnoreStatus.cpp @@ -0,0 +1,22 @@ +#include "IgnoreStatus.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +IgnoreStatus::IgnoreStatus( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "IGNORESTATUS request received - for " << request.srcAvatarId << "@" + << FromWideString(request.srcAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + response.srcAvatar = srcAvatar; +} diff --git a/src/protocol/IgnoreStatus.hpp b/src/protocol/IgnoreStatus.hpp new file mode 100644 index 0000000..4e14fa5 --- /dev/null +++ b/src/protocol/IgnoreStatus.hpp @@ -0,0 +1,67 @@ + +#pragma once + +#include "ChatAvatar.hpp" +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin IGNORESTATUS */ + +struct ReqIgnoreStatus { + const ChatRequestType type = ChatRequestType::IGNORESTATUS; + uint32_t track; + uint32_t srcAvatarId; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqIgnoreStatus& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.srcAddress); +} + +/** Begin IGNORESTATUS */ + +struct ResIgnoreStatus { + ResIgnoreStatus(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::IGNORESTATUS; + uint32_t track; + ChatResultCode result; + const ChatAvatar* srcAvatar; +}; + +template +void write(StreamT& ar, const ResIgnoreStatus& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + if (data.result == ChatResultCode::SUCCESS && data.srcAvatar) { + const auto& ignored = data.srcAvatar->GetIgnoreList(); + + write(ar, static_cast(ignored.size())); + for (auto& ignoredContact : ignored) { + write(ar, ignoredContact); + } + } else { + write(ar, static_cast(0)); + } +} + +class IgnoreStatus { +public: + using RequestType = ReqIgnoreStatus; + using ResponseType = ResIgnoreStatus; + + IgnoreStatus(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; +}; diff --git a/src/protocol/KickAvatar.cpp b/src/protocol/KickAvatar.cpp new file mode 100644 index 0000000..4ce9ec8 --- /dev/null +++ b/src/protocol/KickAvatar.cpp @@ -0,0 +1,39 @@ +#include "KickAvatar.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +KickAvatar::KickAvatar(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "KICKAVATAR request received - kicking: " << FromWideString(request.destAvatarName) + << "@" << FromWideString(request.destAvatarAddress) << " from " + << FromWideString(request.destRoomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto destAvatar = avatarService_->GetAvatar(request.destAvatarName, request.destAvatarAddress); + if (!destAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + auto room = roomService_->GetRoom(request.destRoomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.destRoomId = room->GetRoomId(); + + auto addresses = room->GetConnectedAddresses(); + room->KickAvatar(srcAvatar->GetAvatarId(), destAvatar); + + client->SendKickAvatarUpdate(addresses, srcAvatar, destAvatar, room); +} diff --git a/src/protocol/KickAvatar.hpp b/src/protocol/KickAvatar.hpp new file mode 100644 index 0000000..e4f3812 --- /dev/null +++ b/src/protocol/KickAvatar.hpp @@ -0,0 +1,63 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin KICKAVATAR */ + +struct ReqKickAvatar { + const ChatRequestType type = ChatRequestType::KICKAVATAR; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destAvatarName; + std::u16string destAvatarAddress; + std::u16string destRoomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqKickAvatar& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destAvatarName); + read(ar, data.destAvatarAddress); + read(ar, data.destRoomAddress); + read(ar, data.srcAddress); +} + +/** Begin KICKAVATAR */ + +struct ResKickAvatar { + ResKickAvatar(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::KICKAVATAR; + uint32_t track; + ChatResultCode result; + uint32_t destRoomId; +}; + +template +void write(StreamT& ar, const ResKickAvatar& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.destRoomId); +} + +class KickAvatar { +public: + using RequestType = ReqKickAvatar; + using ResponseType = ResKickAvatar; + + KickAvatar(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/LeaveRoom.cpp b/src/protocol/LeaveRoom.cpp new file mode 100644 index 0000000..4ae2462 --- /dev/null +++ b/src/protocol/LeaveRoom.cpp @@ -0,0 +1,31 @@ +#include "LeaveRoom.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" + +#include "easylogging++.h" + +LeaveRoom::LeaveRoom(GatewayClient * client, const RequestType & request, ResponseType & response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto room = roomService_->GetRoom(request.roomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.roomId = room->GetRoomId(); + + // Cache the addresses before leaving the room in case this avatar was the + // last on their server, to ensure the update messages goes out. + auto addresses = room->GetConnectedAddresses(); + room->LeaveRoom(srcAvatar); + + client->SendLeaveRoomUpdate(addresses, srcAvatar->GetAvatarId(), room->GetRoomId()); +} diff --git a/src/protocol/LeaveRoom.hpp b/src/protocol/LeaveRoom.hpp new file mode 100644 index 0000000..a278e90 --- /dev/null +++ b/src/protocol/LeaveRoom.hpp @@ -0,0 +1,59 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin LEAVEROOM */ + +struct ReqLeaveRoom { + const ChatRequestType type = ChatRequestType::LEAVEROOM; + uint32_t track; + uint32_t srcAvatarId; + std::u16string roomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqLeaveRoom& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.roomAddress); + read(ar, data.srcAddress); +} + +/** Begin LEAVEROOM */ + +struct ResLeaveRoom { + ResLeaveRoom(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::LEAVEROOM; + uint32_t track; + ChatResultCode result; + uint32_t roomId; +}; + +template +void write(StreamT& ar, const ResLeaveRoom& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.roomId); +} + +class LeaveRoom { +public: + using RequestType = ReqLeaveRoom; + using ResponseType = ResLeaveRoom; + + LeaveRoom(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/LoginAvatar.cpp b/src/protocol/LoginAvatar.cpp new file mode 100644 index 0000000..88c814b --- /dev/null +++ b/src/protocol/LoginAvatar.cpp @@ -0,0 +1,36 @@ + +#include "LoginAvatar.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +LoginAvatar::LoginAvatar(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "LOGINAVATAR request received " << FromWideString(request.name) << "@" + << FromWideString(request.address); + + auto avatar = avatarService_->GetAvatar(request.name, request.address); + if (!avatar) { + LOG(INFO) << "Login avatar does not exist, creating a new one " + << FromWideString(request.name) << "@" << FromWideString(request.address); + avatar = avatarService_->CreateAvatar(request.name, request.address, request.userId, + request.loginAttributes, request.loginLocation); + } + + avatarService_->LoginAvatar(CHECK_NOTNULL(avatar)); + + if (avatar->GetName().compare(u"SYSTEM") == 0) { + client->GetNode()->RegisterClientAddress(avatar->GetAddress(), client); + roomService_->LoadRoomsFromStorage(request.address); + } else { + client->SendFriendLoginUpdates(avatar); + } + + response.avatar = avatar; +} diff --git a/src/protocol/LoginAvatar.hpp b/src/protocol/LoginAvatar.hpp new file mode 100644 index 0000000..e9b5d59 --- /dev/null +++ b/src/protocol/LoginAvatar.hpp @@ -0,0 +1,69 @@ + +#pragma once + +#include "ChatAvatar.hpp" +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin LOGINAVATAR */ + +struct ReqLoginAvatar { + const ChatRequestType type = ChatRequestType::LOGINAVATAR; + uint32_t track; + uint32_t userId; + std::u16string name; + std::u16string address; + std::u16string loginLocation; + int32_t loginPriority; + int32_t loginAttributes; +}; + +template +void read(StreamT& ar, ReqLoginAvatar& data) { + read(ar, data.track); + read(ar, data.userId); + read(ar, data.name); + read(ar, data.address); + read(ar, data.loginLocation); + read(ar, data.loginPriority); + read(ar, data.loginAttributes); +} + +/** Begin LOGINAVATAR */ + +struct ResLoginAvatar { + explicit ResLoginAvatar(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::LOGINAVATAR; + uint32_t track; + ChatResultCode result; + const ChatAvatar* avatar; +}; + +template +void write(StreamT& ar, const ResLoginAvatar& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + if (data.result == ChatResultCode::SUCCESS) { + write(ar, data.avatar); + } +} + +class LoginAvatar { +public: + using RequestType = ReqLoginAvatar; + using ResponseType = ResLoginAvatar; + + LoginAvatar(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/LogoutAvatar.cpp b/src/protocol/LogoutAvatar.cpp new file mode 100644 index 0000000..07496d7 --- /dev/null +++ b/src/protocol/LogoutAvatar.cpp @@ -0,0 +1,28 @@ +#include "LogoutAvatar.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" + +#include "easylogging++.h" + +LogoutAvatar::LogoutAvatar(GatewayClient * client, const RequestType & request, ResponseType & response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} +{ + LOG(INFO) << "LOGOUTAVATAR request received - avatar id:" << request.avatarId; + + auto avatar = avatarService_->GetAvatar(request.avatarId); + + for (auto room : avatar->GetJoinedRooms()) { + auto addresses = room->GetConnectedAddresses(); + room->LeaveRoom(avatar); + + client->SendLeaveRoomUpdate(addresses, avatar->GetAvatarId(), room->GetRoomId()); + } + + client->SendFriendLogoutUpdates(avatar); + + avatarService_->LogoutAvatar(avatar); +} diff --git a/src/protocol/LogoutAvatar.hpp b/src/protocol/LogoutAvatar.hpp new file mode 100644 index 0000000..eb763bc --- /dev/null +++ b/src/protocol/LogoutAvatar.hpp @@ -0,0 +1,54 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin LOGOUTAVATAR */ + +struct ReqLogoutAvatar { + const ChatRequestType type = ChatRequestType::LOGOUTAVATAR; + uint32_t track; + uint32_t avatarId; +}; + +template +void read(StreamT& ar, ReqLogoutAvatar& data) { + read(ar, data.track); + read(ar, data.avatarId); +} + +/** Begin LOGOUTAVATAR */ + +struct ResLogoutAvatar { + explicit ResLogoutAvatar(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::LOGOUTAVATAR; + uint32_t track; + ChatResultCode result; +}; + +template +void write(StreamT& ar, const ResLogoutAvatar& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} + + +class LogoutAvatar { +public: + using RequestType = ReqLogoutAvatar; + using ResponseType = ResLogoutAvatar; + + LogoutAvatar(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/RegistrarGetChatServer.cpp b/src/protocol/RegistrarGetChatServer.cpp new file mode 100644 index 0000000..3472eb2 --- /dev/null +++ b/src/protocol/RegistrarGetChatServer.cpp @@ -0,0 +1,18 @@ +#include "RegistrarGetChatServer.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "RegistrarClient.hpp" +#include "RegistrarNode.hpp" +#include "StationChatConfig.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + + +RegistrarGetChatServer::RegistrarGetChatServer(RegistrarClient* client, const RequestType & request, ResponseType & response) { + auto& config = client->GetNode()->GetConfig(); + + response.hostname = ToWideString(config.gatewayAddress); + response.port = config.gatewayPort; +} diff --git a/src/protocol/RegistrarGetChatServer.hpp b/src/protocol/RegistrarGetChatServer.hpp new file mode 100644 index 0000000..87a96e7 --- /dev/null +++ b/src/protocol/RegistrarGetChatServer.hpp @@ -0,0 +1,54 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class RegistrarClient; + +/** Begin REGISTRAR_GETCHATSERVER */ + +struct ReqRegistrarGetChatServer { + const ChatRequestType type = ChatRequestType::REGISTRAR_GETCHATSERVER; + uint32_t track; + std::u16string hostname; + uint16_t port; +}; + +template +void read(StreamT& ar, ReqRegistrarGetChatServer& data) { + read(ar, data.track); + read(ar, data.hostname); + read(ar, data.port); +} + +/** Begin REGISTRAR_GETCHATSERVER */ + +struct ResRegistrarGetChatServer { + ResRegistrarGetChatServer( + uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::REGISTRAR_GETCHATSERVER; + uint32_t track; + ChatResultCode result; + std::u16string hostname; + uint16_t port; +}; + +template +void write(StreamT& ar, const ResRegistrarGetChatServer& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.hostname); + write(ar, data.port); +} + +class RegistrarGetChatServer { +public: + using RequestType = ReqRegistrarGetChatServer; + using ResponseType = ResRegistrarGetChatServer; + + RegistrarGetChatServer(RegistrarClient* client, const RequestType& request, ResponseType& response); +}; diff --git a/src/protocol/RemoveBan.cpp b/src/protocol/RemoveBan.cpp new file mode 100644 index 0000000..6d58801 --- /dev/null +++ b/src/protocol/RemoveBan.cpp @@ -0,0 +1,38 @@ +#include "RemoveBan.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +RemoveBan::RemoveBan(GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "REMOVEBAN request received - removing ban for: " + << FromWideString(request.destAvatarName) << "@" + << FromWideString(request.destAvatarAddress) << " from " + << FromWideString(request.destRoomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto bannedAvatar + = avatarService_->GetAvatar(request.destAvatarName, request.destAvatarAddress); + if (!bannedAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + auto room = roomService_->GetRoom(request.destRoomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.destRoomId = room->GetRoomId(); + + room->RemoveBanned(srcAvatar->GetAvatarId(), bannedAvatar->GetAvatarId()); +} diff --git a/src/protocol/RemoveBan.hpp b/src/protocol/RemoveBan.hpp new file mode 100644 index 0000000..451db10 --- /dev/null +++ b/src/protocol/RemoveBan.hpp @@ -0,0 +1,63 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin REMOVEBAN */ + +struct ReqRemoveBan { + const ChatRequestType type = ChatRequestType::REMOVEBAN; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destAvatarName; + std::u16string destAvatarAddress; + std::u16string destRoomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqRemoveBan& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destAvatarName); + read(ar, data.destAvatarAddress); + read(ar, data.destRoomAddress); + read(ar, data.srcAddress); +} + +/** Begin REMOVEBAN */ + +struct ResRemoveBan { + explicit ResRemoveBan(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::REMOVEBAN; + uint32_t track; + ChatResultCode result; + uint32_t destRoomId; +}; + +template +void write(StreamT& ar, const ResRemoveBan& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.destRoomId); +} + +class RemoveBan { +public: + using RequestType = ReqRemoveBan; + using ResponseType = ResRemoveBan; + + RemoveBan(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/RemoveFriend.cpp b/src/protocol/RemoveFriend.cpp new file mode 100644 index 0000000..8f57120 --- /dev/null +++ b/src/protocol/RemoveFriend.cpp @@ -0,0 +1,28 @@ +#include "RemoveFriend.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +RemoveFriend::RemoveFriend( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "REMOVEFRIEND request received - removing: " << FromWideString(request.destName) + << "@" << FromWideString(request.destAddress) << " from " << request.srcAvatarId + << "@" << FromWideString(request.srcAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto destAvatar = avatarService_->GetAvatar(request.destName, request.destAddress); + if (!destAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + srcAvatar->RemoveFriend(destAvatar); +} diff --git a/src/protocol/RemoveFriend.hpp b/src/protocol/RemoveFriend.hpp new file mode 100644 index 0000000..e5e7ccb --- /dev/null +++ b/src/protocol/RemoveFriend.hpp @@ -0,0 +1,58 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin REMOVEFRIEND */ + +struct ReqRemoveFriend { + const ChatRequestType type = ChatRequestType::REMOVEFRIEND; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destName; + std::u16string destAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqRemoveFriend& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destName); + read(ar, data.destAddress); + read(ar, data.srcAddress); +} + +/** Begin REMOVEFRIEND */ + +struct ResRemoveFriend { + ResRemoveFriend(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::REMOVEFRIEND; + uint32_t track; + ChatResultCode result; +}; + +template +void write(StreamT& ar, const ResRemoveFriend& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} + +class RemoveFriend { +public: + using RequestType = ReqRemoveFriend; + using ResponseType = ResRemoveFriend; + + RemoveFriend(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; +}; diff --git a/src/protocol/RemoveIgnore.cpp b/src/protocol/RemoveIgnore.cpp new file mode 100644 index 0000000..d932f2c --- /dev/null +++ b/src/protocol/RemoveIgnore.cpp @@ -0,0 +1,27 @@ +#include "RemoveIgnore.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +RemoveIgnore::RemoveIgnore(GatewayClient * client, const RequestType & request, ResponseType & response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "REMOVEIGNORE request received - removing: " << FromWideString(request.destName) << "@" + << FromWideString(request.destAddress) << " from " << request.srcAvatarId << "@" + << FromWideString(request.srcAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto destAvatar = avatarService_->GetAvatar(request.destName, request.destAddress); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + srcAvatar->RemoveIgnore(destAvatar); +} diff --git a/src/protocol/RemoveIgnore.hpp b/src/protocol/RemoveIgnore.hpp new file mode 100644 index 0000000..252dc6e --- /dev/null +++ b/src/protocol/RemoveIgnore.hpp @@ -0,0 +1,58 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin REMOVEIGNORE */ + +struct ReqRemoveIgnore { + const ChatRequestType type = ChatRequestType::REMOVEIGNORE; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destName; + std::u16string destAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqRemoveIgnore& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destName); + read(ar, data.destAddress); + read(ar, data.srcAddress); +} + +/** Begin REMOVEIGNORE */ + +struct ResRemoveIgnore { + ResRemoveIgnore(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::REMOVEIGNORE; + uint32_t track; + ChatResultCode result; +}; + +template +void write(StreamT& ar, const ResRemoveIgnore& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} + +class RemoveIgnore { +public: + using RequestType = ReqRemoveIgnore; + using ResponseType = ResRemoveIgnore; + + RemoveIgnore(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; +}; diff --git a/src/protocol/RemoveInvite.cpp b/src/protocol/RemoveInvite.cpp new file mode 100644 index 0000000..ae34199 --- /dev/null +++ b/src/protocol/RemoveInvite.cpp @@ -0,0 +1,39 @@ +#include "RemoveInvite.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +RemoveInvite::RemoveInvite( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "REMOVEINVITE request received - removing invitation for: " + << FromWideString(request.destAvatarName) << "@" + << FromWideString(request.destAvatarAddress) << " to " + << FromWideString(request.destRoomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto invitedAvatar + = avatarService_->GetAvatar(request.destAvatarName, request.destAvatarAddress); + if (!invitedAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + auto room = roomService_->GetRoom(request.destRoomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.destRoomId = room->GetRoomId(); + + room->RemoveInvite(srcAvatar->GetAvatarId(), invitedAvatar->GetAvatarId()); +} diff --git a/src/protocol/RemoveInvite.hpp b/src/protocol/RemoveInvite.hpp new file mode 100644 index 0000000..d4c789c --- /dev/null +++ b/src/protocol/RemoveInvite.hpp @@ -0,0 +1,63 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin REMOVEINVITE */ + +struct ReqRemoveInvite { + const ChatRequestType type = ChatRequestType::REMOVEINVITE; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destAvatarName; + std::u16string destAvatarAddress; + std::u16string destRoomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqRemoveInvite& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destAvatarName); + read(ar, data.destAvatarAddress); + read(ar, data.destRoomAddress); + read(ar, data.srcAddress); +} + +/** Begin REMOVEINVITE */ + +struct ResRemoveInvite { + explicit ResRemoveInvite(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::REMOVEINVITE; + uint32_t track; + ChatResultCode result; + uint32_t destRoomId; +}; + +template +void write(StreamT& ar, const ResRemoveInvite& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.destRoomId); +} + +class RemoveInvite { +public: + using RequestType = ReqRemoveInvite; + using ResponseType = ResRemoveInvite; + + RemoveInvite(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/RemoveModerator.cpp b/src/protocol/RemoveModerator.cpp new file mode 100644 index 0000000..6a0be29 --- /dev/null +++ b/src/protocol/RemoveModerator.cpp @@ -0,0 +1,35 @@ +#include "RemoveModerator.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +RemoveModerator::RemoveModerator(GatewayClient * client, const RequestType & request, ResponseType & response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "REMOVEMODERATOR request recieved - removing: " << FromWideString(request.destAvatarName) << "@" + << FromWideString(request.destAvatarAddress) << " from " << FromWideString(request.destRoomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + auto moderatorAvatar = avatarService_->GetAvatar(request.destAvatarName, request.destAvatarAddress); + if (!moderatorAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + auto room = roomService_->GetRoom(request.destRoomAddress); + if (!room) { + throw ChatResultException{ChatResultCode::ADDRESSNOTROOM}; + } + + response.destRoomId = room->GetRoomId(); + + room->RemoveModerator(srcAvatar->GetAvatarId(), moderatorAvatar->GetAvatarId()); +} diff --git a/src/protocol/RemoveModerator.hpp b/src/protocol/RemoveModerator.hpp new file mode 100644 index 0000000..1cfc7dc --- /dev/null +++ b/src/protocol/RemoveModerator.hpp @@ -0,0 +1,63 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin REMOVEMODERATOR */ + +struct ReqRemoveModerator { + const ChatRequestType type = ChatRequestType::REMOVEMODERATOR; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destAvatarName; + std::u16string destAvatarAddress; + std::u16string destRoomAddress; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqRemoveModerator& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destAvatarName); + read(ar, data.destAvatarAddress); + read(ar, data.destRoomAddress); + read(ar, data.srcAddress); +} + +/** Begin REMOVEMODERATOR */ + +struct ResRemoveModerator { + ResRemoveModerator(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::REMOVEMODERATOR; + uint32_t track; + ChatResultCode result; + uint32_t destRoomId; +}; + +template +void write(StreamT& ar, const ResRemoveModerator& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.destRoomId); +} + +class RemoveModerator { +public: + using RequestType = ReqRemoveModerator; + using ResponseType = ResRemoveModerator; + + RemoveModerator(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/SendInstantMessage.cpp b/src/protocol/SendInstantMessage.cpp new file mode 100644 index 0000000..2df2902 --- /dev/null +++ b/src/protocol/SendInstantMessage.cpp @@ -0,0 +1,28 @@ +#include "SendInstantMessage.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +SendInstantMessage::SendInstantMessage( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "SENDINSTANTMESSAGE request received " + << " - from " << request.srcAvatarId << "@" << FromWideString(request.srcAddress) << " to " + << FromWideString(request.destName) << "@" << FromWideString(request.destAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException(ChatResultCode::SRCAVATARDOESNTEXIST); + } + + auto destAvatar = avatarService_->GetAvatar(request.destName, request.destAddress); + if (!destAvatar) { + throw ChatResultException(ChatResultCode::DESTAVATARDOESNTEXIST); + } + + client->SendInstantMessageUpdate(srcAvatar, destAvatar, request.message, request.oob); +} diff --git a/src/protocol/SendInstantMessage.hpp b/src/protocol/SendInstantMessage.hpp new file mode 100644 index 0000000..48fb132 --- /dev/null +++ b/src/protocol/SendInstantMessage.hpp @@ -0,0 +1,62 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin SENDINSTANTMESSAGE */ + +struct ReqSendInstantMessage { + const ChatRequestType type = ChatRequestType::SENDINSTANTMESSAGE; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destName; + std::u16string destAddress; + std::u16string message; + std::u16string oob; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqSendInstantMessage& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destName); + read(ar, data.destAddress); + read(ar, data.message); + read(ar, data.oob); + read(ar, data.srcAddress); +} + +/** Begin SENDINSTANTMESSAGE */ + +struct ResSendInstantMessage { + ResSendInstantMessage(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::SENDINSTANTMESSAGE; + uint32_t track; + ChatResultCode result; +}; + +template +void write(StreamT& ar, const ResSendInstantMessage& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} + +class SendInstantMessage { +public: + using RequestType = ReqSendInstantMessage; + using ResponseType = ResSendInstantMessage; + + SendInstantMessage(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; +}; diff --git a/src/protocol/SendPersistentMessage.cpp b/src/protocol/SendPersistentMessage.cpp new file mode 100644 index 0000000..2856848 --- /dev/null +++ b/src/protocol/SendPersistentMessage.cpp @@ -0,0 +1,48 @@ +#include "SendPersistentMessage.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "PersistentMessageService.hpp" +#include "StreamUtils.hpp" + +#include "easylogging++.h" + +SendPersistentMessage::SendPersistentMessage(GatewayClient * client, const RequestType & request, ResponseType & response) + : avatarService_{client->GetNode()->GetAvatarService()} + , messageService_{client->GetNode()->GetMessageService()} { + LOG(INFO) << "SENDPERSISTENTMESSAGE request received:"; + + auto destAvatar = avatarService_->GetAvatar(request.destName, request.destAddress); + if (!destAvatar) { + throw ChatResultException{ChatResultCode::DESTAVATARDOESNTEXIST}; + } + + PersistentMessage message; + + if (request.avatarPresence) { + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + message.header.fromName = srcAvatar->GetName(); + message.header.fromAddress = srcAvatar->GetAddress(); + } else { + message.header.fromName = request.srcName; + message.header.fromAddress = destAvatar->GetAddress(); + } + + message.header.sentTime = static_cast(std::time(nullptr)); + message.header.avatarId = destAvatar->GetAvatarId(); + message.header.subject = request.subject; + message.header.category = request.category; + message.message = request.msg; + message.oob = request.oob; + + messageService_->StoreMessage(message); + + response.messageId = message.header.messageId; + + client->SendPersistentMessageUpdate(destAvatar, message.header); +} diff --git a/src/protocol/SendPersistentMessage.hpp b/src/protocol/SendPersistentMessage.hpp new file mode 100644 index 0000000..0e6d3bb --- /dev/null +++ b/src/protocol/SendPersistentMessage.hpp @@ -0,0 +1,83 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class PersistentMessageService; +class GatewayClient; + +/** Begin SENDPERSISTENTMESSAGE */ + +struct ReqSendPersistentMessage { + const ChatRequestType type = ChatRequestType::SENDPERSISTENTMESSAGE; + uint32_t track; + uint16_t avatarPresence; + uint32_t srcAvatarId; + std::u16string srcName; + std::u16string destName; + std::u16string destAddress; + std::u16string subject; + std::u16string msg; + std::u16string oob; + std::u16string category; + bool enforceInboxLimit; + uint32_t categoryLimit; +}; + +template +void read(StreamT& ar, ReqSendPersistentMessage& data) { + read(ar, data.track); + read(ar, data.avatarPresence); + + if (data.avatarPresence) { + read(ar, data.srcAvatarId); + } else { + read(ar, data.srcName); + } + + read(ar, data.destName); + read(ar, data.destAddress); + read(ar, data.subject); + read(ar, data.msg); + read(ar, data.oob); + read(ar, data.category); + read(ar, data.enforceInboxLimit); + read(ar, data.categoryLimit); +} + +/** Begin SENDPERSISTENTMESSAGE */ + +struct ResSendPersistentMessage { + ResSendPersistentMessage(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::SENDPERSISTENTMESSAGE; + uint32_t track; + ChatResultCode result; + uint32_t messageId; +}; + +template +void write(StreamT& ar, const ResSendPersistentMessage& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + if (data.result == ChatResultCode::SUCCESS) { + write(ar, data.messageId); + } +} + +class SendPersistentMessage { +public: + using RequestType = ReqSendPersistentMessage; + using ResponseType = ResSendPersistentMessage; + + SendPersistentMessage(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + PersistentMessageService* messageService_; +}; diff --git a/src/protocol/SendRoomMessage.cpp b/src/protocol/SendRoomMessage.cpp new file mode 100644 index 0000000..5774c39 --- /dev/null +++ b/src/protocol/SendRoomMessage.cpp @@ -0,0 +1,33 @@ +#include "SendRoomMessage.hpp" + +#include "ChatAvatarService.hpp" +#include "ChatRoomService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StringUtils.hpp" + +#include "easylogging++.h" + +SendRoomMessage::SendRoomMessage( + GatewayClient* client, const RequestType& request, ResponseType& response) + : avatarService_{client->GetNode()->GetAvatarService()} + , roomService_{client->GetNode()->GetRoomService()} { + LOG(INFO) << "SENDROOMMESSAGE request received " + << " - from " << request.srcAvatarId << "@" << FromWideString(request.srcAddress) + << " to " << FromWideString(request.destRoomAddress); + + auto srcAvatar = avatarService_->GetAvatar(request.srcAvatarId); + if (!srcAvatar) { + throw ChatResultException(ChatResultCode::SRCAVATARDOESNTEXIST); + } + + auto room = roomService_->GetRoom(request.destRoomAddress); + if (!room) { + throw ChatResultException(ChatResultCode::ADDRESSNOTROOM); + } + + response.roomId = room->GetRoomId(); + + client->SendRoomMessageUpdate( + srcAvatar, room, room->GetNextMessageId(), request.message, request.oob); +} diff --git a/src/protocol/SendRoomMessage.hpp b/src/protocol/SendRoomMessage.hpp new file mode 100644 index 0000000..ce7bfc3 --- /dev/null +++ b/src/protocol/SendRoomMessage.hpp @@ -0,0 +1,68 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin SENDROOMMESSAGE */ + +struct ReqSendRoomMessage { + const ChatRequestType type = ChatRequestType::SENDROOMMESSAGE; + uint32_t track; + uint32_t srcAvatarId; + std::u16string destRoomAddress; + std::u16string message; + std::u16string oob; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqSendRoomMessage& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.destRoomAddress); + read(ar, data.message); + read(ar, data.oob); + read(ar, data.srcAddress); +} + +/** Begin SENDROOMMESSAGE */ + +struct ResSendRoomMessage { + explicit ResSendRoomMessage(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + ResSendRoomMessage(uint32_t track_, ChatResultCode result_, uint32_t roomId_) + : track{track_} + , result{result_} + , roomId{roomId_} {} + + const ChatResponseType type = ChatResponseType::SENDROOMMESSAGE; + uint32_t track; + ChatResultCode result; + uint32_t roomId; +}; + +template +void write(StreamT& ar, const ResSendRoomMessage& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.roomId); +} + +class SendRoomMessage { +public: + using RequestType = ReqSendRoomMessage; + using ResponseType = ResSendRoomMessage; + + SendRoomMessage(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/SetApiVersion.cpp b/src/protocol/SetApiVersion.cpp new file mode 100644 index 0000000..a16f0b5 --- /dev/null +++ b/src/protocol/SetApiVersion.cpp @@ -0,0 +1,16 @@ +#include "SetApiVersion.hpp" + +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "StationChatConfig.hpp" + +#include "easylogging++.h" + +SetApiVersion::SetApiVersion( + GatewayClient* client, const RequestType& request, ResponseType& response) { + LOG(INFO) << "SETAPIVERSION request received - version: " << request.version; + response.version = client->GetNode()->GetConfig().version; + response.result = (response.version == request.version) + ? ChatResultCode::SUCCESS + : ChatResultCode::WRONGCHATSERVERFORREQUEST; +} diff --git a/src/protocol/SetApiVersion.hpp b/src/protocol/SetApiVersion.hpp new file mode 100644 index 0000000..cb08a63 --- /dev/null +++ b/src/protocol/SetApiVersion.hpp @@ -0,0 +1,55 @@ + +#pragma once + +#include "ChatEnums.hpp" + +class ChatAvatarService; +class ChatRoomService; +class GatewayClient; + +/** Begin SETAPIVERSION */ + +struct ReqSetApiVersion { + const ChatRequestType type = ChatRequestType::SETAPIVERSION; + uint32_t track; + uint32_t version; +}; + +template +void read(StreamT& ar, ReqSetApiVersion& data) { + read(ar, data.track); + read(ar, data.version); +} + +/** Begin SETAPIVERSION */ + +struct ResSetApiVersion { + ResSetApiVersion(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::SETAPIVERSION; + uint32_t track; + ChatResultCode result; + uint32_t version; +}; + +template +void write(StreamT& ar, const ResSetApiVersion& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + write(ar, data.version); +} + +class SetApiVersion { +public: + using RequestType = ReqSetApiVersion; + using ResponseType = ResSetApiVersion; + + SetApiVersion(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; + ChatRoomService* roomService_; +}; diff --git a/src/protocol/SetAvatarAttributes.cpp b/src/protocol/SetAvatarAttributes.cpp new file mode 100644 index 0000000..070125e --- /dev/null +++ b/src/protocol/SetAvatarAttributes.cpp @@ -0,0 +1,27 @@ +#include "SetAvatarAttributes.hpp" + +#include "ChatAvatarService.hpp" +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" + +#include "easylogging++.h" + +SetAvatarAttributes::SetAvatarAttributes(GatewayClient * client, const RequestType & request, ResponseType & response) + : avatarService_{client->GetNode()->GetAvatarService()} { + LOG(INFO) << "SETAVATARATTRIBUTES request received - avatar: " << request.avatarId; + + auto avatar = avatarService_->GetAvatar(request.avatarId); + if (!avatar) { + throw ChatResultException{ChatResultCode::SRCAVATARDOESNTEXIST}; + } + + response.avatar = avatar; + + if (avatar->GetAttributes() != request.avatarAttributes) { + avatar->SetAttributes(request.avatarAttributes); + + if (request.persistent != 0) { + avatarService_->PersistAvatar(avatar); + } + } +} diff --git a/src/protocol/SetAvatarAttributes.hpp b/src/protocol/SetAvatarAttributes.hpp new file mode 100644 index 0000000..98e09de --- /dev/null +++ b/src/protocol/SetAvatarAttributes.hpp @@ -0,0 +1,63 @@ + +#pragma once + +#include "ChatAvatar.hpp" +#include "ChatEnums.hpp" + +class ChatAvatarService; +class GatewayClient; + +/** Begin SETAVATARATTRIBUTES */ + +struct ReqSetAvatarAttributes { + const ChatRequestType type = ChatRequestType::SETAVATARATTRIBUTES; + uint32_t track; + uint32_t avatarId; + uint32_t avatarAttributes; + uint32_t persistent; + std::u16string srcAddress; +}; + +template +void read(StreamT& ar, ReqSetAvatarAttributes& data) { + read(ar, data.track); + read(ar, data.avatarId); + read(ar, data.avatarAttributes); + read(ar, data.persistent); + read(ar, data.srcAddress); +} + +/** Begin SETAVATARATTRIBUTES */ + +struct ResSetAvatarAttributes { + ResSetAvatarAttributes(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::SETAVATARATTRIBUTES; + uint32_t track; + ChatResultCode result; + const ChatAvatar* avatar; +}; + +template +void write(StreamT& ar, const ResSetAvatarAttributes& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); + + if (data.result == ChatResultCode::SUCCESS) { + write(ar, data.avatar); + } +} + +class SetAvatarAttributes { +public: + using RequestType = ReqSetAvatarAttributes; + using ResponseType = ResSetAvatarAttributes; + + SetAvatarAttributes(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + ChatAvatarService* avatarService_; +}; diff --git a/src/protocol/UpdatePersistentMessage.cpp b/src/protocol/UpdatePersistentMessage.cpp new file mode 100644 index 0000000..f5b0f6b --- /dev/null +++ b/src/protocol/UpdatePersistentMessage.cpp @@ -0,0 +1,14 @@ +#include "UpdatePersistentMessage.hpp" + +#include "GatewayClient.hpp" +#include "GatewayNode.hpp" +#include "PersistentMessageService.hpp" + +#include "easylogging++.h" + +UpdatePersistentMessage::UpdatePersistentMessage(GatewayClient * client, const RequestType & request, ResponseType & response) + : messageService_{client->GetNode()->GetMessageService()} { + LOG(INFO) << "UPDATEPERSISTENTMESSAGE request received"; + messageService_->UpdateMessageStatus( + request.srcAvatarId, request.messageId, request.status); +} diff --git a/src/protocol/UpdatePersistentMessage.hpp b/src/protocol/UpdatePersistentMessage.hpp new file mode 100644 index 0000000..7704477 --- /dev/null +++ b/src/protocol/UpdatePersistentMessage.hpp @@ -0,0 +1,56 @@ + +#pragma once + +#include "ChatEnums.hpp" +#include "PersistentMessage.hpp" + +class PersistentMessageService; +class GatewayClient; + +/** Begin UPDATEPERSISTENTMESSAGE */ + +struct ReqUpdatePersistentMessage { + const ChatRequestType type = ChatRequestType::UPDATEPERSISTENTMESSAGE; + uint32_t track; + uint32_t srcAvatarId; + uint32_t messageId; + PersistentState status; +}; + +template +void read(StreamT& ar, ReqUpdatePersistentMessage& data) { + read(ar, data.track); + read(ar, data.srcAvatarId); + read(ar, data.messageId); + read(ar, data.status); +} + +/** Begin UPDATEPERSISTENTMESSAGE */ + +struct ResUpdatePersistentMessage { + ResUpdatePersistentMessage(uint32_t track_) + : track{track_} + , result{ChatResultCode::SUCCESS} {} + + const ChatResponseType type = ChatResponseType::UPDATEPERSISTENTMESSAGE; + uint32_t track; + ChatResultCode result; +}; + +template +void write(StreamT& ar, const ResUpdatePersistentMessage& data) { + write(ar, data.type); + write(ar, data.track); + write(ar, data.result); +} + +class UpdatePersistentMessage { +public: + using RequestType = ReqUpdatePersistentMessage; + using ResponseType = ResUpdatePersistentMessage; + + UpdatePersistentMessage(GatewayClient* client, const RequestType& request, ResponseType& response); + +private: + PersistentMessageService* messageService_; +}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..cdf669d --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,8 @@ +include_directories(${PROJECT_SOURCE_DIR}/externals/catch + ${PROJECT_SOURCE_DIR}/src) + +add_executable(stationapi_tests + main.cpp) + +target_link_libraries(stationapi_tests + stationapi) diff --git a/tests/main.cpp b/tests/main.cpp new file mode 100644 index 0000000..063e878 --- /dev/null +++ b/tests/main.cpp @@ -0,0 +1,2 @@ +#define CATCH_CONFIG_MAIN +#include "catch.hpp" \ No newline at end of file