text:
#pragma once

#include "SimpleJSON/stringify/jss_fusion_adapted_struct.hpp"
#include "SimpleJSON/parse/jsd_fusion_adapted_struct.hpp"

#include <boost/fusion/adapted/struct/adapt_struct.hpp>

#include <string>
#include <vector>

namespace WretchedCss
{
    enum class SelectorType
    {
        Element,
        Classes,
        Id,
        All,
        Attribute
    };

    struct ParsedSelector : public JSON::Stringifiable <ParsedSelector>
                          , public JSON::Parsable <ParsedSelector>
    {
		SelectorType type;
		std::string selectorString;
		std::vector <std::string> classes;
		std::vector <std::string> filters; // +element, >element, ~element, element, :active, ::before, ::nth-child(), ::lang()

        std::string toString() const;
        long calculateSpecificity() const;
        bool canSelect(std::string const& selector) const;
    };

    class Selector : public JSON::Stringifiable <Selector>
                   , public JSON::Parsable <Selector>
    {
    public:
        Selector() = default;
        Selector(std::string const& raw);

        std::string toString() const;
        std::vector <ParsedSelector> getSelectors() const;

        // returns -1, if cannot be selected.
        long getHighestSpecificityFor(std::string const& selector);

    //private:
    public: // this is necessary, is not worth the effort to fix
        std::vector <ParsedSelector> selectors_;
    };
} // namespace WretchedCss

BOOST_FUSION_ADAPT_STRUCT
(
	WretchedCss::ParsedSelector,
	(WretchedCss::SelectorType, type)
	(std::string, selectorString)
	(std::vector <std::string>, filters)
	(std::vector <std::string>, classes)
)

BOOST_FUSION_ADAPT_STRUCT
(
    WretchedCss::Selector,
    (std::vector <WretchedCss::ParsedSelector>, selectors_)
)

ext: hpp


text:
#include "cmd_options.h"

#include "test_detail.h"

#include <boost/test/unit_test.hpp>

#include <iostream>

/**
  case 12, Raw keys with optional value
 */

BOOST_AUTO_TEST_SUITE( case12_test_suite )

namespace co = cmd_options;

typedef std::basic_string<detail::check_char_t> string_type;
typedef co::basic_option_pack<detail::check_char_t> option_pack_type;
typedef co::basic_option_description<detail::check_char_t>
  option_description_type;
typedef co::basic_options_group<detail::check_char_t> options_group_type;
typedef co::basic_variable_map<detail::check_char_t> variable_map_type;
typedef detail::std_stream_select<detail::check_char_t> stream_select;

/**
  All POSIX keys
 */
BOOST_AUTO_TEST_CASE( all_POSIX_key_test )
{
  variable_map_type vm;
  options_group_type options;
  std::vector<const detail::check_char_t *> argv{
    _LIT("-f"),
    _LIT("-b")
  };

  options = options_group_type{
    co::make_option(_LIT(""),
      co::basic_value<string_type,detail::check_char_t>()
        .implicit(_LIT("floo")),
      _LIT("case 12"))
  };

  std::tie(std::ignore,vm) =
    co::parse_arguments(argv.data(),argv.data()+argv.size(),options);

  BOOST_REQUIRE(detail::contents_equal<string_type>(vm,
    variable_map_type{
      {_LIT("f"),{string_type(_LIT("floo"))}},
      {_LIT("b"),{string_type(_LIT("floo"))}}
    }));
}

/**
  All GNU keys
 */
BOOST_AUTO_TEST_CASE( all_GNU_key_test )
{
  variable_map_type vm;
  options_group_type options;
  std::vector<const detail::check_char_t *> argv{
    _LIT("--foo"),
    _LIT("--bar")
  };

  options = options_group_type{
    co::make_option(_LIT(""),
      co::basic_value<string_type,detail::check_char_t>()
        .implicit(_LIT("floo")),
      _LIT("case 12"))
  };

  std::tie(std::ignore,vm) =
    co::parse_arguments(argv.data(),argv.data()+argv.size(),options);

//   stream_select::cerr << detail::to_string(vm,co::basic_value<string_type,detail::check_char_t>());

  BOOST_REQUIRE(detail::contents_equal<string_type>(vm,
    variable_map_type{
      {_LIT("foo"),{string_type(_LIT("floo"))}},
      {_LIT("bar"),{string_type(_LIT("floo"))}}
    }));
}

/**
  All POSIX keys with values
 */
BOOST_AUTO_TEST_CASE( all_POSIX_key_value_test )
{
  variable_map_type vm;
  options_group_type options;
  std::vector<const detail::check_char_t *> argv{
    _LIT("-ffloopy")
  };

  options = options_group_type{
    co::make_option(_LIT(""),
      co::basic_value<string_type,detail::check_char_t>()
        .implicit(_LIT("floo")),
      _LIT("case 12"))
  };

  std::tie(std::ignore,vm) =
    co::parse_arguments(argv.data(),argv.data()+argv.size(),options);

  BOOST_REQUIRE(detail::contents_equal<string_type>(vm,
    variable_map_type{
      {_LIT("f"),{string_type(_LIT("floopy"))}}
    }));
}

BOOST_AUTO_TEST_CASE( all_POSIX_key_value_w_operand_test )
{
  variable_map_type vm;
  options_group_type options;
  std::vector<const detail::check_char_t *> argv{
    _LIT("-ffloopy"),
    _LIT("bloppy")
  };

  options = options_group_type{
    co::make_option(_LIT(""),
      co::basic_value<string_type,detail::check_char_t>()
        .implicit(_LIT("floo")),
      _LIT("case 12")),
    co::make_operand(_LIT("operand_key"),
      co::basic_value<string_type,detail::check_char_t>())
  };

  std::tie(std::ignore,vm) =
    co::parse_arguments(argv.data(),argv.data()+argv.size(),options);

  BOOST_REQUIRE(detail::contents_equal<string_type>(vm,
    variable_map_type{
      {_LIT("f"),{string_type(_LIT("floopy"))}},
      {_LIT("operand_key"),{string_type(_LIT("bloppy"))}}
    }));
}

BOOST_AUTO_TEST_CASE( all_POSIX_key_value_w_nonimplicit_operand_test )
{
  variable_map_type vm;
  options_group_type options;
  std::vector<const detail::check_char_t *> argv{
    _LIT("-ffloopy"),
    _LIT("-b"),
    _LIT("bloppy")
  };

  options = options_group_type{
    co::make_option(_LIT(""),
      co::basic_value<string_type,detail::check_char_t>()
        .implicit(_LIT("floo")),
      _LIT("case 12")),
    co::make_operand(_LIT("operand_key"),
      co::basic_value<string_type,detail::check_char_t>())
  };

  std::tie(std::ignore,vm) =
    co::parse_arguments(argv.data(),argv.data()+argv.size(),options);

  BOOST_REQUIRE(detail::contents_equal<string_type>(vm,
    variable_map_type{
      {_LIT("f"),{string_type(_LIT("floopy"))}},
      {_LIT("b"),{string_type(_LIT("floo"))}},
      {_LIT("operand_key"),{string_type(_LIT("bloppy"))}}
    }));
}

/**
  All GNU keys with values
 */
BOOST_AUTO_TEST_CASE( all_GNU_key_value_test )
{
  variable_map_type vm;
  options_group_type options;
  std::vector<const detail::check_char_t *> argv{
    _LIT("--foo=floopy")
  };

  options = options_group_type{
    co::make_option(_LIT(""),
      co::basic_value<string_type,detail::check_char_t>()
        .implicit(_LIT("floo")),
      _LIT("case 12"))
  };

  std::tie(std::ignore,vm) =
    co::parse_arguments(argv.data(),argv.data()+argv.size(),options);

  BOOST_REQUIRE(detail::contents_equal<string_type>(vm,
    variable_map_type{
      {_LIT("foo"),{string_type(_LIT("floopy"))}}
    }));
}

BOOST_AUTO_TEST_CASE( all_GNU_key_value_w_operand_test )
{
  variable_map_type vm;
  options_group_type options;
  std::vector<const detail::check_char_t *> argv{
    _LIT("--foo=floopy"),
    _LIT("bloppy")
  };

  options = options_group_type{
    co::make_option(_LIT(""),
      co::basic_value<string_type,detail::check_char_t>()
        .implicit(_LIT("floo")),
      _LIT("case 12")),
    co::make_operand(_LIT("operand_key"),
      co::basic_value<string_type,detail::check_char_t>())
  };

  std::tie(std::ignore,vm) =
    co::parse_arguments(argv.data(),argv.data()+argv.size(),options);

  BOOST_REQUIRE(detail::contents_equal<string_type>(vm,
    variable_map_type{
      {_LIT("foo"),{string_type(_LIT("floopy"))}},
      {_LIT("operand_key"),{string_type(_LIT("bloppy"))}}
    }));
}

BOOST_AUTO_TEST_CASE( all_GNU_key_value_w_nonimplicit_operand_test )
{
  variable_map_type vm;
  options_group_type options;
  std::vector<const detail::check_char_t *> argv{
    _LIT("--foo=floopy"),
    _LIT("--bar"),
    _LIT("bloppy")
  };

  options = options_group_type{
    co::make_option(_LIT(""),
      co::basic_value<string_type,detail::check_char_t>()
        .implicit(_LIT("floo")),
      _LIT("case 12")),
    co::make_operand(_LIT("operand_key"),
      co::basic_value<string_type,detail::check_char_t>())
  };

  std::tie(std::ignore,vm) =
    co::parse_arguments(argv.data(),argv.data()+argv.size(),options);

  BOOST_REQUIRE(detail::contents_equal<string_type>(vm,
    variable_map_type{
      {_LIT("foo"),{string_type(_LIT("floopy"))}},
      {_LIT("bar"),{string_type(_LIT("floo"))}},
      {_LIT("operand_key"),{string_type(_LIT("bloppy"))}}
    }));
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc


text:
//
// Copyright 2018 - 2021 (C). Alex Robenko. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "Cmake.h"

#include <fstream>

#include <boost/filesystem.hpp>

#include "Generator.h"
#include "common.h"

namespace bf = boost::filesystem;

namespace commsdsl2old
{

namespace
{
const std::string FetchScriptStr("CC_Prefetch.cmake");
}

bool Cmake::write(Generator& generator)
{
    Cmake obj(generator);
    return
        obj.writeMain() &&
        obj.writePlugin() &&
        obj.writeTest() &&
        obj.writePrefetch();
}

bool Cmake::writeMain() const
{
    auto dir = m_generator.outputDir();
    if (dir.empty()) {
        return false;
    }

    bf::path filePath(dir);
    filePath /= common::cmakeListsFileStr();

    std::string filePathStr(filePath.string());

    m_generator.logger().info("Generating " + filePathStr);
    std::ofstream stream(filePathStr);
    if (!stream) {
        m_generator.logger().error("Failed to open \"" + filePathStr + "\" for writing.");
        return false;
    }

    auto allInterfaces = m_generator.getAllInterfaces();
    assert(!allInterfaces.empty());
    auto* firstInterface = allInterfaces.front();
    assert(!firstInterface->name().empty());

    auto allFrames = m_generator.getAllFrames();
    assert(!allFrames.empty());
    auto* firstFrame = allFrames.front();
    assert(!firstFrame->name().empty());

    std::string build_test_opt("OFF");
    if (m_generator.testsBuildEnabledByDefault()) {
        build_test_opt = "ON";
    }

    std::string build_plugin_opt("OFF");
    if (m_generator.pluginBuildEnabledByDefault()) {
        build_plugin_opt = "ON";
    }

    common::ReplacementMap replacements;
    replacements.insert(std::make_pair("PROJ_NAME", m_generator.schemaName()));
    replacements.insert(std::make_pair("PROJ_NAMESPACE", m_generator.mainNamespace()));
    replacements.insert(std::make_pair("PROJ_CAP_NAMESPACE", common::toUpperCopy(m_generator.mainNamespace())));
    replacements.insert(std::make_pair("CC_TAG", m_generator.commsChampionTag()));
    replacements.insert(std::make_pair("APPEND", m_generator.getExtraAppendForFile(common::cmakeListsFileStr())));
    replacements.insert(std::make_pair("DEFAULT_INTERFACE", m_generator.scopeForInterface(firstInterface->externalRef(), true, true)));
    replacements.insert(std::make_pair("DEFAULT_FRAME", m_generator.scopeForFrame(firstFrame->externalRef(), true, true)));
    replacements.insert(std::make_pair("DEFAULT_OPTIONS", m_generator.scopeForOptions(common::defaultOptionsStr(), true, true)));
    replacements.insert(std::make_pair("DEFAULT_INPUT", m_generator.scopeForInput(common::allMessagesStr(), true, true)));
    replacements.insert(std::make_pair("BUILD_TEST_OPT", build_test_opt));
    replacements.insert(std::make_pair("BUILD_PLUGIN_OPT", build_plugin_opt));

    static const std::string Template =
        "cmake_minimum_required (VERSION 3.1)\n"
        "project (\"#^#PROJ_NAME#$#\")\n\n"
        "option (OPT_BUILD_TEST \"Build and install test applications.\" #^#BUILD_TEST_OPT#$#)\n"
        "option (OPT_BUILD_PLUGIN \"Build and install CommsChampion plugin.\" #^#BUILD_PLUGIN_OPT#$#)\n"
        "option (OPT_NO_COMMS \"Forcefully exclude checkout and install of COMMS library. \\\n"
        "    Works only if OPT_BUILD_TEST and OPT_BUILD_PLUGIN options weren't used\" OFF)\n"
        "option (OPT_WARN_AS_ERR \"Treat warning as error\" ON)\n"
        "option (OPT_USE_CCACHE \"Use of ccache on UNIX system\" ON)\n"
        "option (OPT_EXTERNALS_UPDATE_DISCONNECTED \"Allow skip of external projects update.\" OFF)\n\n"
        "# Other parameters:\n"
        "# OPT_CMAKE_EXPORT_NAMESPACE - Set namespace for a protocol library\n"
        "#     exported via generated *Config.cmake file. Defaults to \"cc\".\n"
        "# OPT_CC_TAG - Override default tag of cc_tools_qt project.\n"
        "# OPT_QT_DIR - Path to custom Qt5 install directory.\n"
        "# OPT_CC_MAIN_INSTALL_DIR - Path to CommsChampion external install directory\n"
        "#       (if such already built).\n"
        "# OPT_TEST_OPTIONS - Class name of the options for test applications,\n"
        "#       defaults to #^#DEFAULT_OPTIONS#$#.\n"
        "# OPT_TEST_INTERFACE - Class name of the interface for test applications,\n"
        "#       defaults to #^#DEFAULT_INTERFACE#$#.\n"
        "# OPT_TEST_FRAME - Class name of the frame for test applications,\n"
        "#       defaults to #^#DEFAULT_FRAME#$#.\n"
        "# OPT_TEST_INPUT_MESSAGES - All input messages bundle for test applications,\n"
        "#       defaults to #^#DEFAULT_INPUT#$#.\n"
        "# OPT_EXTERNALS_DIR - Directory where externals (cc_tools_qt) are checked out,\n"
        "#       defaults to ${PROJECT_BINARY_DIR}/externals.\n"
        "# OPT_MSVC_FORCE_WARN_LEVEL - Force msvc warning level\n\n"
        "if (CMAKE_TOOLCHAIN_FILE AND EXISTS ${CMAKE_TOOLCHAIN_FILE})\n"
        "    message(STATUS \"Loading toolchain from ${CMAKE_TOOLCHAIN_FILE}\")\n"
        "endif()\n\n"
        "if (\"${OPT_CC_TAG}\" STREQUAL \"\")\n"
        "    set (OPT_CC_TAG \"#^#CC_TAG#$#\")\n"
        "endif()\n\n"
        "if (NOT CMAKE_CXX_STANDARD)\n"
        "    set (CMAKE_CXX_STANDARD 11)\n"
        "endif()\n\n"
        "if (\"${OPT_EXTERNALS_DIR}\" STREQUAL \"\")\n"
        "    set (OPT_EXTERNALS_DIR \"${PROJECT_BINARY_DIR}/externals\")\n"
        "endif()\n\n"
        "include(GNUInstallDirs)\n"
        "set (LIB_INSTALL_DIR ${CMAKE_INSTALL_LIBDIR})\n"
        "set (BIN_INSTALL_DIR ${CMAKE_INSTALL_BINDIR})\n"
        "set (INC_INSTALL_DIR ${CMAKE_INSTALL_INCLUDEDIR})\n"
        "set (CONFIG_INSTALL_DIR ${CMAKE_INSTALL_DATADIR}/CommsChampion)\n"
        "set (PLUGIN_INSTALL_DIR ${CMAKE_INSTALL_LIBDIR}/CommsChampion/plugin)\n"
        "set (DOC_INSTALL_DIR ${CMAKE_INSTALL_DOCDIR})\n\n"
        "######################################################################\n\n"
        "if (OPT_BUILD_PLUGIN)\n"
        "    if (NOT \"${OPT_QT_DIR}\" STREQUAL \"\")\n"
        "        list (APPEND CMAKE_PREFIX_PATH ${OPT_QT_DIR})\n"
        "    endif ()\n\n"
        "    find_package(Qt5Core)\n"
        "    find_package(Qt5Widgets)\n"
        "endif ()\n\n"
        "######################################################################\n\n"
        "# Use external CommsChampion project or compile it in place\n"
        "set (CC_EXTERNAL_TGT \"cc_tools_qt_external\")\n"
        "if (OPT_BUILD_TEST OR OPT_BUILD_PLUGIN)\n"
        "    set (external_cc_needed TRUE)\n"
        "endif ()\n\n"
        "if ((external_cc_needed OR (NOT OPT_NO_COMMS)) AND (\"${OPT_CC_MAIN_INSTALL_DIR}\" STREQUAL \"\"))\n"
        "    include (${PROJECT_SOURCE_DIR}/cmake/CC_Prefetch.cmake)\n"
        "    cc_prefetch(SRC_DIR \"${OPT_EXTERNALS_DIR}/cc_tools_qt\" TAG \"${OPT_CC_TAG}\")\n"
        "    include(${OPT_EXTERNALS_DIR}/cc_tools_qt/cmake/CC_External.cmake)\n\n"
        "    set (qt_dir_opt)\n"
        "    if (NOT \"${OPT_QT_DIR}\" STREQUAL \"\")\n"
        "        set (qt_dir_opt QT_DIR \"${OPT_QT_DIR}\")\n"
        "    endif ()\n\n"
        "    set (no_tools_opt)\n"
        "    if (NOT ${OPT_BUILD_PLUGIN})\n"
        "        set (no_tools_opt NO_TOOLS)\n"
        "    endif ()\n\n"
        "    set (cc_update_disconnected_opt)\n"
        "    if (${OPT_EXTERNALS_UPDATE_DISCONNECTED})\n"
        "        set (cc_update_disconnected_opt \"UPDATE_DISCONNECTED\")\n"
        "    endif ()\n\n"
        "    cc_build_as_external_project(\n"
        "        SRC_DIR ${OPT_EXTERNALS_DIR}/cc_tools_qt\n"
        "        BUILD_DIR ${PROJECT_BINARY_DIR}/cc_tools_qt\n"
        "        INSTALL_DIR \"${CMAKE_INSTALL_PREFIX}\"\n"
        "        TAG ${OPT_CC_TAG}\n"
        "        TGT ${CC_EXTERNAL_TGT}\n"
        "        ${qt_dir_opt} ${no_tools_opt} ${cc_update_disconnected_opt}\n"
        "        CMAKE_ARGS\n"
        "            -DCC_BUILD_UNIT_TESTS=OFF -DCC_WARN_AS_ERR=OFF\n"
        "    )\n"
        "    set (cc_compile_file \"${OPT_EXTERNALS_DIR}/cc_tools_qt/cmake/CC_Compile.cmake\")\n"
        "elseif (external_cc_needed)\n"
        "    list (APPEND CMAKE_PREFIX_PATH \"${OPT_CC_MAIN_INSTALL_DIR}\")\n"
        "    find_package(CommsChampion NO_MODULE)\n"
        "    set (cc_compile_file \"${OPT_CC_MAIN_INSTALL_DIR}/lib/LibComms/cmake/CC_Compile.cmake\")\n"
        "endif ()\n\n"
        "if (EXISTS ${cc_compile_file})\n"
        "    # Set compiler flags\n"
        "    set (warn_as_err_opt)\n"
        "    if (OPT_WARN_AS_ERR)\n"
        "        set (warn_as_err_opt \"WARN_AS_ERR\")\n"
        "    endif ()\n\n"
        "    set (ccache_opt)\n"
        "    if (OPT_USE_CCACHE)\n"
        "        set (ccache_opt \"USE_CCACHE\")\n"
        "    endif ()\n\n"
        "    include(${cc_compile_file})\n"
        "    cc_compile(${warn_as_err_opt} ${ccache_opt})\n"
        "    if (NOT \"${OPT_MSVC_FORCE_WARN_LEVEL}\" STREQUAL \"\")\n"
        "        cc_msvc_force_warn_opt(\"${OPT_MSVC_FORCE_WARN_LEVEL}\")\n"
        "    endif()\n"
        "endif ()\n\n"
        "######################################################################\n\n"
        "# Define documentation target\n"
        "find_package (Doxygen)\n"
        "if (DOXYGEN_FOUND)\n"
        "    set (doc_output_dir \"${CMAKE_INSTALL_PREFIX}/${DOC_INSTALL_DIR}\")\n"
        "    set (match_str \"OUTPUT_DIRECTORY[^\\n]*\")\n"
        "    set (replacement_str \"OUTPUT_DIRECTORY = ${doc_output_dir}\")\n"
        "    set (config_file \"${CMAKE_CURRENT_SOURCE_DIR}/doc/doxygen.conf\")\n"
        "    set (OPT_DOXYGEN_CONFIG_FILE \"${CMAKE_CURRENT_BINARY_DIR}/doxygen.conf\")\n\n"
        "    file (READ ${config_file} config_text)\n"
        "    string (REGEX REPLACE \"${match_str}\" \"${replacement_str}\" modified_config_text \"${config_text}\")\n"
        "    file (WRITE \"${OPT_DOXYGEN_CONFIG_FILE}\" \"${modified_config_text}\")\n"
        "    set (doc_tgt \"doc_#^#PROJ_NAMESPACE#$#\")\n"
        "    add_custom_target (\"${doc_tgt}\"\n"
        "        COMMAND ${CMAKE_COMMAND} -E make_directory ${doc_output_dir}\n"
        "        COMMAND ${DOXYGEN_EXECUTABLE} ${OPT_DOXYGEN_CONFIG_FILE}\n"
        "        WORKING_DIRECTORY ${PROJECT_SOURCE_DIR})\n"
        "endif ()\n\n"
        "######################################################################\n\n"
        "# Define protocol library\n"
        "add_library(#^#PROJ_NAMESPACE#$# INTERFACE)\n\n"
        "target_include_directories(#^#PROJ_NAMESPACE#$# INTERFACE\n"
        "    $<INSTALL_INTERFACE:include>\n"
        "    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>\n"
        ")\n\n"
        "if (external_cc_needed AND (NOT TARGET ${CC_EXTERNAL_TGT}))\n"
        "    if (NOT TARGET cc::comms)\n"
        "        message (FATAL_ERROR \"COMMS library is not found\")\n"
        "    endif()\n\n"
        "    target_link_libraries(#^#PROJ_NAMESPACE#$# INTERFACE cc::comms)\n"
        "endif ()\n\n"
        "if (\"${OPT_CMAKE_EXPORT_NAMESPACE}\" STREQUAL \"\")\n"
        "    set (OPT_CMAKE_EXPORT_NAMESPACE \"cc\")\n"
        "endif ()\n\n"
        "install(TARGETS #^#PROJ_NAMESPACE#$# EXPORT #^#PROJ_NAMESPACE#$#Config)\n"
        "install(EXPORT #^#PROJ_NAMESPACE#$#Config\n"
        "    DESTINATION ${LIB_INSTALL_DIR}/#^#PROJ_NAMESPACE#$#/cmake\n"
        "    NAMESPACE ${OPT_CMAKE_EXPORT_NAMESPACE}::\n"
        ")\n\n"
        "install (\n"
        "    DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/#^#PROJ_NAMESPACE#$#\n"
        "    DESTINATION ${INC_INSTALL_DIR}\n"
        ")\n\n"
        "file (READ \"${PROJECT_SOURCE_DIR}/include/#^#PROJ_NAMESPACE#$#/Version.h\" version_file)\n"
        "string (REGEX MATCH \"#^#PROJ_CAP_NAMESPACE#$#_MAJOR_VERSION[^0-9]*([0-9]*)U*\" _ ${version_file})\n"
        "set (major_ver ${CMAKE_MATCH_1})\n"
        "string (REGEX MATCH \"#^#PROJ_CAP_NAMESPACE#$#_MINOR_VERSION[^0-9]*([0-9]*)U*\" _ ${version_file})\n"
        "set (minor_ver ${CMAKE_MATCH_1})\n"
        "string (REGEX MATCH \"#^#PROJ_CAP_NAMESPACE#$#_PATCH_VERSION[^0-9]*([0-9]*)U*\" _ ${version_file})\n"
        "set (patch_ver ${CMAKE_MATCH_1})\n"
        "if ((NOT \"${major_ver}\" STREQUAL \"\") AND\n"
        "    (NOT \"${minor_ver}\" STREQUAL \"\") AND\n"
        "    (NOT \"${patch_ver}\" STREQUAL \"\"))\n"
        "    set (#^#PROJ_CAP_NAMESPACE#$#_VERSION \"${major_ver}.${minor_ver}.${patch_ver}\")\n\n"
        "    message (STATUS \"Detected version ${#^#PROJ_CAP_NAMESPACE#$#_VERSION} of the protocol\")\n"
        "    include(CMakePackageConfigHelpers)\n"
        "    write_basic_package_version_file(\n"
        "        ${CMAKE_BINARY_DIR}/#^#PROJ_NAMESPACE#$#ConfigVersion.cmake\n"
        "        VERSION ${#^#PROJ_CAP_NAMESPACE#$#_VERSION}\n"
        "        COMPATIBILITY AnyNewerVersion)\n\n"
        "    install (\n"
        "        FILES ${CMAKE_BINARY_DIR}/#^#PROJ_NAMESPACE#$#ConfigVersion.cmake\n"
        "        DESTINATION ${LIB_INSTALL_DIR}/#^#PROJ_NAMESPACE#$#/cmake/)\n"
        "endif ()\n\n"
        "######################################################################\n\n"
        "if (OPT_BUILD_TEST)\n"
        "    add_subdirectory(test)\n"
        "endif ()\n\n"
        "######################################################################\n\n"
        "if (OPT_BUILD_PLUGIN)\n"
        "    add_subdirectory(cc_plugin)\n"
        "endif ()\n"
        "#^#APPEND#$#\n";

    auto str = common::processTemplate(Template, replacements);
    stream << str;

    stream.flush();
    if (!stream.good()) {
        m_generator.logger().error("Failed to write \"" + filePathStr + "\".");
        return false;
    }
    return true;
}

bool Cmake::writePlugin() const
{
    auto dir = m_generator.pluginDir();
    if (dir.empty()) {
        return false;
    }

    bf::path filePath(dir);
    filePath /= common::cmakeListsFileStr();

    std::string filePathStr(filePath.string());

    m_generator.logger().info("Generating " + filePathStr);
    std::ofstream stream(filePathStr);
    if (!stream) {
        m_generator.logger().error("Failed to open \"" + filePathStr + "\" for writing.");
        return false;
    }

    common::StringsList calls;
    auto plugins = m_generator.getPlugins();
    for (auto* p : plugins) {
        auto pName = common::nameToClassCopy(p->adjustedName());

        static const std::string FalseStr = "FALSE";
        static const std::string TrueStr = "TRUE";
        const std::string* hasConfigWidget = &FalseStr;
        if (p->hasConfigWidget()) {
            hasConfigWidget = &TrueStr;
        }
        calls.push_back("cc_plugin (\"" + pName + "\" " + *hasConfigWidget + ")");
    }

    common::ReplacementMap replacements;
    replacements.insert(std::make_pair("SOURCES", m_generator.pluginCommonSources()));
    replacements.insert(std::make_pair("PROJ_NAMESPACE", m_generator.mainNamespace()));
    replacements.insert(std::make_pair("PLUGINS", common::listToString(calls, "\n", "\n")));
    if (plugins.size() == 1U) {
        auto str =
            "if (TARGET ${CC_EXTERNAL_TGT})\n"
            "    install (\n"
            "        FILES plugin/" + common::nameToClassCopy(plugins.front()->adjustedName()) + ".cfg\n"
            "        DESTINATION ${CONFIG_INSTALL_DIR}\n"
            "        RENAME \"default.cfg\")\n"
            "endif()\n\n";
        replacements.insert(std::make_pair("DEFAULT_INSTALL", std::move(str)));

    }

    std::vector<std::string> appendPath = {
        common::pluginNsStr(),
        common::cmakeListsFileStr()
    };

    replacements.insert(std::make_pair("APPEND", m_generator.getExtraAppendForFile(appendPath)));

    static const std::string Template =
        "set (ALL_MESSAGES_LIB \"all_messages\")\n\n"
        "######################################################################\n\n"
        "function (cc_plugin_all_messages)\n"
        "    set (name \"${ALL_MESSAGES_LIB}\")\n"
        "    set (src\n"
        "        #^#SOURCES#$#\n"
        "    )\n\n"
        "    add_library (${name} STATIC ${src})\n"
        "    target_link_libraries (${name} PUBLIC #^#PROJ_NAMESPACE#$# cc::comms cc::cc_tools_qt Qt5::Widgets Qt5::Core)\n"
        "    target_include_directories (${name} PUBLIC ${PROJECT_SOURCE_DIR})\n"
        "    target_compile_options(${name} PRIVATE\n"
        "        $<$<CXX_COMPILER_ID:MSVC>:/bigobj /wd4127 /wd5054>\n"
        "        $<$<CXX_COMPILER_ID:GNU>:-ftemplate-depth=2048>\n"
        "        $<$<CXX_COMPILER_ID:Clang>:-ftemplate-depth=2048>\n"
        "    )\n\n"
        "    if (CC_COMMS_CHAMPION_FOUND)\n"
        "        if (CC_PLUGIN_DIR)\n"
        "            file (RELATIVE_PATH rel_plugin_install_path \"${CC_ROOT_DIR}\" \"${CC_PLUGIN_DIR}\")\n"
        "            set (PLUGIN_INSTALL_DIR \"${rel_plugin_install_path}\")\n"
        "        endif()\n"
        "    endif ()\n\n"
        "    if (TARGET ${CC_EXTERNAL_TGT})\n"
        "        add_dependencies(${name} ${CC_EXTERNAL_TGT})\n"
        "    endif ()\n"
        "endfunction()\n\n"
        "######################################################################\n\n"
        "function (cc_plugin protocol has_config_widget)\n"
        "    set (name \"cc_plugin_${protocol}\")\n\n"
        "    set (meta_file \"${CMAKE_CURRENT_SOURCE_DIR}/${protocol}.json\")\n"
        "    set (stamp_file \"${CMAKE_CURRENT_BINARY_DIR}/${protocol}_refresh_stamp.txt\")\n\n"
        "    if ((NOT EXISTS ${stamp_file}) OR (${meta_file} IS_NEWER_THAN ${stamp_file}))\n"
        "        execute_process(\n"
        "            COMMAND ${CMAKE_COMMAND} -E touch ${CMAKE_CURRENT_SOURCE_DIR}/plugin/${protocol}Plugin.h)\n\n"
        "        execute_process(\n"
        "            COMMAND ${CMAKE_COMMAND} -E touch ${stamp_file})\n"
        "    endif ()\n\n"
        "    set (src\n"
        "        plugin/${protocol}Protocol.cpp\n"
        "        plugin/${protocol}Plugin.cpp\n"
        "    )\n\n"
        "    set (hdr\n"
        "        plugin/${protocol}Plugin.h\n"
        "    )\n\n"
        "    if (has_config_widget)\n"
        "        list (APPEND src plugin/${protocol}ConfigWidget.cpp)\n"
        "        list (APPEND hdr plugin/${protocol}ConfigWidget.h)\n"
        "    endif ()\n\n"
        "    qt5_wrap_cpp(moc ${hdr})\n\n"
        "    set(extra_link_opts)\n"
        "    if (CMAKE_COMPILER_IS_GNUCC)\n"
        "        set(extra_link_opts \"-Wl,--no-undefined\")\n"
        "    endif ()\n\n"
        "    add_library (${name} MODULE ${src} ${moc})\n"
        "    target_link_libraries (${name} ${ALL_MESSAGES_LIB} cc::cc_tools_qt Qt5::Widgets Qt5::Core ${extra_link_opts})\n"
        "    target_compile_options(${name} PRIVATE\n"
        "        $<$<CXX_COMPILER_ID:MSVC>:/bigobj /wd4127 /wd5054>\n"
        "        $<$<CXX_COMPILER_ID:GNU>:-ftemplate-depth=2048>\n"
        "        $<$<CXX_COMPILER_ID:Clang>:-ftemplate-depth=2048>\n"
        "    )\n\n"
        "    install (\n"
        "        TARGETS ${name}\n"
        "        DESTINATION ${PLUGIN_INSTALL_DIR})\n\n"
        "    install (\n"
        "        FILES plugin/${protocol}.cfg\n"
        "        DESTINATION ${CONFIG_INSTALL_DIR})\n\n"
        "endfunction()\n\n"
        "######################################################################\n\n"
        "if (NOT Qt5Core_FOUND)\n"
        "    message (WARNING \"Can NOT compile protocol plugin due to missing QT5 Core library\")\n"
        "    return ()\n"
        "endif ()\n\n"
        "if (NOT Qt5Widgets_FOUND)\n"
        "    message (WARNING \"Can NOT compile protocol plugin due to missing QT5 Widgets library\")\n"
        "    return ()\n"
        "endif ()\n\n"
        "if (TARGET cc::cc_tools_qt)\n"
        "    get_target_property(cc_inc cc::cc_tools_qt INTERFACE_INCLUDE_DIRECTORIES)\n\n"
        "    if (NOT cc_inc)\n"
        "        message (FATAL_ERROR \"No include directories are specified for cc::cc_tools_qt\")\n"
        "    endif ()\n\n"
        "    # Global include is required for \"moc\"\n"
        "    include_directories (${cc_inc})\n"
        "endif ()\n\n"
        "cc_plugin_all_messages()\n\n"
        "#^#PLUGINS#$#\n"
        "#^#DEFAULT_INSTALL#$#\n"
        "#^#APPEND#$#\n";

    auto str = common::processTemplate(Template, replacements);
    stream << str;
    stream.flush();
    if (!stream.good()) {
        m_generator.logger().error("Failed to write \"" + filePathStr + "\".");
        return false;
    }
    return true;
}

bool Cmake::writeTest() const
{
    auto dir = m_generator.testDir();
    if (dir.empty()) {
        return false;
    }

    bf::path filePath(dir);
    filePath /= common::cmakeListsFileStr();

    std::string filePathStr(filePath.string());

    m_generator.logger().info("Generating " + filePathStr);
    std::ofstream stream(filePathStr);
    if (!stream) {
        m_generator.logger().error("Failed to open \"" + filePathStr + "\" for writing.");
        return false;
    }

    auto allInterfaces = m_generator.getAllInterfaces();
    assert(!allInterfaces.empty());
    auto* firstInterface = allInterfaces.front();
    assert(!firstInterface->name().empty());

    auto allFrames = m_generator.getAllFrames();
    assert(!allFrames.empty());
    auto* firstFrame = allFrames.front();
    assert(!firstFrame->name().empty());

    std::vector<std::string> appendPath = {
        common::testStr(),
        common::cmakeListsFileStr()
    };

    common::ReplacementMap replacements;
    replacements.insert(std::make_pair("PROJ_NS", m_generator.mainNamespace()));
    replacements.insert(std::make_pair("APPEND", m_generator.getExtraAppendForFile(appendPath)));
    replacements.insert(std::make_pair("INTERFACE_SCOPE", m_generator.scopeForInterface(firstInterface->externalRef(), true, true)));
    replacements.insert(std::make_pair("FRAME_SCOPE", m_generator.scopeForFrame(firstFrame->externalRef(), true, true)));
    replacements.insert(std::make_pair("OPTIONS_SCOPE", m_generator.scopeForOptions(common::defaultOptionsStr(), true, true)));
    replacements.insert(std::make_pair("INPUT_SCOPE", m_generator.scopeForInput(common::allMessagesStr(), true, true)));

    static const std::string Template =
        "######################################################################\n"
        "function (define_test name)\n"
        "    set (src ${name}.cpp)\n"
        "    add_executable(${name} ${src})\n"
        "    target_link_libraries(${name} PRIVATE #^#PROJ_NS#$# cc::comms)\n\n"
        "    set (extra_defs)\n"
        "    if (NOT \"${OPT_TEST_INTERFACE}\" STREQUAL \"\")\n"
        "        list (APPEND extra_defs -DINTERFACE=${OPT_TEST_INTERFACE})\n"
        "    endif ()\n\n"
        "    if (NOT \"${OPT_TEST_INTERFACE_HEADER}\" STREQUAL \"\")\n"
        "        list (APPEND extra_defs -DINTERFACE_HEADER=${OPT_TEST_INTERFACE_HEADER})\n"
        "    endif ()\n\n"
        "    if (NOT \"${OPT_TEST_FRAME}\" STREQUAL \"\")\n"
        "        list (APPEND extra_defs -DFRAME=${OPT_TEST_FRAME})\n"
        "    endif ()\n\n"
        "    if (NOT \"${OPT_TEST_FRAME_HEADER}\" STREQUAL \"\")\n"
        "        list (APPEND extra_defs -DFRAME_HEADER=${OPT_TEST_FRAME_HEADER})\n"
        "    endif ()\n\n"
        "    if (NOT \"${OPT_TEST_OPTIONS}\" STREQUAL \"\")\n"
        "        list (APPEND extra_defs -DOPTIONS=${OPT_TEST_OPTIONS})\n"
        "    endif ()\n\n"
        "    if (NOT \"${OPT_TEST_OPTIONS_HEADER}\" STREQUAL \"\")\n"
        "        list (APPEND extra_defs -DOPTIONS_HEADER=${OPT_TEST_OPTIONS_HEADER})\n"
        "    endif ()\n\n"
        "    if (NOT \"${OPT_TEST_INPUT_MESSAGES}\" STREQUAL \"\")\n"
        "        list (APPEND extra_defs -DINPUT_MESSAGES=${OPT_TEST_INPUT_MESSAGES})\n"
        "    endif ()\n\n"
        "    if (NOT \"${OPT_TEST_INPUT_MESSAGES_HEADER}\" STREQUAL \"\")\n"
        "        list (APPEND extra_defs -DINPUT_MESSAGES_HEADER=${OPT_TEST_INPUT_MESSAGES_HEADER})\n"
        "    endif ()\n\n"
        "    if (extra_defs)\n"
        "        target_compile_definitions(${name} PRIVATE ${extra_defs})\n"
        "    endif ()\n\n"
        "    install (\n"
        "        TARGETS ${name}\n"
        "        DESTINATION ${BIN_INSTALL_DIR}\n"
        "    )\n\n"
        "    if (TARGET ${CC_EXTERNAL_TGT})\n"
        "        add_dependencies(${name} ${CC_EXTERNAL_TGT})\n"
        "    endif ()\n\n"
        "    target_compile_options(${name} PRIVATE\n"
        "        $<$<CXX_COMPILER_ID:MSVC>:/wd4996 /bigobj>\n"
        "        $<$<CXX_COMPILER_ID:GNU>:-Wno-unused-function -ftemplate-depth=2048>\n"
        "        $<$<CXX_COMPILER_ID:Clang>:-Wno-unused-function -Wno-unneeded-internal-declaration -ftemplate-depth=2048>\n"
        "    )\n"
        "endfunction ()\n\n"
        "######################################################################\n\n"
        "if (\"${OPT_TEST_INTERFACE}\" STREQUAL \"\")\n"
        "    set (OPT_TEST_INTERFACE \"#^#INTERFACE_SCOPE#$#\")\n"
        "endif ()\n\n"
        "if (\"${OPT_TEST_FRAME}\" STREQUAL \"\")\n"
        "    set (OPT_TEST_FRAME \"#^#FRAME_SCOPE#$#\")\n"
        "endif ()\n\n"
        "if (\"${OPT_TEST_OPTIONS}\" STREQUAL \"\")\n"
        "    set (OPT_TEST_OPTIONS \"#^#OPTIONS_SCOPE#$#\")\n"
        "endif ()\n\n"
        "if (\"${OPT_TEST_INPUT_MESSAGES}\" STREQUAL \"\")\n"
        "    set (OPT_TEST_INPUT_MESSAGES \"#^#INPUT_SCOPE#$#\")\n"
        "endif ()\n\n"
        "string (REPLACE \"::\" \"/\" OPT_TEST_INTERFACE_HEADER \"${OPT_TEST_INTERFACE}.h\")\n"
        "string (REPLACE \"::\" \"/\" OPT_TEST_FRAME_HEADER \"${OPT_TEST_FRAME}.h\")\n"
        "string (REPLACE \"::\" \"/\" OPT_TEST_OPTIONS_HEADER \"${OPT_TEST_OPTIONS}.h\")\n"
        "string (REPLACE \"::\" \"/\" OPT_TEST_INPUT_MESSAGES_HEADER \"${OPT_TEST_INPUT_MESSAGES}.h\")\n\n"
        "define_test(#^#PROJ_NS#$#_input_test)\n"
        "#^#APPEND#$#\n";

    auto str = common::processTemplate(Template, replacements);
    stream << str;
    stream.flush();
    if (!stream.good()) {
        m_generator.logger().error("Failed to write \"" + filePathStr + "\".");
        return false;
    }
    return true;
}

bool Cmake::writePrefetch() const
{
    auto dir = m_generator.cmakeDir();
    if (dir.empty()) {
        return false;
    }

    bf::path filePath(dir);
    filePath /= FetchScriptStr;

    std::string filePathStr(filePath.string());

    m_generator.logger().info("Generating " + filePathStr);
    std::ofstream stream(filePathStr);
    if (!stream) {
        m_generator.logger().error("Failed to open \"" + filePathStr + "\" for writing.");
        return false;
    }

    static const std::string Contents =
        "set (CC_FETCH_DEFAULT_REPO \"https://github.com/commschamp/cc_tools_qt.git\")\n"
        "set (CC_FETCH_DEFAULT_TAG \"master\")\n\n"
        "function (cc_prefetch)\n"
        "    set (_prefix CC_FETCH)\n"
        "    set (_options)\n"
        "    set (_oneValueArgs SRC_DIR REPO TAG)\n"
        "    set (_mutiValueArgs)\n"
        "    cmake_parse_arguments(${_prefix} \"${_options}\" \"${_oneValueArgs}\" \"${_mutiValueArgs}\" ${ARGN})\n\n"
        "    if (NOT CC_FETCH_SRC_DIR)\n"
        "        message (FATAL_ERROR \"The SRC_DIR parameter is not provided\")\n"
        "    endif ()\n\n"
        "    if (NOT CC_FETCH_REPO)\n"
        "        set (CC_FETCH_REPO ${CC_FETCH_DEFAULT_REPO})\n"
        "    endif ()\n\n"
        "    if (NOT CC_FETCH_TAG)\n"
        "        set (CC_FETCH_TAG ${CC_FETCH_DEFAULT_TAG})\n"
        "    endif ()\n\n"
        "    if (NOT GIT_FOUND)\n"
        "        find_package(Git REQUIRED)\n"
        "    endif ()\n\n"
        "    if (EXISTS \"${CC_FETCH_SRC_DIR}/cmake/CC_External.cmake\")\n"
        "        return ()\n"
        "    endif()\n\n"
        "    execute_process (\n"
        "        COMMAND ${CMAKE_COMMAND} -E remove_directory \"${CC_FETCH_SRC_DIR}\"\n"
        "    )\n\n"
        "    execute_process (\n"
        "        COMMAND ${CMAKE_COMMAND} -E make_directory \"${CC_FETCH_SRC_DIR}\"\n"
        "    )\n\n"
        "    execute_process (\n"
        "        COMMAND\n"
        "            ${GIT_EXECUTABLE} clone -b ${CC_FETCH_TAG} ${CC_FETCH_REPO} ${CC_FETCH_SRC_DIR}\n"
        "        RESULT_VARIABLE git_result\n"
        "    )\n\n"
        "    if (NOT \"${git_result}\" STREQUAL \"0\")\n"
        "        message (WARNING \"git clone/checkout failed\")\n"
        "    endif ()\n\n"
        "endfunction()\n";

    stream << Contents;
    stream.flush();
    if (!stream.good()) {
        m_generator.logger().error("Failed to write \"" + filePathStr + "\".");
        return false;
    }
    return true;
}

} // namespace commsdsl2old

ext: cpp

max_stars_repo_name: arobenko/commsdsl

max_issues_repo_name: arobenko/commsdsl

max_forks_repo_name: arobenko/commsdsl


text:
/*
 * Copyright (c) 2013, Peter Thorson. 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 WebSocket++ Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON 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.
 *
 */
//#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE transport_asio_timers
#include <boost/test/unit_test.hpp>

#include <exception>
#include <iostream>

#include <websocketpp/common/thread.hpp>

#include <websocketpp/transport/asio/endpoint.hpp>
#include <websocketpp/transport/asio/security/tls.hpp>

// Concurrency
#include <websocketpp/concurrency/none.hpp>

// HTTP
#include <websocketpp/http/request.hpp>
#include <websocketpp/http/response.hpp>

// Loggers
#include <websocketpp/logger/stub.hpp>
//#include <websocketpp/logger/basic.hpp>

#include <boost/asio.hpp>

// Accept a connection, read data, and discard until EOF
void run_dummy_server(int port) {
    using boost::asio::ip::tcp;

    try {
        boost::asio::io_service io_service;
        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v6(), port));
        tcp::socket socket(io_service);

        acceptor.accept(socket);
        for (;;) {
            char data[512];
            boost::system::error_code ec;
            socket.read_some(boost::asio::buffer(data), ec);
            if (ec == boost::asio::error::eof) {
                break;
            } else if (ec) {
                // other error
                throw ec;
            }
        }
    } catch (std::exception & e) {
        std::cout << e.what() << std::endl;
    } catch (boost::system::error_code & ec) {
        std::cout << ec.message() << std::endl;
    }
}

// Wait for the specified time period then fail the test
void run_test_timer(long value) {
    boost::asio::io_service ios;
    boost::asio::deadline_timer t(ios,boost::posix_time::milliseconds(value));
    boost::system::error_code ec;
    t.wait(ec);
    BOOST_FAIL( "Test timed out" );
}

struct config {
    typedef websocketpp::concurrency::none concurrency_type;
    //typedef websocketpp::log::basic<concurrency_type,websocketpp::log::alevel> alog_type;
    typedef websocketpp::log::stub alog_type;
    typedef websocketpp::log::stub elog_type;
    typedef websocketpp::http::parser::request request_type;
    typedef websocketpp::http::parser::response response_type;
    typedef websocketpp::transport::asio::tls_socket::endpoint socket_type;

    static const long timeout_socket_pre_init = 1000;
    static const long timeout_proxy = 1000;
    static const long timeout_socket_post_init = 1000;
    static const long timeout_dns_resolve = 1000;
    static const long timeout_connect = 1000;
    static const long timeout_socket_shutdown = 1000;
};

// Mock context that does no validation
typedef websocketpp::lib::shared_ptr<boost::asio::ssl::context> context_ptr;
context_ptr on_tls_init(websocketpp::connection_hdl hdl) {
    return context_ptr(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1));
}

// Mock connection
struct mock_con: public websocketpp::transport::asio::connection<config> {
    typedef websocketpp::transport::asio::connection<config> base;

    mock_con(bool a, config::alog_type& b, config::elog_type& c) : base(a,b,c) {}

    void start() {
        base::init(websocketpp::lib::bind(&mock_con::handle_start,this,
            websocketpp::lib::placeholders::_1));
    }

    void handle_start(const websocketpp::lib::error_code& ec) {
        using websocketpp::transport::asio::socket::make_error_code;
        using websocketpp::transport::asio::socket::error::tls_handshake_timeout;

        BOOST_CHECK_EQUAL( ec, make_error_code(tls_handshake_timeout) );

        base::cancel_socket();
    }
};

typedef websocketpp::transport::asio::connection<config> con_type;
typedef websocketpp::lib::shared_ptr<mock_con> connection_ptr;

struct mock_endpoint : public websocketpp::transport::asio::endpoint<config> {
    typedef websocketpp::transport::asio::endpoint<config> base;

    mock_endpoint() {
        alog.set_channels(websocketpp::log::alevel::all);
        base::init_logging(&alog,&elog);
        init_asio();
    }

    void connect(std::string u) {
        m_con.reset(new mock_con(false,alog,elog));
        websocketpp::uri_ptr uri(new websocketpp::uri(u));

        BOOST_CHECK( uri->get_valid() );
        BOOST_CHECK_EQUAL( base::init(m_con), websocketpp::lib::error_code() );

        base::async_connect(
            m_con,
            uri,
            websocketpp::lib::bind(
                &mock_endpoint::handle_connect,
                this,
                m_con,
                websocketpp::lib::placeholders::_1,
                websocketpp::lib::placeholders::_2
            )
        );
    }

    void handle_connect(connection_ptr con, websocketpp::connection_hdl,
        const websocketpp::lib::error_code & ec)
    {
        BOOST_CHECK( !ec );
        con->start();
    }

    connection_ptr m_con;
    config::alog_type alog;
    config::elog_type elog;
};

BOOST_AUTO_TEST_CASE( tls_handshake_timeout ) {
    websocketpp::lib::thread dummy_server(websocketpp::lib::bind(&run_dummy_server,9005));
    websocketpp::lib::thread timer(websocketpp::lib::bind(&run_test_timer,5000));
    dummy_server.detach();
    timer.detach();

    mock_endpoint endpoint;
    endpoint.set_tls_init_handler(&on_tls_init);
    endpoint.connect("wss://localhost:9005");
    endpoint.run();
}

max_stars_repo_name: anypath/CoinVault

max_stars_repo_licenses: Unlicense OpenSSL MIT

max_issues_repo_name: anypath/CoinVault

max_issues_repo_licenses: Unlicense OpenSSL MIT

max_forks_repo_name: anypath/CoinVault

max_forks_repo_licenses: Unlicense OpenSSL MIT


text:
#define BOOST_LOG_DYN_LINK 1
#include <boost/scoped_ptr.hpp>
#include <boost/log/trivial.hpp>

#include <ros/ros.h>
#include <ros/publisher.h>
#include <signal.h>
#include <camera_info_manager/camera_info_manager.h>
#include <image_transport/image_transport.h>
#include <image_transport/camera_publisher.h>
#include <sensor_msgs/Image.h>
#include <cv_bridge/cv_bridge.h>
#include <dynamic_reconfigure/server.h>
#include <driver_base/SensorLevels.h>
#include <boost/filesystem.hpp>
#include <std_msgs/String.h>

#include <pix2image.h>

void processCallback(const sensor_msgs::ImageConstPtr& msg,
                     const std::string& s, ros::NodeHandle &node_handle, const bool save=false){

  // parsed image from original image

  cv_bridge::CvImagePtr cv_ptr;
  try
    {
      cv_ptr = cv_bridge::toCvCopy(msg, "mono8");
      //cv::imshow("view", cv_bridge::toCvCopy(msg, "mono8")-> image);

    }
  catch (cv_bridge::Exception& e)
    {
      ROS_ERROR("cv_bridge exception: %s", e.what());

    }
  /* Add any OpenCV processing here */
  /* Gray scale image */
  cv::Mat img;
  img = cv_ptr->image.clone();

  std_msgs::Header h = msg -> header;
  std::string name;
  name = std::to_string(h.stamp.sec) + ".tiff";
  std::string PathtoSave;
  PathtoSave = "/home/viper/ros/indigo/catkin_ws/src/pleora_polarcam/images/";

  if (s == "stokes"){

    //std::vector<cv::Mat> angle_image = POLPro::raw2mat(img, false);
    std::vector<cv::Mat> output_img = POLPro::compute_stokes(img, false);

    if (save){
      output_img = POLPro::polar_stokes_preprocessing(output_img, true);
      POLPro::imsave(output_img, name, s, PathtoSave);
    }
    POLPro::imshow(output_img, false, true);

  }else if (s == "polar"){

    if (save){
      std::vector<cv::Mat> out_to_save_imgs = POLPro::compute_polar_params
	(img, false);

      out_to_save_imgs = POLPro::polar_stokes_preprocessing(out_to_save_imgs, false);
      POLPro::imsave(out_to_save_imgs, name, s, PathtoSave);
    }

    std::vector<cv::Mat> output_img = POLPro::compute_polar_params
      (img, false);

    POLPro::imshow(output_img, false, false);

  }else{
    std::vector<cv::Mat> output_img = POLPro::raw2mat(img, true);
    POLPro::imshow(output_img, false, false);
    if (save){
      POLPro::imsave(output_img, name, s, PathtoSave);
    }

  }

}

int main( int argc, char** argv )
{
  // initializing the ros node
  ros::init(argc, argv, "process");
  // creating ros handle, main access point to communicate to ros
  ros::NodeHandle nh;

  // suscribing to the pleora_polarcam node and topic raw_image
  //ros::Subscriber sub = n.subscribe("pleora_polarcam/raw_image",
  //				      1000, processCallback);

  if (argc <= 1) {
    std::cout <<" Usage: display_image Option (mat, stokes, polar) (save/None)"
	      << std::endl;
    return -1;
  }
  std::string s = argv[1];
  cv::namedWindow("Output image");
  cv::startWindowThread();
  image_transport::ImageTransport n(nh);

  // suscribing to image_raw topic
  image_transport::Subscriber sub = n.subscribe("pleora_polarcam_driver/image_raw"
						, 1,
						boost::bind(processCallback,
							    _1, s, boost::ref(nh), argv[2]));

  ros::spin();
  cv::destroyWindow("Output image");

  ros::spin();
  return 0 ;

}