pax_global_header00006660000000000000000000000064142260524360014516gustar00rootroot0000000000000052 comment=8ebb24c32302271097080771240620d16147b9c2 libArcus-5.0.0/000077500000000000000000000000001422605243600132645ustar00rootroot00000000000000libArcus-5.0.0/.gitignore000066400000000000000000000016201422605243600152530ustar00rootroot00000000000000# CMake ArcusConfig.cmake ArcusConfigVersion.cmake cmake_install.cmake CPackSourceConfig.cmake # Compiled Object files *.slo *.lo *.o *.obj # Compiled Dynamic libraries *.so *.dylib *.dll *.so.1.0.0 *.so.2 # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app # KDevelop project files *kdev* *.kate-swp # Standard CMake build dir build *.make Makefile CMakeCache.txt install_manifest.txt CMakeFiles/* compile_commands.json examples/Makefile examples/CMakeFiles/* examples/example examples/example.pb.h examples/example.pb.cc examples/example_pb2.py # Python compile cache files *.pyc __pycache__ /examples/cmake_install.cmake /CMakeFiles/CMakeRuleHashes.txt # Netbeans project files nbproject/* # Eclipse+PyDev .project .pydevproject # PyCharm .idea # SIP generated code /python/sipArcuspart*.cpp /python/sipAPIArcus.h # Generated headers /src/ArcusExport.h /cmake-build-* libArcus-5.0.0/ArcusConfig.cmake.in000066400000000000000000000007201422605243600170750ustar00rootroot00000000000000@PACKAGE_INIT@ # We want to have access to protobuf_generate_cpp and other FindProtobuf features. # However, if ProtobufConfig is used instead, there is a CMake option that controls # this, which defaults to OFF. We need to force this option to ON instead. set(protobuf_MODULE_COMPATIBLE ON CACHE "" INTERNAL FORCE) find_package(Protobuf 3.0.0 REQUIRED) get_filename_component(SELF_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) include(${SELF_DIR}/Arcus-targets.cmake) libArcus-5.0.0/CMakeLists.txt000066400000000000000000000115241422605243600160270ustar00rootroot00000000000000project(arcus) cmake_minimum_required(VERSION 3.20) include(cmake/StandardProjectSettings.cmake) include(CMakePackageConfigHelpers) include(GenerateExportHeader) option(BUILD_PYTHON "Build Python bindings for this library" ON) find_package(Protobuf 3.17.1 REQUIRED) set(arcus_SRCS src/Socket.cpp src/SocketListener.cpp src/MessageTypeStore.cpp src/PlatformSocket.cpp src/Error.cpp ) set(arcus_HDRS src/Socket.h src/SocketListener.h src/Types.h src/MessageTypeStore.h src/Error.h ${CMAKE_CURRENT_BINARY_DIR}/src/ArcusExport.h ) set(ARCUS_VERSION 5.0.0) set(ARCUS_SOVERSION 5) if(BUILD_SHARED_LIBS) add_library(Arcus SHARED ${arcus_SRCS}) else() add_library(Arcus STATIC ${arcus_SRCS}) endif() set_project_standards(Arcus) use_threads(Arcus) set_rpath(TARGETS Arcus PATHS "$<$:usr/bin>" "$<$:usr/bin/lib>" "$<$:../lib>" RELATIVE) target_include_directories(Arcus PUBLIC $ $ ${PROTOBUF_INCLUDE_DIR} ) target_link_libraries(Arcus PUBLIC protobuf::libprotobuf) if(WIN32) target_compile_definitions(Arcus PRIVATE -D_WIN32_WINNT=0x0600) # Declare we require Vista or higher, this allows us to use IPv6 functions. target_link_libraries(Arcus PUBLIC Ws2_32) endif() if(${CMAKE_BUILD_TYPE} STREQUAL "Debug" OR ${CMAKE_BUILD_TYPE} STREQUAL "RelWithDebInfo") target_compile_definitions(Arcus PRIVATE -DARCUS_DEBUG) endif() set_target_properties(Arcus PROPERTIES FRAMEWORK FALSE VERSION ${ARCUS_VERSION} SOVERSION ${ARCUS_SOVERSION} PUBLIC_HEADER "${arcus_HDRS}" DEFINE_SYMBOL MAKE_ARCUS_LIB CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN 1 ) generate_export_header(Arcus EXPORT_FILE_NAME src/ArcusExport.h ) # This is required when building out-of-tree. # The compiler won't find the generated header otherwise. include_directories(${CMAKE_BINARY_DIR}/src) install(TARGETS Arcus EXPORT Arcus-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/Arcus ) install(EXPORT Arcus-targets DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus ) configure_package_config_file(ArcusConfig.cmake.in ${CMAKE_BINARY_DIR}/ArcusConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus) write_basic_package_version_file(${CMAKE_BINARY_DIR}/ArcusConfigVersion.cmake VERSION ${ARCUS_VERSION} COMPATIBILITY SameMajorVersion) install(FILES ${CMAKE_BINARY_DIR}/ArcusConfig.cmake ${CMAKE_BINARY_DIR}/ArcusConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Arcus ) # Create the Python bindings if(BUILD_PYTHON) list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake) if(NOT DEFINED Python_VERSION) set(Python_VERSION 3.10 CACHE STRING "Python Version" FORCE) message(STATUS "Setting Python version to ${Python_VERSION}. Set Python_VERSION if you want to compile against an other version.") endif() if(APPLE) set(Python_FIND_FRAMEWORK NEVER) endif() find_package(cpython ${Python_VERSION} QUIET COMPONENTS Interpreter Development) if(NOT TARGET cpython::cpython) find_package(Python ${Python_VERSION} EXACT REQUIRED COMPONENTS Interpreter Development) else() add_library(Python::Python ALIAS cpython::python) set(Python_SITEARCH "${CMAKE_INSTALL_PREFIX}/lib/python${Python_VERSION}/site-packages") set(Python_EXECUTABLE ${cpython_PACKAGE_FOLDER_RELEASE}/bin/python3) set(ENV{PYTHONPATH} ${Python_SITEARCH}) endif() message(STATUS "Linking and building ${project_name} against Python ${Python_VERSION}") find_package(SIP REQUIRED 6.5.0) add_library(pyArcus INTERFACE ${CMAKE_SOURCE_DIR}/python/PythonMessage.cpp) set_project_standards(pyArcus) set_rpath(TARGETS pyArcus PATHS "$<$:usr/bin>" "$<$:usr/bin/lib>" "$<$:../lib>" "$<$:../Resources/lib/>" "../../" RELATIVE) use_threads(pyArcus) target_include_directories(pyArcus INTERFACE $ $ ) target_link_libraries(pyArcus INTERFACE Arcus protobuf::libprotobuf Python::Python) add_sip_module(pyArcus) if (DEFINED Python_SITELIB_LOCAL) install_sip_module(pyArcus ${Python_SITELIB_LOCAL}) else() install_sip_module(pyArcus) endif () endif()libArcus-5.0.0/LICENSE000066400000000000000000000167231422605243600143020ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.libArcus-5.0.0/README.md000066400000000000000000000063351422605243600145520ustar00rootroot00000000000000Arcus ===== This library contains C++ code and Python3 bindings for creating a socket in a thread and using this socket to send and receive messages based on the Protocol Buffers library. It is designed to facilitate the communication between Cura and its backend and similar code. Building ======== To build the library, the following packages are needed: * [Protobuf 3](https://github.com/google/protobuf) (3.0+) * [CMake](https://www.cmake.org) To build the python bindings (default on, disable with -DBUILD_PYTHON=OFF) these additional libries are needed: * python3-dev (3.4+) * python3-sip-dev (4.16+) On Ubuntu 20.04 this can be achieved with: ``` sudo apt install build-essential cmake python3-dev python3-sip-dev protobuf-compiler libprotoc-dev libprotobuf-dev ``` Building the library can be done with: - ```$ mkdir build && cd build``` - ```$ cmake ..``` - ```$ make``` - ```# make install``` This will install to CMake's default install prefix, ```/usr/local```. To change the prefix, set ```CMAKE_INSTALL_PREFIX```. By default, the examples directory is also built. To disable this, set BUILD_EXAMPLES to off. To disable building the Python bindings, set BUILD_PYTHON to OFF. They will be installed into ```$prefix/lib/python3/dist-packages``` on Debian-based systems and into ```$prefix/lib/python3.4/site-packages``` on other computers. Building the Python bindings on 64-bit Windows requires you to build with Microsoft Visual C++ since the module will fail to import if built with MinGW. Using the Socket ================ The socket assumes a very simple and strict wire protocol: one 32-bit integer with a header, one 32-bit integer with the message size, one 32-bit integer with a type id then a byte array containing the message as serialized by Protobuf. The receiving side checks for these fields and will deserialize the message, after which it can be processed by the application. To send or receive messages, the message first needs to be registered on both sides with a call to `registerMessageType()`. You can also register all messages from a Protobuf .proto file with a call to `registerAllMessageTypes()`. For the Python bindings, this is the only supported way of registering since there are no Python classses for individual message types. The Python bindings expose the same API as the Public C++ API, except for the missing `registerMessageType()` and the individual messages. The Python bindings wrap the messages in a class that exposes the message's properties as Python properties, and can thus be set the same way you would set any other Python property. The exception is repeated fields. Currently, only repeated messages are supported, which can be created through the `addRepeatedMessage()` method. `repeatedMessageCount()` will return the number of repeated messages on an object and `getRepeatedMessage()` will get a certain instance of a repeated message. See python/PythonMessage.h for more details. Origin of the Name ================== The name Arcus is from the Roman god Arcus. This god is the roman equivalent of the goddess Iris, who is the personification of the rainbow and the messenger of the gods. Java ==== There is a Java port of libArcus, which can be found [here](https://github.com/Ocarthon/libArcus-Java). libArcus-5.0.0/TODO.md000066400000000000000000000004641422605243600143570ustar00rootroot00000000000000Things to add later =================== - Support for Unix file sockets in addition to streamed local TCP sockets. - Support for DNS resolving. - Find some way to unit test this. - Use a hash function on the message type name to automatically determine message type id. - Improve error handling / checking. libArcus-5.0.0/cmake/000077500000000000000000000000001422605243600143445ustar00rootroot00000000000000libArcus-5.0.0/cmake/CMakeBuilder.py000066400000000000000000000006041422605243600172050ustar00rootroot00000000000000from sipbuild import SetuptoolsBuilder class CMakeBuilder(SetuptoolsBuilder): def __init__(self, project, **kwargs): print("Using the CMake builder") super().__init__(project, **kwargs) def build(self): """ Only Generate the source files """ print("Generating the source files") self._generate_bindings() self._generate_scripts()libArcus-5.0.0/cmake/COPYING-CMAKE-SCRIPTS000066400000000000000000000024571422605243600173520ustar00rootroot00000000000000Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. libArcus-5.0.0/cmake/FindSIP.cmake000066400000000000000000000047511422605243600166110ustar00rootroot00000000000000# Find SIP # ~~~~~~~~ # # SIP website: http://www.riverbankcomputing.co.uk/sip/index.php # # Find the installed version of SIP. FindSIP should be called after Python # has been found. # # This file defines the following variables: # # SIP_VERSION - The version of SIP found expressed as a 6 digit hex number # suitable for comparison as a string. # # SIP_VERSION_STR - The version of SIP found as a human readable string. # # SIP_BINARY_PATH - Path and filename of the SIP command line executable. # # SIP_INCLUDE_DIR - Directory holding the SIP C++ header file. # # SIP_DEFAULT_SIP_DIR - Default directory where .sip files should be installed # into. # Copyright (c) 2007, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. IF(SIP_VERSION OR SIP_BUILD_EXECUTABLE) # Already in cache, be silent SET(SIP_FOUND TRUE) ELSE() FIND_FILE(_find_sip_py FindSIP.py PATHS ${CMAKE_MODULE_PATH} NO_CMAKE_FIND_ROOT_PATH) EXECUTE_PROCESS(COMMAND ${Python_EXECUTABLE} ${_find_sip_py} OUTPUT_VARIABLE sip_config) IF(sip_config) STRING(REGEX REPLACE "^sip_version:([^\n]+).*$" "\\1" SIP_VERSION ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_num:([^\n]+).*$" "\\1" SIP_VERSION_NUM ${sip_config}) STRING(REGEX REPLACE ".*\nsip_version_str:([^\n]+).*$" "\\1" SIP_VERSION_STR ${sip_config}) STRING(REGEX REPLACE ".*\ndefault_sip_dir:([^\n]+).*$" "\\1" SIP_DEFAULT_SIP_DIR ${sip_config}) IF(${SIP_VERSION_STR} VERSION_LESS 5) STRING(REGEX REPLACE ".*\nsip_bin:([^\n]+).*$" "\\1" SIP_BINARY_PATH ${sip_config}) STRING(REGEX REPLACE ".*\nsip_inc_dir:([^\n]+).*$" "\\1" SIP_INCLUDE_DIR ${sip_config}) STRING(REGEX REPLACE ".*\nsip_module_dir:([^\n]+).*$" "\\1" SIP_MODULE_DIR ${sip_config}) ELSE(${SIP_VERSION_STR} VERSION_LESS 5) FIND_PROGRAM(SIP_BUILD_EXECUTABLE sip-build) ENDIF(${SIP_VERSION_STR} VERSION_LESS 5) SET(SIP_FOUND TRUE) ENDIF(sip_config) IF(SIP_FOUND) IF(NOT SIP_FIND_QUIETLY) MESSAGE(STATUS "Found SIP version: ${SIP_VERSION_STR}") ENDIF(NOT SIP_FIND_QUIETLY) ELSE(SIP_FOUND) IF(SIP_FIND_REQUIRED) MESSAGE(FATAL_ERROR "Could not find SIP") ENDIF(SIP_FIND_REQUIRED) ENDIF(SIP_FOUND) ENDIF() include(${CMAKE_SOURCE_DIR}/cmake/SIPMacros.cmake) ADD_DEFINITIONS(-DSIP_VERSION=0x${SIP_VERSION}) libArcus-5.0.0/cmake/FindSIP.py000066400000000000000000000055361422605243600161630ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Copyright (c) 2007, Simon Edwards # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Simon Edwards nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Simon Edwards ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Simon Edwards BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # FindSIP.py # Copyright (c) 2007, Simon Edwards # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. try: import sipbuild print("sip_version:%06.0x" % sipbuild.version.SIP_VERSION) print("sip_version_num:%d" % sipbuild.version.SIP_VERSION) print("sip_version_str:%s" % sipbuild.version.SIP_VERSION_STR) from distutils.sysconfig import get_python_lib python_modules_dir = get_python_lib(plat_specific=1) print("default_sip_dir:%s" % python_modules_dir) except ImportError: # Code for SIP v4 import sipconfig sipcfg = sipconfig.Configuration() print("sip_version:%06.0x" % sipcfg.sip_version) print("sip_version_num:%d" % sipcfg.sip_version) print("sip_version_str:%s" % sipcfg.sip_version_str) print("sip_bin:%s" % sipcfg.sip_bin) print("default_sip_dir:%s" % sipcfg.default_sip_dir) print("sip_inc_dir:%s" % sipcfg.sip_inc_dir) # SIP 4.19.10+ has new sipcfg.sip_module_dir if hasattr(sipcfg, "sip_module_dir"): print("sip_module_dir:%s" % sipcfg.sip_module_dir) else: print("sip_module_dir:%s" % sipcfg.sip_mod_dir) libArcus-5.0.0/cmake/SIPMacros.cmake000066400000000000000000000131001422605243600171410ustar00rootroot00000000000000# Macros for SIP # ~~~~~~~~~~~~~~ set(SIP_ARGS --pep484-pyi --no-protected-is-public) function(add_sip_module MODULE_TARGET) if(NOT SIP_BUILD_EXECUTABLE) set(SIP_BUILD_EXECUTABLE ${CMAKE_PREFIX_PATH}/Scripts/sip-build) endif() message(STATUS "SIP: Generating pyproject.toml") configure_file(${CMAKE_SOURCE_DIR}/pyproject.toml.in ${CMAKE_CURRENT_BINARY_DIR}/pyproject.toml) configure_file(${CMAKE_SOURCE_DIR}/cmake/CMakeBuilder.py ${CMAKE_CURRENT_BINARY_DIR}/CMakeBuilder.py) if(WIN32) set(ext .pyd) set(env_path_sep ";") else() set(ext .so) set(env_path_sep ":") endif() message(STATUS "SIP: Generating source files") execute_process( COMMAND ${CMAKE_COMMAND} -E env "PYTHONPATH=${PYTHONPATH}${env_path_sep}$ENV{PYTHONPATH}${env_path_sep}${CMAKE_CURRENT_BINARY_DIR}" ${SIP_BUILD_EXECUTABLE} ${SIP_ARGS} COMMAND_ECHO STDOUT WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/ ) # This will generate the source-files during the configuration step in CMake. Needed to obtain the sources # Touch the generated files (8 in total) to make them dirty and force them to rebuild message(STATUS "SIP: Touching the source files") set(_sip_output_files) list(LENGTH SIP_FILES _no_outputfiles) foreach(_concat_file_nr RANGE 0 ${_no_outputfiles}) if(${_concat_file_nr} LESS 8) list(APPEND _sip_output_files "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/sip${MODULE_TARGET}part${_concat_file_nr}.cpp") endif() endforeach() # Find the generated source files message(STATUS "SIP: Collecting the generated source files") file(GLOB sip_c "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/*.c") file(GLOB sip_cpp "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/*.cpp") file(GLOB sip_hdr "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/*.h") # Add the user specified source files message(STATUS "SIP: Collecting the user specified source files") get_target_property(usr_src ${MODULE_TARGET} SOURCES) # create the target library and link all the files (generated and user specified message(STATUS "SIP: Linking the interface target against the shared library") set(sip_sources "${sip_c}" "${sip_cpp}" "${usr_src}") if (BUILD_SHARED_LIBS) add_library("sip_${MODULE_TARGET}" SHARED ${sip_sources}) else() add_library("sip_${MODULE_TARGET}" STATIC ${sip_sources}) endif() # Make sure that the library name of the target is the same as the MODULE_TARGET with the appropriate extension target_link_libraries("sip_${MODULE_TARGET}" PRIVATE "${MODULE_TARGET}") set_target_properties("sip_${MODULE_TARGET}" PROPERTIES PREFIX "") set_target_properties("sip_${MODULE_TARGET}" PROPERTIES SUFFIX ${ext}) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES OUTPUT_NAME "${MODULE_TARGET}") # Make sure all rpaths are set from the INTERFACE target get_target_property(_SKIP_BUILD_RPATH ${MODULE_TARGET} SKIP_BUILD_RPATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES SKIP_BUILD_RPATH "${_SKIP_BUILD_RPATH}") get_target_property(_BUILD_WITH_INSTALL_RPATH ${MODULE_TARGET} BUILD_WITH_INSTALL_RPATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES BUILD_WITH_INSTALL_RPATH "${_BUILD_WITH_INSTALL_RPATH}") get_target_property(_INSTALL_RPATH_USE_LINK_PATH ${MODULE_TARGET} INSTALL_RPATH_USE_LINK_PATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES INSTALL_RPATH_USE_LINK_PATH "${_INSTALL_RPATH_USE_LINK_PATH}") get_target_property(_MACOSX_RPATH ${MODULE_TARGET} MACOSX_RPATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES MACOSX_RPATH "${_MACOSX_RPATH}") get_target_property(_INSTALL_RPATH ${MODULE_TARGET} INSTALL_RPATH) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES INSTALL_RPATH "${_INSTALL_RPATH}") # Add the custom command to (re-)generate the files and mark them as dirty. This allows the user to actually work # on the sip definition files without having to reconfigure the complete project. if (NOT DEFINED PYTHONPATH) set(PYTHONPATH "") endif () add_custom_command( TARGET "sip_${MODULE_TARGET}" COMMAND ${CMAKE_COMMAND} -E env "PYTHONPATH=${PYTHONPATH}${env_path_sep}$ENV{PYTHONPATH}${env_path_sep}${CMAKE_CURRENT_BINARY_DIR}" ${SIP_BUILD_EXECUTABLE} ${SIP_ARGS} COMMAND ${CMAKE_COMMAND} -E touch ${_sip_output_files} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/ MAIN_DEPENDENCY ${MODULE_SIP} DEPENDS ${sip_sources} VERBATIM ) set_target_properties("sip_${MODULE_TARGET}" PROPERTIES RESOURCE "${CMAKE_CURRENT_BINARY_DIR}/${MODULE_TARGET}/${MODULE_TARGET}/${MODULE_TARGET}.pyi") endfunction() function(install_sip_module MODULE_TARGET) if(DEFINED ARGV1) set(_install_path ${ARGV1}) else() if(DEFINED Python_SITEARCH) set(_install_path ${Python_SITEARCH}) elseif(DEFINED Python_SITELIB) set(_install_path ${Python_SITELIB}) else() message(FATAL_ERROR "SIP: Specify the site-packages location") endif() endif() message(STATUS "SIP: Installing Python module and PEP 484 file in ${_install_path}") install(TARGETS "sip_${MODULE_TARGET}" ARCHIVE DESTINATION ${_install_path} LIBRARY DESTINATION ${_install_path} RUNTIME DESTINATION ${_install_path} RESOURCE DESTINATION ${_install_path} ) endfunction()libArcus-5.0.0/cmake/StandardProjectSettings.cmake000066400000000000000000000364131422605243600221650ustar00rootroot00000000000000include(GNUInstallDirs) # Standard install dirs if(NOT DEFINED BUILD_SHARED_LIBS) set(BUILD_SHARED_LIBS ON) message(STATUS "Setting BUILD_SHARED_LIBS to ${BUILD_SHARED_LIBS}") endif() # Set a default build type if none was specified if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Release' as none was specified.") set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui, ccmake set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() # Generate compile_commands.json to make it easier to work with clang based tools message(STATUS "Generating compile commands to ${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json") set(CMAKE_EXPORT_COMPILE_COMMANDS ON) option(ENABLE_IPO "Enable Interprocedural Optimization, aka Link Time Optimization (LTO)" ON) if(ENABLE_IPO) include(CheckIPOSupported) check_ipo_supported( RESULT result OUTPUT output) if(result) set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) else() message(SEND_ERROR "IPO is not supported: ${output}") endif() endif() if (NOT MSVC) # Compile with the -fPIC options if supported if(DEFINED POSITION_INDEPENDENT_CODE) # Use the user/Conan set value message(STATUS "Using POSITION_INDEPENDENT_CODE: ${POSITION_INDEPENDENT_CODE}") else() set(POSITION_INDEPENDENT_CODE ON) # Defaults to on message(STATUS "Setting POSITION_INDEPENDENT_CODE: ${POSITION_INDEPENDENT_CODE}") endif() else() # Set Visual Studio flags MD/MDd or MT/MTd if(NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY) if(BUILD_STATIC OR NOT BUILD_SHARED_LIBS) message(STATUS "Setting MT/MTd flags") set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") else() message(STATUS "Setting MD/MDd flags") set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>DLL") endif() endif() endif() # Use C++17 Standard message(STATUS "Setting C++17 support with extensions off and standard required") set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Set common project options for the target function(set_project_standards project_name) get_target_property(type ${project_name} TYPE) if(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") option(ENABLE_BUILD_WITH_TIME_TRACE "Enable -ftime-trace to generate time tracing .json files on clang" OFF) if(ENABLE_BUILD_WITH_TIME_TRACE) message(STATUS "Enabling time tracing for ${project_name}") if (${type} STREQUAL "INTERFACE_LIBRARY") add_compile_definitions(${project_name} INTERFACE -ftime-trace) else() add_compile_definitions(${project_name} PRIVATE -ftime-trace) endif() endif() if (APPLE) message(STATUS "Compiling ${project_name} against libc++") if (${type} STREQUAL "INTERFACE_LIBRARY") target_compile_options(${project_name} INTERFACE "-stdlib=libc++") else() target_compile_options(${project_name} PRIVATE "-stdlib=libc++") endif() endif() endif() endfunction() function(set_rpath) # Sets the RPATHS for targets (Linux and Windows, these can either be absolute paths or relative to the executable # Usage: # set_rpath(TARGETS # PATHS # RELATIVE) # if the RELATIVE option is used the paths will be specified from either $ORIGIN on Linux or @executable_path on Mac set(options RELATIVE) set(oneValueArgs ) set(multiValueArgs TARGETS PATHS) cmake_parse_arguments(SET_RPATH "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) foreach(_target IN ITEMS ${SET_RPATH_TARGETS}) message(STATUS "Setting SKIP_BUILD_RPATH for target ${_target} to FALSE") set_target_properties(${_target} PROPERTIES SKIP_BUILD_RPATH FALSE) message(STATUS "Setting BUILD_WITH_INSTALL_RPATH for target ${_target} to FALSE") set_target_properties(${_target} PROPERTIES BUILD_WITH_INSTALL_RPATH FALSE) message(STATUS "Setting INSTALL_RPATH_USE_LINK_PATH for target ${_target} to TRUE") set_target_properties(${_target} PROPERTIES INSTALL_RPATH_USE_LINK_PATH TRUE) if(APPLE) message(STATUS "Setting MACOSX_RPATH for target ${_target}") set_target_properties(${_target} PROPERTIES MACOSX_RPATH ON) endif() if(SET_RPATH_RELATIVE) list(PREPEND SET_RPATH_PATHS "") if(APPLE) set(loader_path "${SET_RPATH_PATHS}") list(TRANSFORM loader_path PREPEND "@loader_path/") list(TRANSFORM SET_RPATH_PATHS PREPEND "@executable_path/") list(APPEND SET_RPATH_PATHS ${loader_path}) else(LINUX) list(TRANSFORM SET_RPATH_PATHS PREPEND "\$ORIGIN/") endif() endif() set_target_properties(${_target} PROPERTIES INSTALL_RPATH "${SET_RPATH_PATHS}") message(STATUS "Setting install RPATH for target ${_target} to ${SET_RPATH_PATHS}") endforeach() endfunction() # Ultimaker uniform Python linking method function(use_python project_name) find_package(Python REQUIRED) get_target_property(type ${project_name} TYPE) if(${type} STREQUAL "INTERFACE_LIBRARY") target_link_libraries(${project_name} INTERFACE Python::Python) else() target_link_libraries(${project_name} PRIVATE Python::Python) endif() message(STATUS "Linking and building ${project_name} against Python ${Python_VERSION}") endfunction() # Ultimaker uniform Thread linking method function(use_threads project_name) message(STATUS "Enabling threading support for ${project_name}") set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads) get_target_property(type ${project_name} TYPE) if (${type} STREQUAL "INTERFACE_LIBRARY") target_link_libraries(${project_name} INTERFACE Threads::Threads) else() target_link_libraries(${project_name} PRIVATE Threads::Threads) endif() endfunction() # https://github.com/lefticus/cppbestpractices/blob/master/02-Use_the_Tools_Available.md function(set_project_warnings project_name) message(STATUS "Setting warnings for ${project_name}") set(MSVC_WARNINGS /W4 # Baseline reasonable warnings /w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss of data /w14254 # 'operator': conversion from 'type1:field_bits' to 'type2:field_bits', possible loss of data /w14263 # 'function': member function does not override any base class virtual member function /w14265 # 'classname': class has virtual functions, but destructor is not virtual instances of this class may not # be destructed correctly /w14287 # 'operator': unsigned/negative constant mismatch /we4289 # nonstandard extension used: 'variable': loop control variable declared in the for-loop is used outside # the for-loop scope /w14296 # 'operator': expression is always 'boolean_value' /w14311 # 'variable': pointer truncation from 'type1' to 'type2' /w14545 # expression before comma evaluates to a function which is missing an argument list /w14546 # function call before comma missing argument list /w14547 # 'operator': operator before comma has no effect; expected operator with side-effect /w14549 # 'operator': operator before comma has no effect; did you intend 'operator'? /w14555 # expression has no effect; expected expression with side- effect /w14619 # pragma warning: there is no warning number 'number' /w14640 # Enable warning on thread un-safe static member initialization /w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may cause unexpected runtime behavior. /w14905 # wide string literal cast to 'LPSTR' /w14906 # string literal cast to 'LPWSTR' /w14928 # illegal copy-initialization; more than one user-defined conversion has been implicitly applied /permissive- # standards conformance mode for MSVC compiler. ) set(CLANG_WARNINGS -Wall -Wextra # reasonable and standard -Wshadow # warn the user if a variable declaration shadows one from a parent context -Wnon-virtual-dtor # warn the user if a class with virtual functions has a non-virtual destructor. This helps # catch hard to track down memory errors -Wold-style-cast # warn for c-style casts -Wcast-align # warn for potential performance problem casts -Wunused # warn on anything being unused -Woverloaded-virtual # warn if you overload (not override) a virtual function -Wpedantic # warn if non-standard C++ is used -Wconversion # warn on type conversions that may lose data -Wsign-conversion # warn on sign conversions -Wnull-dereference # warn if a null dereference is detected -Wdouble-promotion # warn if float is implicit promoted to double -Wformat=2 # warn on security issues around functions that format output (ie printf) ) set(GCC_WARNINGS ${CLANG_WARNINGS} -Wmisleading-indentation # warn if indentation implies blocks where blocks do not exist -Wduplicated-cond # warn if if / else chain has duplicated conditions -Wduplicated-branches # warn if if / else branches have duplicated code -Wlogical-op # warn about logical operations being used where bitwise were probably wanted -Wuseless-cast # warn if you perform a cast to the same type ) if(MSVC) set(PROJECT_WARNINGS ${MSVC_WARNINGS}) elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") set(PROJECT_WARNINGS ${CLANG_WARNINGS}) elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set(PROJECT_WARNINGS ${GCC_WARNINGS}) else() message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.") endif() get_target_property(type ${project_name} TYPE) if (${type} STREQUAL "INTERFACE_LIBRARY") target_compile_options(${project_name} INTERFACE ${PROJECT_WARNINGS}) else() target_compile_options(${project_name} PRIVATE ${PROJECT_WARNINGS}) endif() endfunction() # This function will prevent in-source builds function(assure_out_of_source_builds) # make sure the user doesn't play dirty with symlinks get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH) get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH) # disallow in-source builds if("${srcdir}" STREQUAL "${bindir}") message("######################################################") message("Warning: in-source builds are disabled") message("Please create a separate build directory and run cmake from there") message("######################################################") message(FATAL_ERROR "Quitting configuration") endif() endfunction() option(ALLOW_IN_SOURCE_BUILD "Allow building in your source folder. Strongly discouraged" OFF) if(NOT ALLOW_IN_SOURCE_BUILD) assure_out_of_source_builds() endif() function(enable_sanitizers project_name) if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") option(ENABLE_COVERAGE "Enable coverage reporting for gcc/clang" FALSE) if(ENABLE_COVERAGE) target_compile_options(${project_name} INTERFACE --coverage -O0 -g) target_link_libraries(${project_name} INTERFACE --coverage) endif() set(SANITIZERS "") option(ENABLE_SANITIZER_ADDRESS "Enable address sanitizer" FALSE) if(ENABLE_SANITIZER_ADDRESS) list(APPEND SANITIZERS "address") endif() option(ENABLE_SANITIZER_LEAK "Enable leak sanitizer" FALSE) if(ENABLE_SANITIZER_LEAK) list(APPEND SANITIZERS "leak") endif() option(ENABLE_SANITIZER_UNDEFINED_BEHAVIOR "Enable undefined behavior sanitizer" FALSE) if(ENABLE_SANITIZER_UNDEFINED_BEHAVIOR) list(APPEND SANITIZERS "undefined") endif() option(ENABLE_SANITIZER_THREAD "Enable thread sanitizer" FALSE) if(ENABLE_SANITIZER_THREAD) if("address" IN_LIST SANITIZERS OR "leak" IN_LIST SANITIZERS) message(WARNING "Thread sanitizer does not work with Address and Leak sanitizer enabled") else() list(APPEND SANITIZERS "thread") endif() endif() option(ENABLE_SANITIZER_MEMORY "Enable memory sanitizer" FALSE) if(ENABLE_SANITIZER_MEMORY AND CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") if("address" IN_LIST SANITIZERS OR "thread" IN_LIST SANITIZERS OR "leak" IN_LIST SANITIZERS) message(WARNING "Memory sanitizer does not work with Address, Thread and Leak sanitizer enabled") else() list(APPEND SANITIZERS "memory") endif() endif() list( JOIN SANITIZERS "," LIST_OF_SANITIZERS) endif() if(LIST_OF_SANITIZERS) if(NOT "${LIST_OF_SANITIZERS}" STREQUAL "") target_compile_options(${project_name} INTERFACE -fsanitize=${LIST_OF_SANITIZERS}) target_link_options(${project_name} INTERFACE -fsanitize=${LIST_OF_SANITIZERS}) endif() endif() endfunction() option(ENABLE_CPPCHECK "Enable static analysis with cppcheck" OFF) option(ENABLE_CLANG_TIDY "Enable static analysis with clang-tidy" OFF) option(ENABLE_INCLUDE_WHAT_YOU_USE "Enable static analysis with include-what-you-use" OFF) if(ENABLE_CPPCHECK) find_program(CPPCHECK cppcheck) if(CPPCHECK) message(STATUS "Using cppcheck") set(CMAKE_CXX_CPPCHECK ${CPPCHECK} --suppress=missingInclude --enable=all --inline-suppr --inconclusive -i ${CMAKE_SOURCE_DIR}/imgui/lib) else() message(WARNING "cppcheck requested but executable not found") endif() endif() if(ENABLE_CLANG_TIDY) find_program(CLANGTIDY clang-tidy) if(CLANGTIDY) message(STATUS "Using clang-tidy") set(CMAKE_CXX_CLANG_TIDY ${CLANGTIDY} -extra-arg=-Wno-unknown-warning-option) else() message(WARNING "clang-tidy requested but executable not found") endif() endif() if(ENABLE_INCLUDE_WHAT_YOU_USE) find_program(INCLUDE_WHAT_YOU_USE include-what-you-use) if(INCLUDE_WHAT_YOU_USE) message(STATUS "Using include-what-you-use") set(CMAKE_CXX_INCLUDE_WHAT_YOU_USE ${INCLUDE_WHAT_YOU_USE}) else() message(WARNING "include-what-you-use requested but executable not found") endif() endif()libArcus-5.0.0/cmake/cpack_config_deb_mingw64.cmake000066400000000000000000000022701422605243600221420ustar00rootroot00000000000000set(CPACK_GENERATOR "DEB") set(CPACK_CMAKE_GENERATOR "Unix Makefiles") set(CPACK_PACKAGE_NAME "cura-libarcus-mingw-w64-dev") set(CPACK_PACKAGE_VENDOR "Ultimaker B.V.") set(CPACK_PACKAGE_DESCRIPTION "(Cura) libArcus static library for MinGW-w64 targeting Win64") set(CPACK_PACKAGE_CONTACT "Lipu Fei ") set(CPACK_PACKAGING_INSTALL_PREFIX "/usr/x86_64-w64-mingw32") set(CPACK_PACKAGE_VERSION "4.5.0") set(CPACK_DEBIAN_PACKAGE_RELEASE 1) set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}_${CPACK_PACKAGE_VERSION}-${CPACK_DEBIAN_PACKAGE_RELEASE}") set(CPACK_DEBIAN_PACKAGE_NAME "${CPACK_PACKAGE_NAME}") set(CPACK_DEBIAN_PACKAGE_DESCRIPTION "${CPACK_PACKAGE_DESCRIPTION}") set(CPACK_DEBIAN_PACKAGE_MAINTAINER "${CPACK_PACKAGE_CONTACT}") set(CPACK_DEBIAN_PACKAGE_VERSION "${CPACK_PACKAGE_VERSION}") set(CPACK_DEBIAN_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}.deb") set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "all") set(CPACK_DEBIAN_PACKAGE_SECTION "devel") set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional") set(_arcus_DEB_DEPENDS "cura-libprotobuf-mingw-w64-dev (>= 3.9.2)" ) string(REPLACE ";" ", " _arcus_DEB_DEPENDS "${_arcus_DEB_DEPENDS}") set(CPACK_DEBIAN_PACKAGE_DEPENDS "${_arcus_DEB_DEPENDS}") libArcus-5.0.0/conanfile.py000066400000000000000000000070641422605243600156030ustar00rootroot00000000000000import os from conan.tools.cmake import CMakeToolchain, CMakeDeps, CMake from conan.tools.files.packager import AutoPackager from conans import ConanFile, tools required_conan_version = ">=1.44.1" class ArcusConan(ConanFile): name = "arcus" license = "LGPL-3.0" author = "Ultimaker B.V." url = "https://github.com/Ultimaker/libArcus" description = "Communication library between internal components for Ultimaker software" topics = ("conan", "python", "binding", "sip", "cura", "protobuf", "c++") settings = "os", "compiler", "build_type", "arch" revision_mode = "scm" exports = "LICENSE*" options = { "build_python": [True, False], # TODO: Fix the Sip recipe first in the https://github.com/ultimaker/conan-ultimaker-index.git "shared": [True, False], "fPIC": [True, False], "examples": [True, False] } default_options = { "build_python": False, "shared": True, "fPIC": True, "examples": False } scm = { "type": "git", "subfolder": ".", "url": "auto", "revision": "auto" } @property def _site_packages(self): return "site-packages" def requirements(self): # TODO: Add the Python and SIP requirements. First get it up and running for CuraEngine CI/CT self.requires("protobuf/3.17.1") def config_options(self): self.options["protobuf"].shared = self.options.shared def configure(self): if self.options.shared or self.settings.compiler == "Visual Studio": del self.options.fPIC def validate(self): if self.settings.compiler.get_safe("cppstd"): tools.check_min_cppstd(self, 17) def generate(self): cmake = CMakeDeps(self) cmake.build_context_activated = ["protobuf"] cmake.build_context_build_modules = ["protobuf"] cmake.build_context_suffix = {"protobuf": "_BUILD"} cmake.generate() tc = CMakeToolchain(self) if self.settings.compiler == "Visual Studio": tc.blocks["generic_system"].values["generator_platform"] = None tc.blocks["generic_system"].values["toolset"] = None tc.variables["ALLOW_IN_SOURCE_BUILD"] = True tc.variables["BUILD_PYTHON"] = self.options.build_python tc.generate() def build(self): cmake = CMake(self) cmake.configure() cmake.build() def package(self): self.copy("*Arcus.*", dst="lib", src=self.build_folder, excludes=("python/*", "CMakeFiles/*")) self.copy("*.h", dst="include/Arcus", src=f"{self.source_folder}/src", excludes=("./PlatformSocket_p.h", "./Socket_p.h", "./WireMessage_p.h")) self.copy("*.h", dst="include/Arcus", src=f"{self.build_folder}/src") def package_info(self): # To stay compatible with the FindArcus module. This should be removed when we fully switch to Conan self.cpp_info.set_property("cmake_file_name", "Arcus") self.cpp_info.set_property("cmake_target_aliases", ["Arcus"]) self.cpp_info.libs = ["Arcus"] self.cpp_info.defines.append("ARCUS") if self.settings.build_type == "Debug": self.cpp_info.defines.append("ARCUS_DEBUG") if self.settings.os in ["Linux", "FreeBSD", "Macos"]: self.cpp_info.system_libs.append("pthread") elif self.settings.os == "Windows": self.cpp_info.system_libs.append("ws2_32") if self.options.build_python: self.runenv_info.append("PYTHONPATH", os.path.join(self.package_folder, self._site_packages))libArcus-5.0.0/pyproject.toml.in000066400000000000000000000006261422605243600166110ustar00rootroot00000000000000[build-system] requires = ["sip >=6, <7"] build-backend = "sipbuild.api" [tool.sip.metadata] name = "pyArcus" [tool.sip.project] builder-factory = "CMakeBuilder" sip-files-dir = "${CMAKE_CURRENT_SOURCE_DIR}/python/" sip-include-dirs = ["CMAKE_CURRENT_SOURCE_DIR/python/"] build-dir = "${CMAKE_CURRENT_BINARY_DIR}/pyArcus/" [tool.sip.bindings.pyArcus] exceptions = true release-gil = true concatenate = 8libArcus-5.0.0/python/000077500000000000000000000000001422605243600146055ustar00rootroot00000000000000libArcus-5.0.0/python/Error.sip000066400000000000000000000031121422605243600164100ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ enum class ErrorCode { UnknownError, CreationError, ConnectFailedError, BindFailedError, AcceptFailedError, SendFailedError, ReceiveFailedError, UnknownMessageTypeError, ParseFailedError, ConnectionResetError, MessageRegistrationFailedError, InvalidStateError, InvalidMessageError, Debug, }; class Error { %TypeHeaderCode #include "Error.h" %End public: Error(); Error(ErrorCode error_code, const std::string& error_message); Error(const Error& error); ErrorCode getErrorCode() const; std::string getErrorMessage() const; bool isFatalError() const; bool isValid() const; void setFatalError(bool fatal); PyObject* __repr__(); %MethodCode return PyUnicode_FromString(sipCpp->toString().c_str()); %End }; libArcus-5.0.0/python/PythonMessage.cpp000066400000000000000000000202751422605243600201050ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #include "PythonMessage.h" #include #include #include using namespace Arcus; using namespace google::protobuf; PythonMessage::PythonMessage(google::protobuf::Message* message) { _message = message; _reflection = message->GetReflection(); _descriptor = message->GetDescriptor(); } Arcus::PythonMessage::PythonMessage(const MessagePtr& message) { _shared_message = message; _message = message.get(); _reflection = message->GetReflection(); _descriptor = message->GetDescriptor(); } PythonMessage::~PythonMessage() { } std::string Arcus::PythonMessage::getTypeName() const { return _message->GetTypeName(); } MessagePtr Arcus::PythonMessage::getSharedMessage() const { return _shared_message; } bool Arcus::PythonMessage::__hasattr__(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); return bool(field); } PyObject* Arcus::PythonMessage::__getattr__(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } switch(field->type()) { case FieldDescriptor::TYPE_FLOAT: return PyFloat_FromDouble(_reflection->GetFloat(*_message, field)); case FieldDescriptor::TYPE_DOUBLE: return PyFloat_FromDouble(_reflection->GetDouble(*_message, field)); case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_SINT32: case FieldDescriptor::TYPE_SFIXED32: return PyLong_FromLong(_reflection->GetInt32(*_message, field)); case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: return PyLong_FromLongLong(_reflection->GetInt64(*_message, field)); case FieldDescriptor::TYPE_UINT32: return PyLong_FromUnsignedLong(_reflection->GetUInt32(*_message, field)); case FieldDescriptor::TYPE_UINT64: return PyLong_FromUnsignedLongLong(_reflection->GetUInt64(*_message, field)); case FieldDescriptor::TYPE_BOOL: if(_reflection->GetBool(*_message, field)) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } case FieldDescriptor::TYPE_BYTES: { std::string data = _reflection->GetString(*_message, field); return PyBytes_FromStringAndSize(data.c_str(), data.size()); } case FieldDescriptor::TYPE_STRING: return PyUnicode_FromString(_reflection->GetString(*_message, field).c_str()); case FieldDescriptor::TYPE_ENUM: return PyLong_FromLong(_reflection->GetEnumValue(*_message, field)); default: PyErr_SetString(PyExc_ValueError, "Could not handle value of field"); return nullptr; } } void Arcus::PythonMessage::__setattr__(const std::string& field_name, PyObject* value) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return; } switch(field->type()) { case FieldDescriptor::TYPE_FLOAT: _reflection->SetFloat(_message, field, PyFloat_AsDouble(value)); break; case FieldDescriptor::TYPE_DOUBLE: _reflection->SetDouble(_message, field, PyFloat_AsDouble(value)); break; case FieldDescriptor::TYPE_INT32: case FieldDescriptor::TYPE_SFIXED32: case FieldDescriptor::TYPE_FIXED32: case FieldDescriptor::TYPE_SINT32: _reflection->SetInt32(_message, field, PyLong_AsLong(value)); break; case FieldDescriptor::TYPE_INT64: case FieldDescriptor::TYPE_FIXED64: case FieldDescriptor::TYPE_SINT64: case FieldDescriptor::TYPE_SFIXED64: _reflection->SetInt64(_message, field, PyLong_AsLongLong(value)); break; case FieldDescriptor::TYPE_UINT32: _reflection->SetUInt32(_message, field, PyLong_AsUnsignedLong(value)); break; case FieldDescriptor::TYPE_UINT64: _reflection->SetUInt64(_message, field, PyLong_AsUnsignedLongLong(value)); break; case FieldDescriptor::TYPE_BOOL: if(value == Py_True) { _reflection->SetBool(_message, field, true); } else { _reflection->SetBool(_message, field, false); } break; case FieldDescriptor::TYPE_BYTES: { Py_buffer buffer; PyObject_GetBuffer(value, &buffer, PyBUF_SIMPLE); std::string str(reinterpret_cast(buffer.buf), buffer.len); _reflection->SetString(_message, field, str); break; } case FieldDescriptor::TYPE_STRING: _reflection->SetString(_message, field, PyUnicode_AsUTF8(value)); break; case FieldDescriptor::TYPE_ENUM: { if(PyUnicode_Check(value)) { auto enum_value = _descriptor->FindEnumValueByName(PyUnicode_AsUTF8(value)); _reflection->SetEnum(_message, field, enum_value); } else { _reflection->SetEnumValue(_message, field, PyLong_AsLong(value)); } break; } default: PyErr_SetString(PyExc_ValueError, "Could not handle value of field"); break; } } PythonMessage* Arcus::PythonMessage::addRepeatedMessage(const std::string& field_name) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } Message* message = _reflection->AddMessage(_message, field); return new PythonMessage(message); } int PythonMessage::repeatedMessageCount(const std::string& field_name) const { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return -1; } return _reflection->FieldSize(*_message, field); } PythonMessage* Arcus::PythonMessage::getMessage(const std::string& field_name) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } return new PythonMessage(_reflection->MutableMessage(_message, field)); } PythonMessage* Arcus::PythonMessage::getRepeatedMessage(const std::string& field_name, int index) { auto field = _descriptor->FindFieldByName(field_name); if(!field) { PyErr_SetString(PyExc_AttributeError, field_name.c_str()); return nullptr; } if(index < 0 || index > _reflection->FieldSize(*_message, field)) { PyErr_SetString(PyExc_IndexError, field_name.c_str()); return nullptr; } return new PythonMessage(_reflection->MutableRepeatedMessage(_message, field, index)); } int Arcus::PythonMessage::getEnumValue(const std::string& enum_value) const { auto field = _descriptor->FindEnumValueByName(enum_value); if(!field) { return -1; } return field->number(); } libArcus-5.0.0/python/PythonMessage.h000066400000000000000000000101301422605243600175370ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #ifndef ARCUS_PYTHON_MESSAGE_H #define ARCUS_PYTHON_MESSAGE_H #include #include "Types.h" namespace google { namespace protobuf { class Descriptor; class Reflection; } } namespace Arcus { /** * A simple wrapper around a Protobuf message so it can be used from Python. * * This class wraps a Protobuf message and makes it possible to get and set * values from the message. Message properties are exposed as Python properties * so can be set using things like `message.data = b"something"` from Python. * * Repeated messages are supported, using addRepeatedMessage, repeatedMessageCount * and getRepeatedMessage. A repeated message is returned as a PythonMessage object * so exposes the same API as the top level message. */ class PythonMessage { public: PythonMessage(google::protobuf::Message* message); PythonMessage(const MessagePtr& message); virtual ~PythonMessage(); /** * Get the message type name of this message. */ std::string getTypeName() const; /** * Python property interface. */ bool __hasattr__(const std::string& field_name) const; PyObject* __getattr__(const std::string& field_name) const; void __setattr__(const std::string& name, PyObject* value); /** * Add an instance of a Repeated Message to a specific field. * * \param field_name The name of the field to add a message to. * * \return A pointer to an instance of PythonMessage wrapping the new Message in the field. */ PythonMessage* addRepeatedMessage(const std::string& field_name); /** * Get the number of messages in a repeated message field. */ int repeatedMessageCount(const std::string& field_name) const; /** * Get a specific instance of a message in a repeated message field. * * \param field_name The name of a repeated message field to get an instance from. * \param index The index of the item to get in the repeated field. * * \return A pointer to an instance of PythonMessage wrapping the specified repeated message. */ PythonMessage* getRepeatedMessage(const std::string& field_name, int index); /** * Get a specific instance of a message in a message field. * * \param field_name The name of a repeated message field to get an instance from. * * \return A pointer to an instance of PythonMessage wrapping the specified repeated message. */ PythonMessage* getMessage(const std::string& field_name); /** * Get the value of a certain enumeration. * * \param enum_value The fully-qualified name of an Enum value. * * \return The integer value of the specified enum. */ int getEnumValue(const std::string& enum_value) const; /** * Internal. */ MessagePtr getSharedMessage() const; private: MessagePtr _shared_message; google::protobuf::Message* _message; const google::protobuf::Reflection* _reflection; const google::protobuf::Descriptor* _descriptor; }; } #endif //ARCUS_MESSAGE_PTR_H libArcus-5.0.0/python/PythonMessage.sip000066400000000000000000000034061422605243600201130ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ class PythonMessage { %TypeHeaderCode #include "PythonMessage.h" %End public: virtual ~PythonMessage(); std::string getTypeName() const; bool __hasattr__(const std::string&) const /AllowNone/; PyObject* __getattr__(const std::string&) const /AllowNone, HoldGIL/; void __setattr__(const std::string&, PyObject*) /AllowNone/; %MethodCode sipCpp->__setattr__(*a0, a1); %End void __delattr__(const std::string&); %MethodCode PyErr_SetString(PyExc_NotImplementedError, "__delattr__ not supported on messages."); return 0; %End PythonMessage* addRepeatedMessage(const std::string& field_name) /TransferBack/; int repeatedMessageCount(const std::string& field_name) const; PythonMessage* getRepeatedMessage(const std::string& field_name, int index) /TransferBack/; PythonMessage* getMessage(const std::string& field_name) /TransferBack/; int getEnumValue(const std::string& enum_value) const; private: PythonMessage(); }; libArcus-5.0.0/python/SocketListener.sip000066400000000000000000000021631422605243600202620ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ class SocketListener { %TypeHeaderCode #include "SocketListener.h" %End public: SocketListener(); virtual ~SocketListener(); Socket* getSocket(); virtual void stateChanged(SocketState newState) = 0 /HoldGIL/; virtual void messageReceived() = 0 /HoldGIL/; virtual void error(const Error& error) = 0 /HoldGIL/; }; libArcus-5.0.0/python/Types.sip000066400000000000000000000072261422605243600164350ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ // Convert a python str object to a std::string. %MappedType std::string { %TypeHeaderCode #include %End %ConvertFromTypeCode // convert an std::string to a Python (unicode) string PyObject* newstring; newstring = PyUnicode_DecodeUTF8(sipCpp->c_str(), sipCpp->length(), NULL); if(newstring == NULL) { PyErr_Clear(); newstring = PyBytes_FromString(sipCpp->c_str()); } return newstring; %End %ConvertToTypeCode // Allow a Python string (or a unicode string) whenever a string is // expected. // If argument is a Unicode string, just decode it to UTF-8 // If argument is a Python string, assume it's UTF-8 if (sipIsErr == NULL) return (PyBytes_Check(sipPy) || PyUnicode_Check(sipPy)); if (sipPy == Py_None) { *sipCppPtr = new std::string; return 1; } if (PyUnicode_Check(sipPy)) { PyObject* s = PyUnicode_AsEncodedString(sipPy, "UTF-8", ""); *sipCppPtr = new std::string(PyBytes_AS_STRING(s)); Py_DECREF(s); return 1; } if (PyBytes_Check(sipPy)) { *sipCppPtr = new std::string(PyBytes_AS_STRING(sipPy)); return 1; } return 0; %End }; // Convert a MessagePtr (aka std::shared_ptr) to a PythonMessage* %MappedType MessagePtr { %TypeHeaderCode #include #include "PythonMessage.h" %End %ConvertFromTypeCode // Convert a Protobuf message to a Python object if(!(*sipCpp)) { PyErr_SetString(PyExc_ValueError, "Unknown message type"); return NULL; } const sipTypeDef* message_type = sipFindType("PythonMessage"); PythonMessage* message = new PythonMessage(*sipCpp); sipTransferObj = Py_None; PyObject* msg = sipConvertFromType(message, message_type, sipTransferObj); if(!msg) { delete message; return NULL; } return msg; %End %ConvertToTypeCode // Convert a Python object to a Protobuf message const sipTypeDef* message_type = sipFindType("PythonMessage"); if(sipIsErr == NULL) { return sipCanConvertToType(sipPy, message_type, SIP_NOT_NONE); } if(sipCanConvertToType(sipPy, message_type, SIP_NOT_NONE)) { int iserr = 0; int state = 0; PythonMessage* message = reinterpret_cast(sipConvertToType(sipPy, message_type, NULL, 0, &state, &iserr)); if(iserr != 0) { PyErr_SetString(PyExc_ValueError, "Could not convert to Message"); return 0; } MessagePtr msg = message->getSharedMessage(); *sipCppPtr = new MessagePtr(msg); sipReleaseType(message, message_type, state); } return sipGetState(sipTransferObj); %End }; %UnitCode #include "Types.h" %End enum class SocketState { Initial, Connecting, Connected, Opening, Listening, Closing, Closed, Error }; libArcus-5.0.0/python/pyArcus.sip000066400000000000000000000033311422605243600167500ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ %Module(name = pyArcus, call_super_init = True) %Include Types.sip %Include SocketListener.sip %Include PythonMessage.sip %Include Error.sip %ModuleHeaderCode using namespace Arcus; %End class Socket { %TypeHeaderCode #include "Socket.h" %End public: Socket(); virtual ~Socket(); SocketState getState() const; Error getLastError() const; void clearError(); void addListener(SocketListener* listener /TransferThis/); void removeListener(SocketListener* listener); void connect(const std::string& address, int port); void listen(const std::string& address, int port); void close() /ReleaseGIL/; void reset() /ReleaseGIL/; void sendMessage(MessagePtr message); MessagePtr takeNextMessage(); MessagePtr createMessage(const std::string& type_name); bool registerAllMessageTypes(const std::string& file_name); private: Socket(const Socket&); Socket& operator=(const Socket&); }; libArcus-5.0.0/src/000077500000000000000000000000001422605243600140535ustar00rootroot00000000000000libArcus-5.0.0/src/Error.cpp000066400000000000000000000045421422605243600156550ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #include "Error.h" #include using namespace Arcus; Arcus::Error::Error() : _error_code(ErrorCode::UnknownError), _fatal_error(false), _native_error_code(0) { } Arcus::Error::Error(ErrorCode error_code, const std::string& error_message) : _error_code(ErrorCode::UnknownError), _fatal_error(false), _native_error_code(0) { _error_code = error_code; _error_message = error_message; } ErrorCode Arcus::Error::getErrorCode() const { return _error_code; } std::string Arcus::Error::getErrorMessage() const { return _error_message; } bool Arcus::Error::isFatalError() const { return _fatal_error; } bool Arcus::Error::isValid() const { return _error_code != ErrorCode::UnknownError || !_error_message.empty(); } int Arcus::Error::getNativeErrorCode() const { return _native_error_code; } void Arcus::Error::setFatalError(bool fatal) { _fatal_error = fatal; } void Arcus::Error::setNativeErrorCode(int code) { _native_error_code = code; } std::string Arcus::Error::toString() const { static std::string error_start("Arcus Error ("); static std::string fatal_error_start("Arcus Fatal Error ("); static std::string native_prefix(", native "); static std::string message_separator("): "); return (_fatal_error ? fatal_error_start : error_start) + std::to_string(static_cast(_error_code)) + (_native_error_code != 0 ? native_prefix + std::to_string(_native_error_code) : "") + message_separator + _error_message; } std::ostream & operator<<(std::ostream& stream, const Arcus::Error& error) { return stream << error.toString(); } libArcus-5.0.0/src/Error.h000066400000000000000000000065531422605243600153260ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #ifndef ARCUS_ERROR_H #define ARCUS_ERROR_H #include "ArcusExport.h" #include "Types.h" namespace Arcus { /** * Possible error codes. */ enum class ErrorCode { UnknownError, ///< An unknown error occurred. CreationError, ///< Socket creation failed. ConnectFailedError, ///< Connection failed. BindFailedError, ///< Bind to IP and port failed. AcceptFailedError, ///< Accepting an incoming connection failed. SendFailedError, ///< Sending a message failed. ReceiveFailedError, ///< Receiving a message failed. UnknownMessageTypeError, ///< Received a message with an unknown message type. ParseFailedError, ///< Parsing the received message failed. ConnectionResetError, ///< The connection was reset by peer. MessageRegistrationFailedError, ///< Message registration failed. InvalidStateError, ///< Socket is in an invalid state. InvalidMessageError, ///< Message being handled is a nullptr or otherwise invalid. Debug, //Debug messages }; /** * A class representing an error with an error code and an error message. */ class ARCUS_EXPORT Error { public: /** * Default constructor. */ Error(); /** * Create an error with an error code and error message. */ Error(ErrorCode error_code, const std::string& error_message); /** * Get the error code of this error. */ ErrorCode getErrorCode() const; /** * Get the error message. */ std::string getErrorMessage() const; /** * Is this error considered a fatal error? */ bool isFatalError() const; /** * Is this error valid? */ bool isValid() const; /** * The error code as reported by the platform. */ int getNativeErrorCode() const; /** * Set whether this should be considered a fatal error. */ void setFatalError(bool fatal); /** * Set the native error code, if any. */ void setNativeErrorCode(int code); /** * Convert the error to a string that can be printed. */ std::string toString() const; private: ErrorCode _error_code; std::string _error_message; bool _fatal_error; int _native_error_code; }; } // Output the error to a stream. ARCUS_EXPORT std::ostream& operator<<(std::ostream& stream, const Arcus::Error& error); #endif //ARCUS_ERROR_H libArcus-5.0.0/src/MessageTypeStore.cpp000066400000000000000000000135541422605243600200320ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #include "MessageTypeStore.h" #include #include #include #include #include using namespace Arcus; /** * Taken from libstdc++, this implements hashing a string to an int. * * Since we rely on the hashing method for type ID generation and the implementation * of std::hash differs between compilers, we need to make sure we use the same * implementation everywhere. */ uint32_t hash(const std::string& input) { const char* data = input.c_str(); uint32_t length = input.size(); uint32_t result = static_cast(2166136261UL); for(; length; --length) { result ^= static_cast(*data++); result *= static_cast(16777619UL); } return result; } class ErrorCollector : public google::protobuf::compiler::MultiFileErrorCollector { public: ErrorCollector() : _error_count(0) { } void AddError(const std::string& filename, int line, int column, const std::string& message) override { _stream << "[" << filename << " (" << line << "," << column << ")] " << message << std::endl; _error_count++; } std::string getAllErrors() { return _stream.str(); } int getErrorCount() { return _error_count; } private: std::stringstream _stream; int _error_count; }; class ARCUS_NO_EXPORT MessageTypeStore::Private { public: std::unordered_map message_types; std::unordered_map message_type_mapping; std::shared_ptr error_collector; std::shared_ptr source_tree; std::shared_ptr importer; std::shared_ptr message_factory; }; Arcus::MessageTypeStore::MessageTypeStore() : d(new Private) { } Arcus::MessageTypeStore::~MessageTypeStore() { } bool Arcus::MessageTypeStore::hasType(uint32_t type_id) const { if(d->message_types.find(type_id) != d->message_types.end()) { return true; } return false; } bool Arcus::MessageTypeStore::hasType(const std::string& type_name) const { uint32_t type_id = hash(type_name); return hasType(type_id); } MessagePtr Arcus::MessageTypeStore::createMessage(uint32_t type_id) const { if(!hasType(type_id)) { return MessagePtr(); } return MessagePtr(d->message_types[type_id]->New()); } MessagePtr Arcus::MessageTypeStore::createMessage(const std::string& type_name) const { uint32_t type_id = hash(type_name); return createMessage(type_id); } uint32_t Arcus::MessageTypeStore::getMessageTypeId(const MessagePtr& message) { return hash(message->GetTypeName()); } std::string Arcus::MessageTypeStore::getErrorMessages() const { return d->error_collector->getAllErrors(); } bool Arcus::MessageTypeStore::registerMessageType(const google::protobuf::Message* message_type) { uint32_t type_id = hash(message_type->GetTypeName()); if(hasType(type_id)) { return false; } d->message_types[type_id] = message_type; d->message_type_mapping[message_type->GetDescriptor()] = type_id; return true; } bool Arcus::MessageTypeStore::registerAllMessageTypes(const std::string& file_name) { if(!d->importer) { d->error_collector = std::make_shared(); d->source_tree = std::make_shared(); #ifndef _WIN32 d->source_tree->MapPath("/", "/"); #else // Because of silly DiskSourceTree, we need to make sure absolute paths to // the protocol file are properly mapped. for(auto letter : std::string("abcdefghijklmnopqrstuvwxyz")) { std::string lc(1, letter); std::string uc(1, toupper(letter)); d->source_tree->MapPath(lc + ":/", lc + ":\\"); d->source_tree->MapPath(uc + ":/", uc + ":\\"); } #endif d->importer = std::make_shared(d->source_tree.get(), d->error_collector.get()); } auto descriptor = d->importer->Import(file_name); if(d->error_collector->getErrorCount() > 0) { return false; } if(!d->message_factory) { d->message_factory = std::make_shared(); } for(int i = 0; i < descriptor->message_type_count(); ++i) { auto message_type_descriptor = descriptor->message_type(i); auto message_type = d->message_factory->GetPrototype(message_type_descriptor); uint32_t type_id = hash(message_type->GetTypeName()); d->message_types[type_id] = message_type; d->message_type_mapping[message_type_descriptor] = type_id; } return true; } void Arcus::MessageTypeStore::dumpMessageTypes() { for(auto type : d->message_types) { std::cout << "Type ID: " << type.first << " Type Name: " << type.second->GetTypeName() << std::endl; } } libArcus-5.0.0/src/MessageTypeStore.h000066400000000000000000000071231422605243600174720ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #ifndef ARCUS_MESSAGE_TYPE_STORE_H #define ARCUS_MESSAGE_TYPE_STORE_H #include #include "ArcusExport.h" #include "Types.h" namespace Arcus { /** * A class to manage the different types of messages that are available. */ class ARCUS_EXPORT MessageTypeStore { public: MessageTypeStore(); ~MessageTypeStore(); /** * Check if a certain message type was registered. * * \param type_id The ID of the type to check for. * * \return true if the message type was registered, false if not. */ bool hasType(uint32_t type_id) const; /** * Check if a certain message type was registered. * * \param type_name The name of the type to check for. * * \return true if the message type was registered, false if not. */ bool hasType(const std::string& type_name) const; /** * Create a Message instance of a certain type. * * \param type_id The type ID of the message type to create an instance of. * * \return A new instance of a Message or an invalid pointer if type_id was an invalid type. */ MessagePtr createMessage(uint32_t type_id) const; /** * Create a Message instance of a certain type. * * \param type_name The name of the message type to create an instance of. * * \return A new instance of a Message or an invalid pointer if type_id was an invalid type. */ MessagePtr createMessage(const std::string& type_name) const; /** * Get the type ID of a message. * * \param message The message to get the type ID of. * * \return The type id of the message. */ uint32_t getMessageTypeId(const MessagePtr& message); std::string getErrorMessages() const; /** * Register a message type. * * \param message_type An instance of a message that will be used as factory to create new messages. * * \return true if registration was successful, false if not. */ bool registerMessageType(const google::protobuf::Message* message_type); /** * Register all message types from a Protobuf protocol description file. * * \param file_name The absolute path to a Protobuf proto file. * * \return true if registration was successful, false if not. */ bool registerAllMessageTypes(const std::string& file_name); /** * Dump all message type IDs and type names to stdout. */ void dumpMessageTypes(); private: class Private; const std::unique_ptr d; }; } #endif //ARCUS_MESSAGE_TYPE_STORE_H libArcus-5.0.0/src/PlatformSocket.cpp000066400000000000000000000145731422605243600175260ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #include "PlatformSocket_p.h" #ifdef _WIN32 #include #include #else #include #include #include #include #include #include #include #include #endif #ifndef MSG_NOSIGNAL #define MSG_NOSIGNAL 0x0 //Don't request NOSIGNAL on systems where this is not implemented. #endif #ifndef MSG_DONTWAIT #define MSG_DONTWAIT 0x0 #endif using namespace Arcus::Private; #ifdef _WIN32 void initializeWSA() { static bool wsaInitialized = false; if(!wsaInitialized) { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); wsaInitialized = true; } } #endif // Create a sockaddr_in structure from an address and port. sockaddr_in createAddress(const std::string& address, int port) { sockaddr_in a; a.sin_family = AF_INET; #ifdef _WIN32 InetPton(AF_INET, address.c_str(), &(a.sin_addr)); //Note: Vista and higher only. #else ::inet_pton(AF_INET, address.c_str(), &(a.sin_addr)); #endif a.sin_port = htons(port); return a; } Arcus::Private::PlatformSocket::PlatformSocket() { #ifdef _WIN32 initializeWSA(); #endif } Arcus::Private::PlatformSocket::~PlatformSocket() { } bool Arcus::Private::PlatformSocket::create() { _socket_id = ::socket(AF_INET, SOCK_STREAM, 0); return _socket_id != -1; } bool Arcus::Private::PlatformSocket::connect(const std::string& address, int port) { auto address_data = createAddress(address, port); int result = ::connect(_socket_id, reinterpret_cast(&address_data), sizeof(address_data)); return result == 0; } bool Arcus::Private::PlatformSocket::bind(const std::string& address, int port) { auto address_data = createAddress(address, port); int result = ::bind(_socket_id, reinterpret_cast(&address_data), sizeof(address_data)); return result == 0; } bool Arcus::Private::PlatformSocket::listen(int backlog) { int result = ::listen(_socket_id, backlog); return result == 0; } bool Arcus::Private::PlatformSocket::accept() { int new_socket = ::accept(_socket_id, 0, 0); #ifdef _WIN32 ::closesocket(_socket_id); #else ::close(_socket_id); #endif if(new_socket == -1) { return false; } else { _socket_id = new_socket; return true; } } bool Arcus::Private::PlatformSocket::close() { int result = 0; #ifdef _WIN32 result = ::closesocket(_socket_id); #else result = ::close(_socket_id); #endif return result == 0; } bool Arcus::Private::PlatformSocket::shutdown(PlatformSocket::ShutdownDirection direction) { int flag = 0; switch(direction) { case ShutdownDirection::ShutdownRead: #ifdef _WIN32 flag = SD_RECEIVE; #else flag = SHUT_RD; #endif break; case ShutdownDirection::ShutdownWrite: #ifdef _WIN32 flag = SD_SEND; #else flag = SHUT_WR; #endif break; case ShutdownDirection::ShutdownBoth: #ifdef _WIN32 flag = SD_BOTH; #else flag = SHUT_RDWR; #endif } return (::shutdown(_socket_id, flag) == 0); } void Arcus::Private::PlatformSocket::flush() { char* buffer = new char[256]; socket_size num = 0; while(num > 0) { num = ::recv(_socket_id, buffer, 256, MSG_DONTWAIT); } } socket_size Arcus::Private::PlatformSocket::writeUInt32(uint32_t data) { uint32_t temp = htonl(data); socket_size sent_size = ::send(_socket_id, reinterpret_cast(&temp), 4, MSG_NOSIGNAL); return sent_size; } socket_size Arcus::Private::PlatformSocket::writeBytes(std::size_t size, const char* data) { return ::send(_socket_id, data, size, MSG_NOSIGNAL); } socket_size Arcus::Private::PlatformSocket::readUInt32(uint32_t* output) { #ifndef _WIN32 errno = 0; #endif uint32_t buffer; socket_size num = ::recv(_socket_id, reinterpret_cast(&buffer), 4, 0); if(num != 4) { #ifdef _WIN32 if(num == WSAETIMEDOUT) { return 0; } else if(WSAGetLastError() == WSAETIMEDOUT) { return 0; } #else if(errno == EAGAIN) { return 0; } #endif return -1; } *output = ntohl(buffer); return num; } socket_size Arcus::Private::PlatformSocket::readBytes(std::size_t size, char* output) { #ifndef _WIN32 errno = 0; #endif socket_size num = ::recv(_socket_id, output, size, 0); #ifdef _WIN32 if(num == SOCKET_ERROR && WSAGetLastError() == WSAETIMEDOUT) { return 0; } #else if(num <= 0 && errno == EAGAIN) { return 0; } #endif return num; } bool Arcus::Private::PlatformSocket::setReceiveTimeout(int timeout) { int result = 0; #ifdef _WIN32 result = ::setsockopt(_socket_id, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); return result != SOCKET_ERROR; #else timeval t; t.tv_sec = 0; t.tv_usec = timeout * 1000; result = ::setsockopt(_socket_id, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&t), sizeof(t)); return result == 0; #endif } int Arcus::Private::PlatformSocket::getNativeErrorCode() { #ifdef _WIN32 return WSAGetLastError(); #else return errno; #endif } libArcus-5.0.0/src/PlatformSocket_p.h000066400000000000000000000146501422605243600175060ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #ifndef ARCUS_PLATFORM_SOCKET_P_H #define ARCUS_PLATFORM_SOCKET_P_H #include #include namespace Arcus { namespace Private { #ifdef _WIN32 typedef int socket_size; #else typedef ssize_t socket_size; #endif /** * Private class that wraps the platform C API for dealing with Sockets. */ class PlatformSocket { public: /** * Which connection direction should be shutdown? */ enum class ShutdownDirection { ShutdownRead, ///< Shutdown reads from the connection. ShutdownWrite, ///< Shutdown writes to the connection. ShutdownBoth, ///< Shutdown the connection both ways. }; PlatformSocket(); ~PlatformSocket(); /** * Create the socket. * * \return true if socket creation was successful, false if not. */ bool create(); /** * Connect to an IP address and port. * * \param address The IP address to connect to. * \param port The port to bind to. * * \return true if the connection was successful, false if not. */ bool connect(const std::string& address, int port); /** * Bind the socket to an address and port. * * \param address The IP address to bind to. * \param port The port to bind to. * * \return true if successful, false if not. */ bool bind(const std::string& address, int port); /** * Mark the socket as listening for new connections. * * \param backlog The amount of queued connections to accept. * * \return true if successful, false if not. */ bool listen(int backlog); /** * Accept the waiting incoming connection and use it as connected socket. * * \return true if successful, false if not. * * \note This call will block until there is a connection waiting to be accepted. */ bool accept(); /** * Close the socket. * * \return true if successful, false if not. */ bool close(); /** * Shutdown the socket. * * \param direction The direction to shutdown. * * \return true if successful, false if not. */ bool shutdown(ShutdownDirection direction); /** * Flush all waiting data and discard it. * * This is mostly intended as an error recovery mechanism, if we detect a failure * in the messages sent over the wire, we can no longer be sure about the rest of * the data on the wire. So rather than trying to figure out if there is an actual * message hidden somewhere, just flush all data so we start with a clean slate. */ void flush(); /** * Write an unsigned 32-bit integer to the socket. * * \param data The integer to write. Will be converted from local endianness to network endianness. * * \return The amount of bytes written (4) or -1 if an error occurred. */ socket_size writeUInt32(uint32_t data); /** * Write data to the the socket. * * \param size The amount of data to write. * \param data A pointer to the data to send. * * \return The amount of bytes written, or -1 if an error occurred. */ socket_size writeBytes(std::size_t size, const char* data); /** * Read an unsigned 32-bit integer from the socket. * * \param output A pointer to an integer that will be written to. * * \return The amount of bytes read (4) or -1 if an error occurred. * * \note This call will block if the amount of data waiting to be read is less than 4. */ socket_size readUInt32(uint32_t* output); /** * Read an amount of bytes from the socket. * * \param size The amount of bytes to read. * \param output A pointer to a block of data that can be written to. * * \return The amount of bytes read or -1 if an error occurred. * * \note This call will block if the amount of data waiting to be read is less than size. */ socket_size readBytes(std::size_t size, char* output); /** * Set the timeout for the read-related methods. * * The readInt32 and readBytes methods will block for a certain amount of time when * there is not enough data available. This call will set the maximum amount of time these * calls will block. * * \param timeout The amount of time in milliseconds to wait for data. */ bool setReceiveTimeout(int timeout); /** * Return the last error code as reported by the underlying platform. */ int getNativeErrorCode(); private: int _socket_id; }; } } #endif //ARCUS_PLATFORM_SOCKET_P_H libArcus-5.0.0/src/Socket.cpp000066400000000000000000000166561422605243600160250ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #include "Socket.h" #include "Socket_p.h" #include using namespace Arcus; Socket::Socket() : d(new Private) { } Socket::~Socket() { if(d->thread) { if(d->state != SocketState::Closed || d->state != SocketState::Error) { close(); } delete d->thread; } for(SocketListener* listener : d->listeners) { /* If deleting the socket listener while another thread is reporting an * error due to closing the socket, deleting the listener causes another * error to report and this causes an infinite loop. Making sure the * listener is dysfunctional before deleting it prevents this. */ listener->_socket = nullptr; delete listener; } } SocketState Socket::getState() const { return d->state; } Error Socket::getLastError() const { return d->last_error; } void Socket::clearError() { d->last_error = Error(); } bool Socket::registerMessageType(const google::protobuf::Message* message_type) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return false; } return d->message_types.registerMessageType(message_type); } bool Socket::registerAllMessageTypes(const std::string& file_name) { if(file_name.empty()) { d->error(ErrorCode::MessageRegistrationFailedError, "Empty file name"); return false; } if(d->state != SocketState::Initial) { d->error(ErrorCode::MessageRegistrationFailedError, "Socket is not in initial state"); return false; } if(!d->message_types.registerAllMessageTypes(file_name)) { d->error(ErrorCode::MessageRegistrationFailedError, d->message_types.getErrorMessages()); return false; } return true; } void Socket::addListener(SocketListener* listener) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } listener->setSocket(this); d->listeners.push_back(listener); } void Socket::removeListener(SocketListener* listener) { if(d->state != SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } auto itr = std::find(d->listeners.begin(), d->listeners.end(), listener); d->listeners.erase(itr); } void Socket::connect(const std::string& address, int port) { if(d->state != SocketState::Initial || d->thread != nullptr) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } d->address = address; d->port = port; d->thread = new std::thread([&]() { d->run(); }); d->next_state = SocketState::Connecting; } void Socket::reset() { if (d->state != SocketState::Closed && d->state != SocketState::Error) { d->error(ErrorCode::InvalidStateError, "Socket is not in closed or error state"); return; } if(d->thread) { d->thread->join(); d->thread = nullptr; } d->state = SocketState::Initial; d->next_state = SocketState::Initial; clearError(); } void Socket::listen(const std::string& address, int port) { if(d->state != SocketState::Initial || d->thread != nullptr) { d->error(ErrorCode::InvalidStateError, "Socket is not in initial state"); return; } d->address = address; d->port = port; d->thread = new std::thread([&]() { d->run(); }); d->next_state = SocketState::Opening; } void Socket::close() { if(d->state == SocketState::Initial) { d->error(ErrorCode::InvalidStateError, "Cannot close a socket in initial state"); return; } if(d->state == SocketState::Closed || d->state == SocketState::Error) { // Silently ignore this, as calling close on an already closed socket should be fine. d->state = SocketState::Closed; d->message_received_condition_variable.notify_all(); return; } if(d->state == SocketState::Connected) { // Make the socket request close. d->next_state = SocketState::Closing; // Wait with closing until we properly clear the send queue. while(d->state == SocketState::Closing) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } else { // We are still in an unconnected state but want to abort any connection // attempt. So disable any communication on the socket to make sure calls // like accept() exit, then close the socket. d->platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownBoth); d->platform_socket.close(); d->next_state = SocketState::Closed; } if(d->thread) { d->thread->join(); delete d->thread; d->thread = nullptr; } // Notify all in case of closing because the waiting threads need to know // that this socket has been closed and they should not wait any more. d->message_received_condition_variable.notify_all(); } void Socket::sendMessage(MessagePtr message) { if(!message) { d->error(ErrorCode::InvalidMessageError, "Message cannot be nullptr"); return; } std::lock_guard lock(d->sendQueueMutex); d->sendQueue.push_back(message); } MessagePtr Socket::takeNextMessage() { std::unique_lock lk(d->receiveQueueMutexBlock); // Take the next message in the receive queue if available. { std::lock_guard lock(d->receiveQueueMutex); if(d->receiveQueue.size() > 0) { MessagePtr next = d->receiveQueue.front(); d->receiveQueue.pop_front(); return next; } } // For a blocking call, wait until the receive queue available signal gets triggered and fetch the first message // in the receive queue. // Note that wait causes the current thread to block until the condition variable is notified or a spurious wakeup // occurs, optionally looping until some predicate is satisfied. See https://en.cppreference.com/w/cpp/thread/condition_variable/wait d->message_received_condition_variable.wait(lk); // Only continue to fetch the next message if the socket is still operating normally. bool continue_to_take_next = d->state != SocketState::Closed && d->state != SocketState::Error; lk.unlock(); MessagePtr result; // null by default if (continue_to_take_next) { result = takeNextMessage(); } return result; } MessagePtr Arcus::Socket::createMessage(const std::string& type) { return d->message_types.createMessage(type); } libArcus-5.0.0/src/Socket.h000066400000000000000000000111031422605243600154500ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #ifndef ARCUS_SOCKET_H #define ARCUS_SOCKET_H #include #include "Types.h" #include "Error.h" #include "ArcusExport.h" namespace Arcus { class SocketListener; /** * \brief Threaded socket class. * * This class represents a socket and the logic for parsing and handling * protobuf messages that can be sent and received over this socket. * * Please see the README in libArcus for more details. */ class ARCUS_EXPORT Socket { public: Socket(); virtual ~Socket(); /** * Get the socket state. * * \return The current socket state. */ virtual SocketState getState() const; /** * Get the last error. * * \return The last error that occurred. */ Error getLastError() const; /** * Clear any error that was set previously. */ void clearError(); /** * Register a new type of Message to handle. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param message_type An instance of the Message that will be used as factory object. * */ virtual bool registerMessageType(const google::protobuf::Message* message_type); /** * Register all message types contained in a Protobuf protocol description file. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param file_name The absolute path to a Protobuf protocol file to load message types from. */ virtual bool registerAllMessageTypes(const std::string& file_name); /** * Add a listener object that will be notified of socket events. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param listener The listener to add. */ void addListener(SocketListener* listener); /** * Remove a listener from the list of listeners. * * If the socket state is not SocketState::Initial, this method will do nothing. * * \param listener The listener to remove. */ void removeListener(SocketListener* listener); /** * Connect to an address and port. * * \param address The IP address to connect to. * \param port The port to connect to. */ virtual void connect(const std::string& address, int port); /** * Listen for connections on an address and port. * * \param address The IP address to listen on. * \param port The port to listen on. */ virtual void listen(const std::string& address, int port); /** * Close the connection and stop handling any messages. */ virtual void close(); /** * Reset a socket for re-use. State must be Closed or Error */ virtual void reset(); /** * Send a message across the socket. */ virtual void sendMessage(MessagePtr message); /** * Remove and return the next pending message from the queue with condition blocking. */ virtual MessagePtr takeNextMessage(); /** * Create an instance of a Message class. * * \param type_name The type name of the Message type to create an instance of. */ virtual MessagePtr createMessage(const std::string& type_name); private: // Copy and assignment is not supported. Socket(const Socket&); Socket& operator=(const Socket& other); class Private; const std::unique_ptr d; }; } #endif // ARCUS_SOCKET_H libArcus-5.0.0/src/SocketListener.cpp000066400000000000000000000017521422605243600175220ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #include "SocketListener.h" #include "Socket.h" using namespace Arcus; Socket* SocketListener::getSocket() const { return _socket; } void SocketListener::setSocket(Socket* socket) { _socket = socket; } libArcus-5.0.0/src/SocketListener.h000066400000000000000000000056121422605243600171660ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #ifndef ARCUS_SOCKETLISTENER_H #define ARCUS_SOCKETLISTENER_H #include "Types.h" #include "ArcusExport.h" namespace Arcus { class Socket; class Error; /** * Interface for socket event listeners. * * This interface should be implemented to receive notifications when * certain events occur on the socket. The methods of this interface * are called from the Socket's worker thread and thus with that thread * as current thread. This interface is thus primarily intended as an * abstraction to implement your own thread synchronisation. * * For example, when using the Qt event loop, you could emit a queued * signal from a subclass of this class, to make sure the actual event * is handled on the main thread. */ class ARCUS_EXPORT SocketListener { public: SocketListener() : _socket(nullptr) { } virtual ~SocketListener() { } /** * \return The socket this listener is listening to. */ Socket* getSocket() const; /** * Called whenever the socket's state changes. * * \param newState The new state of the socket. */ virtual void stateChanged(SocketState newState) = 0; /** * Called whenever a new message has been received and * correctly parsed. * * \note This is explicitly not passed the received message. Instead, it is put * on a receive queue so other threads can take care of it. */ virtual void messageReceived() = 0; /** * Called whenever an error occurs on the socket. * * \param errorMessage The error message. */ virtual void error(const Error& error) = 0; private: // So we can call setSocket from Socket without making it public interface. friend class Socket; // Set the socket this listener is listening to. // This is automatically called by the socket when Socket::addListener() is called. void setSocket(Socket* socket); Socket* _socket; }; } #endif // ARCUS_SOCKETLISTENER_H libArcus-5.0.0/src/Socket_p.h000066400000000000000000000475401422605243600160050ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #include #include #include #include #include #include #include #include #ifdef _WIN32 #include #include #else #include #include #include #include #include #include #include #endif #include #include #include #include "Socket.h" #include "Types.h" #include "SocketListener.h" #include "MessageTypeStore.h" #include "Error.h" #include "WireMessage_p.h" #include "PlatformSocket_p.h" #define VERSION_MAJOR 1 #define VERSION_MINOR 0 #define ARCUS_SIGNATURE 0x2BAD #define SIG(n) (((n) & 0xffff0000) >> 16) #define SOCKET_CLOSE 0xf0f0f0f0 #ifdef ARCUS_DEBUG #define DEBUG(message) debug(message) #else #define DEBUG(message) #endif /** * Private implementation details for Socket. */ namespace Arcus { using namespace Private; class ARCUS_NO_EXPORT Socket::Private { public: Private() : state(SocketState::Initial) , next_state(SocketState::Initial) , received_close(false) , port(0) , thread(nullptr) { } void run(); void sendMessage(const MessagePtr& message); void receiveNextMessage(); void handleMessage(const std::shared_ptr& wire_message); void checkConnectionState(); #ifdef ARCUS_DEBUG void debug(const std::string& message); #endif void error(ErrorCode error_code, const std::string& message); void fatalError(ErrorCode error_code, const std::string& msg); SocketState state; SocketState next_state; bool received_close; std::string address; uint port; std::thread* thread; std::list listeners; MessageTypeStore message_types; std::shared_ptr current_message; std::deque sendQueue; std::mutex sendQueueMutex; std::deque receiveQueue; std::mutex receiveQueueMutex; std::mutex receiveQueueMutexBlock; std::condition_variable message_received_condition_variable; Arcus::Private::PlatformSocket platform_socket; Error last_error; std::chrono::system_clock::time_point last_keep_alive_sent; static const int keep_alive_rate = 500; //Number of milliseconds between sending keepalive packets // This value determines when protobuf should warn about very large messages. static const int message_size_warning = 400 * 1048576; // This value determines when protobuf should error out because the message is too large. // Due to the way Protobuf is implemented, messages large than 512MiB will cause issues. static const int message_size_maximum = 500 * 1048576; }; #ifdef ARCUS_DEBUG void Socket::Private::debug(const std::string& message) { Error error(ErrorCode::Debug, std::string("[DEBUG] ") + message); for(auto listener : listeners) { listener->error(error); } } #endif // Report an error that should not cause the connection to abort. void Socket::Private::error(ErrorCode error_code, const std::string& message) { Error error(error_code, message); error.setNativeErrorCode(platform_socket.getNativeErrorCode()); last_error = error; for(auto listener : listeners) { listener->error(error); } } // Report an error that should cause the socket to go into an error state and abort the connection. void Socket::Private::fatalError(ErrorCode error_code, const std::string& message) { Error error(error_code, message); error.setFatalError(true); error.setNativeErrorCode(platform_socket.getNativeErrorCode()); last_error = error; platform_socket.close(); next_state = SocketState::Error; for(auto listener : listeners) { listener->error(error); } } // Thread run method. void Socket::Private::run() { while(state != SocketState::Closed && state != SocketState::Error) { switch(state) { case SocketState::Connecting: { if(!platform_socket.create()) { fatalError(ErrorCode::CreationError, "Could not create a socket"); } else if(!platform_socket.connect(address, port)) { fatalError(ErrorCode::ConnectFailedError, "Could not connect to the given address"); } else { if(!platform_socket.setReceiveTimeout(250)) { fatalError(ErrorCode::ConnectFailedError, "Failed to set socket receive timeout"); } else { DEBUG("Socket connected"); next_state = SocketState::Connected; } } break; } case SocketState::Opening: { if(!platform_socket.create()) { fatalError(ErrorCode::CreationError, "Could not create a socket"); } else if(!platform_socket.bind(address, port)) { fatalError(ErrorCode::BindFailedError, "Could not bind to the given address and port"); } else { next_state = SocketState::Listening; } break; } case SocketState::Listening: { platform_socket.listen(1); if(!platform_socket.accept()) { fatalError(ErrorCode::AcceptFailedError, "Could not accept the incoming connection"); } else { if(!platform_socket.setReceiveTimeout(250)) { fatalError(ErrorCode::AcceptFailedError, "Could not set receive timeout of socket"); } else { DEBUG("Socket connected"); next_state = SocketState::Connected; } } break; } case SocketState::Connected: { //Get all the messages from the queue and store them in a temporary array so we can //unlock the queue before performing the send. std::list messagesToSend; sendQueueMutex.lock(); while(sendQueue.size() > 0) { messagesToSend.push_back(sendQueue.front()); sendQueue.pop_front(); } sendQueueMutex.unlock(); for(auto message : messagesToSend) { sendMessage(message); } receiveNextMessage(); if(next_state != SocketState::Error) { checkConnectionState(); } break; } case SocketState::Closing: { if(!received_close) { // We want to close the socket. // First, flush the send queue so it is empty. std::list messagesToSend; sendQueueMutex.lock(); while(sendQueue.size() > 0) { messagesToSend.push_back(sendQueue.front()); sendQueue.pop_front(); } sendQueueMutex.unlock(); for(auto message : messagesToSend) { sendMessage(message); } // Communicate to the other side that we want to close. platform_socket.writeUInt32(SOCKET_CLOSE); // Disable further writing to the socket. error(ErrorCode::Debug, "We got a request to close the socket."); platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownWrite); // Wait until we receive confirmation from the other side to actually close. uint32_t data = 0; while(data != SOCKET_CLOSE && next_state == SocketState::Closing) { if(platform_socket.readUInt32(&data) == -1) { break; } } } else { // The other side requested a close. Drop all pending messages // since the other socket will not process them anyway. sendQueueMutex.lock(); sendQueue.clear(); sendQueueMutex.unlock(); // Send confirmation to the other side that we received their close // request and are also closing down. platform_socket.writeUInt32(SOCKET_CLOSE); // Prevent further writing to the socket. platform_socket.shutdown(PlatformSocket::ShutdownDirection::ShutdownWrite); // At this point the socket can safely be closed, assuming that SOCKET_CLOSE // is the last data received from the other socket and everything was received // in order (which should be guaranteed by TCP). } error(ErrorCode::Debug, "Closing socket because other side requested close."); platform_socket.close(); next_state = SocketState::Closed; break; } default: break; } if(next_state != state) { state = next_state; for(auto listener : listeners) { listener->stateChanged(state); } } } message_received_condition_variable.notify_all(); } // Send a message to the connected socket. void Socket::Private::sendMessage(const MessagePtr& message) { uint32_t header = (ARCUS_SIGNATURE << 16) | (VERSION_MAJOR << 8) | (VERSION_MINOR); if(platform_socket.writeUInt32(header) == -1) { error(ErrorCode::SendFailedError, "Could not send message header"); return; } uint32_t message_size = message->ByteSize(); if(platform_socket.writeUInt32(message_size) == -1) { error(ErrorCode::SendFailedError, "Could not send message size"); return; } uint32_t type_id = message_types.getMessageTypeId(message); if(platform_socket.writeUInt32(type_id) == -1) { error(ErrorCode::SendFailedError, "Could not send message type"); return; } std::string data = message->SerializeAsString(); if(platform_socket.writeBytes(data.size(), data.data()) == -1) { error(ErrorCode::SendFailedError, "Could not send message data"); } DEBUG(std::string("Sending message of type ") + std::to_string(type_id) + " and size " + std::to_string(message_size)); } // Handle receiving data until we have a proper message. void Socket::Private::receiveNextMessage() { int result = 0; if(!current_message) { current_message = std::make_shared(); } if(current_message->state == WireMessage::MessageState::Header) { uint32_t header = 0; platform_socket.readUInt32(&header); if(header == 0) // Keep-alive, just return { return; } else if(header == SOCKET_CLOSE) { // We received a close request from the other socket, so close this socket as well. next_state = SocketState::Closing; received_close = true; return; } int signature = (header & 0xffff0000) >> 16; int major_version = (header & 0x0000ff00) >> 8; int minor_version = header & 0x000000ff; if(signature != ARCUS_SIGNATURE) { // Someone might be speaking to us in a different protocol? error(ErrorCode::ReceiveFailedError, "Header mismatch"); current_message.reset(); platform_socket.flush(); return; } if(major_version != VERSION_MAJOR) { error(ErrorCode::ReceiveFailedError, "Protocol version mismatch"); current_message.reset(); platform_socket.flush(); return; } if(minor_version != VERSION_MINOR) { error(ErrorCode::ReceiveFailedError, "Protocol version mismatch"); current_message.reset(); platform_socket.flush(); return; } DEBUG("Incoming message, header ok"); current_message->state = WireMessage::MessageState::Size; } if(current_message->state == WireMessage::MessageState::Size) { uint32_t size = 0; result = platform_socket.readUInt32(&size); if(result == 0) { return; } else if(result == -1) { error(ErrorCode::ReceiveFailedError, "Size invalid"); current_message.reset(); platform_socket.flush(); return; } DEBUG(std::string("Incoming message size: ") + std::to_string(size)); current_message->size = size; current_message->state = WireMessage::MessageState::Type; } if (current_message->state == WireMessage::MessageState::Type) { uint32_t type = 0; result = platform_socket.readUInt32(&type); if(result == 0) { return; } else if(result == -1) { error(ErrorCode::ReceiveFailedError, "Receiving type failed"); current_message->valid = false; } uint32_t real_type = static_cast(type); try { current_message->allocateData(); } catch (std::bad_alloc&) { // Either way we're in trouble. current_message.reset(); fatalError(ErrorCode::ReceiveFailedError, "Out of memory"); return; } DEBUG(std::string("Incoming message type: ") + std::to_string(real_type)); current_message->type = real_type; current_message->state = WireMessage::MessageState::Data; } if (current_message->state == WireMessage::MessageState::Data) { result = platform_socket.readBytes(current_message->getRemainingSize(), ¤t_message->data[current_message->received_size]); if(result < 0) { error(ErrorCode::ReceiveFailedError, "Could not receive data for message"); current_message.reset(); return; } else { current_message->received_size = current_message->received_size + result; DEBUG("Received " + std::to_string(result) + " bytes data"); if(current_message->isComplete()) { if(!current_message->valid) { current_message.reset(); return; } current_message->state = WireMessage::MessageState::Dispatch; } } } if (current_message->state == WireMessage::MessageState::Dispatch) { handleMessage(current_message); current_message.reset(); } } // Parse and process a message received on the socket. void Socket::Private::handleMessage(const std::shared_ptr& wire_message) { if(!message_types.hasType(wire_message->type)) { DEBUG(std::string("Received message type: ") + std::to_string(wire_message->type)); error(ErrorCode::UnknownMessageTypeError, "Unknown message type"); return; } MessagePtr message = message_types.createMessage(wire_message->type); google::protobuf::io::ArrayInputStream array(wire_message->data, wire_message->size); google::protobuf::io::CodedInputStream stream(&array); stream.SetTotalBytesLimit(message_size_maximum, message_size_warning); if(!message->ParseFromCodedStream(&stream)) { error(ErrorCode::ParseFailedError, "Failed to parse message:" + std::string(wire_message->data)); return; } DEBUG(std::string("Received a message of type ") + std::to_string(wire_message->type) + " and size " + std::to_string(wire_message->size)); receiveQueueMutex.lock(); receiveQueue.push_back(message); receiveQueueMutex.unlock(); for(auto listener : listeners) { listener->messageReceived(); } message_received_condition_variable.notify_all(); } // Send a keepalive packet to check whether we are still connected. void Socket::Private::checkConnectionState() { auto now = std::chrono::system_clock::now(); auto diff = std::chrono::duration_cast(now - last_keep_alive_sent); if(diff.count() > keep_alive_rate) { int32_t keepalive = 0; if(platform_socket.writeUInt32(keepalive) == -1) { error(ErrorCode::ConnectionResetError, "Connection reset by peer"); next_state = SocketState::Closing; } last_keep_alive_sent = now; } } } libArcus-5.0.0/src/Types.h000066400000000000000000000033041422605243600153300ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2015 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #ifndef ARCUS_TYPES_H #define ARCUS_TYPES_H #include #include namespace google { namespace protobuf { class Message; } } namespace Arcus { // Convenience typedef so uint can be used. typedef uint32_t uint; // Convenience typedef for standard message argument. typedef std::shared_ptr MessagePtr; /** * Socket state. */ enum class SocketState { Initial, ///< Created, not running. Connecting, ///< Connecting to an address and port. Connected, ///< Connected and capable of sending and receiving messages. Opening, ///< Opening for incoming connections. Listening, ///< Listening for incoming connections. Closing, ///< Closing down. Closed, ///< Closed, not running. Error ///< A fatal error happened that blocks the socket from operating. }; } #endif //ARCUS_TYPES_H libArcus-5.0.0/src/WireMessage_p.h000066400000000000000000000056271422605243600167700ustar00rootroot00000000000000/* * This file is part of libArcus * * Copyright (C) 2016 Ultimaker b.v. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License v3.0 as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License v3.0 for more details. * You should have received a copy of the GNU Lesser General Public License v3.0 * along with this program. If not, see . */ #ifndef ARCUS_WIRE_MESSAGE_P_H #define ARCUS_WIRE_MESSAGE_P_H #include "Types.h" namespace Arcus { namespace Private { /** * Private class that encapsulates a message being sent over the wire. */ class WireMessage { public: /** * Current state of the message. */ enum class MessageState { Header, ///< Check for the header. Size, ///< Check for the message size. Type, ///< Check for the message type. Data, ///< Get the message data. Dispatch ///< Process the message and parse it into a protobuf message. }; WireMessage() : state(MessageState::Header) , size(0) , received_size(0) , valid(true) , type(0) , data(nullptr) { } inline ~WireMessage() { if(size > 0 && data) { delete[] data; } } // Current message state. MessageState state; // Size of the message. uint32_t size; // Amount of bytes received so far. uint32_t received_size; // Is this a potentially valid message? bool valid; // The type of message. uint32_t type; // The data of the message. char* data; // Return how many bytes are remaining for this message to be complete. inline uint32_t getRemainingSize() const { return size - received_size; } // Allocate data for this message based on size. inline void allocateData() { data = new char[size]; } // Check if the message can be considered complete. inline bool isComplete() const { return received_size >= size; } }; } } #endif //ARCUS_WIRE_MESSAGE_P_H libArcus-5.0.0/test_package/000077500000000000000000000000001422605243600157165ustar00rootroot00000000000000libArcus-5.0.0/test_package/CMakeLists.txt000066400000000000000000000004631422605243600204610ustar00rootroot00000000000000project(PackageTest) cmake_minimum_required(VERSION 3.20) include(../cmake/StandardProjectSettings.cmake) find_package(Arcus REQUIRED) add_executable(test test.cpp) set_project_standards(test) set_project_warnings(test) use_threads(test) target_link_libraries(test PUBLIC Arcus )libArcus-5.0.0/test_package/conanfile.py000066400000000000000000000012701422605243600202260ustar00rootroot00000000000000from conans import ConanFile, CMake from conan.tools.cmake import CMakeToolchain, CMakeDeps, CMake class ArcusTestConan(ConanFile): settings = "os", "compiler", "build_type", "arch" def generate(self): cmake = CMakeDeps(self) cmake.generate() tc = CMakeToolchain(self) if self.settings.compiler == "Visual Studio": tc.blocks["generic_system"].values["generator_platform"] = None tc.blocks["generic_system"].values["toolset"] = None tc.generate() def build(self): cmake = CMake(self) cmake.configure() cmake.build() def test(self): pass # only interested in compiling and linkinglibArcus-5.0.0/test_package/test.cpp000066400000000000000000000002071422605243600174000ustar00rootroot00000000000000#include #include int main(int argc, char** argv) { Arcus::SocketState socket_state; return 0; }