<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2021 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution 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 above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
 *
 *********************************************************************************/

#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>

#include <inviwo/core/algorithm/permutations.h>

namespace inviwo {

TEST(Permutations, permutations) {

    std::array values = {0, 1, 2};
    util::Permutations perm(util::span{values}, 1);

    EXPECT_EQ(*perm.begin(), 0);
    EXPECT_EQ(++perm.begin(), perm.end());

    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*perm.begin(), 1);
    EXPECT_EQ(++perm.begin(), perm.end());

    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*perm.begin(), 2);
    EXPECT_EQ(++perm.begin(), perm.end());

    EXPECT_FALSE(perm.next());

    perm = util::Permutations(util::span{values}, 2);

    auto it = perm.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, perm.end());

    EXPECT_FALSE(perm.next());

    perm = util::Permutations(util::span{values}, 3);

    it = perm.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, perm.end());

    EXPECT_FALSE(perm.next());
}

TEST(Permutations, Combinations) {

    std::array values = {0, 1, 2};
    util::Combinations comb(util::span{values}, 1);

    EXPECT_EQ(*comb.begin(), 0);
    EXPECT_EQ(++comb.begin(), comb.end());

    EXPECT_TRUE(comb.next());
    EXPECT_EQ(*comb.begin(), 1);
    EXPECT_EQ(++comb.begin(), comb.end());

    EXPECT_TRUE(comb.next());
    EXPECT_EQ(*comb.begin(), 2);
    EXPECT_EQ(++comb.begin(), comb.end());

    EXPECT_FALSE(comb.next());

    comb = util::Combinations(util::span{values}, 2);

    auto it = comb.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, comb.end());

    it = comb.begin();
    EXPECT_TRUE(comb.next());
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, comb.end());

    it = comb.begin();
    EXPECT_TRUE(comb.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, comb.end());

    EXPECT_FALSE(comb.next());

    comb = util::Combinations(util::span{values}, 3);

    it = comb.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, comb.end());

    EXPECT_FALSE(comb.next());
}

TEST(Permutations, IndexProduct) {

    std::array sizes = {3, 2};
    util::IndexProduct inds(util::span{sizes});

    auto it = inds.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, inds.end());

    EXPECT_FALSE(inds.next());
}
}  // namespace inviwo
<commit_msg>Core: Permutation unit test gcc fix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2021 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution 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 above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.
 *
 *********************************************************************************/

#include <warn/push>
#include <warn/ignore/all>
#include <gtest/gtest.h>
#include <warn/pop>

#include <inviwo/core/algorithm/permutations.h>

namespace inviwo {

TEST(Permutations, permutations) {

    std::array values = {0, 1, 2};
    auto v = util::span{values};
    util::Permutations perm(v, 1);

    EXPECT_EQ(*perm.begin(), 0);
    EXPECT_EQ(++perm.begin(), perm.end());

    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*perm.begin(), 1);
    EXPECT_EQ(++perm.begin(), perm.end());

    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*perm.begin(), 2);
    EXPECT_EQ(++perm.begin(), perm.end());

    EXPECT_FALSE(perm.next());

    perm = util::Permutations(v, 2);

    auto it = perm.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, perm.end());

    EXPECT_FALSE(perm.next());

    perm = util::Permutations(v, 3);

    it = perm.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, perm.end());

    it = perm.begin();
    EXPECT_TRUE(perm.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, perm.end());

    EXPECT_FALSE(perm.next());
}

TEST(Permutations, Combinations) {

    std::array values = {0, 1, 2};
    auto v = util::span{values};
    util::Combinations comb(v, 1);

    EXPECT_EQ(*comb.begin(), 0);
    EXPECT_EQ(++comb.begin(), comb.end());

    EXPECT_TRUE(comb.next());
    EXPECT_EQ(*comb.begin(), 1);
    EXPECT_EQ(++comb.begin(), comb.end());

    EXPECT_TRUE(comb.next());
    EXPECT_EQ(*comb.begin(), 2);
    EXPECT_EQ(++comb.begin(), comb.end());

    EXPECT_FALSE(comb.next());

    comb = util::Combinations(v, 2);

    auto it = comb.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, comb.end());

    it = comb.begin();
    EXPECT_TRUE(comb.next());
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, comb.end());

    it = comb.begin();
    EXPECT_TRUE(comb.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, comb.end());

    EXPECT_FALSE(comb.next());

    comb = util::Combinations(v, 3);

    it = comb.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(*++it, 2);
    EXPECT_EQ(++it, comb.end());

    EXPECT_FALSE(comb.next());
}

TEST(Permutations, IndexProduct) {

    std::array sizes = {3, 2};
    auto s = util::span{sizes};
    util::IndexProduct inds(s);

    auto it = inds.begin();
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 0);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 1);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 0);
    EXPECT_EQ(++it, inds.end());

    it = inds.begin();
    EXPECT_TRUE(inds.next());
    EXPECT_EQ(*it, 2);
    EXPECT_EQ(*++it, 1);
    EXPECT_EQ(++it, inds.end());

    EXPECT_FALSE(inds.next());
}
}  // namespace inviwo
<|endoftext|>


<commit_before>// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.

/**
 * @file IPFinder.cpp
 *
 */

#include <fastrtps/utils/IPFinder.h>
#include <fastrtps/utils/IPLocator.h>

#if defined(_WIN32)
#pragma comment(lib, "Iphlpapi.lib")
#include <stdio.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <ws2tcpip.h>
#include <assert.h>
#else
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <net/if.h>
#endif

#include <cstddef>
#include <cstring>

using namespace eprosima::fastrtps::rtps;

IPFinder::IPFinder() {
}

IPFinder::~IPFinder() {
}

#if defined(_WIN32)

#define DEFAULT_ADAPTER_ADDRESSES_SIZE 15360

bool IPFinder::getIPs(std::vector<info_IP>* vec_name, bool return_loopback)
{
    DWORD rv, size = DEFAULT_ADAPTER_ADDRESSES_SIZE;
    PIP_ADAPTER_ADDRESSES adapter_addresses, aa;
    PIP_ADAPTER_UNICAST_ADDRESS ua;

    adapter_addresses = (PIP_ADAPTER_ADDRESSES)malloc(DEFAULT_ADAPTER_ADDRESSES_SIZE);

    rv = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, adapter_addresses, &size);

    if (rv != ERROR_SUCCESS)
    {
        adapter_addresses = (PIP_ADAPTER_ADDRESSES)realloc(adapter_addresses, size);

        rv = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, adapter_addresses, &size);
    }

    if (rv != ERROR_SUCCESS)
    {
        fprintf(stderr, "GetAdaptersAddresses() failed...");
        free(adapter_addresses);
        return false;
    }

    for (aa = adapter_addresses; aa != NULL; aa = aa->Next) {
        if (aa->OperStatus == 1) //is ENABLED
        {
            for (ua = aa->FirstUnicastAddress; ua != NULL; ua = ua->Next) {
                char buf[BUFSIZ];

                int family = ua->Address.lpSockaddr->sa_family;

                if (family == AF_INET || family == AF_INET6) //IP4
                {
                    //printf("\t%s ",  family == AF_INET ? "IPv4":"IPv6");
                    memset(buf, 0, BUFSIZ);
                    getnameinfo(ua->Address.lpSockaddr, ua->Address.iSockaddrLength, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
                    info_IP info;
                    info.type = family == AF_INET ? IP4 : IP6;
                    info.name = std::string(buf);
                    info.dev = std::string(aa->AdapterName);

                    // Currently not supported interfaces that not support multicast.
                    if(aa->Flags & 0x0010)
                        continue;

                    if (info.type == IP4)
                    {
                        parseIP4(info);
                    }
                    else if (info.type == IP6)
                    {
                        parseIP6(info);
                    }

                    if(return_loopback || (info.type != IP6_LOCAL && info.type != IP4_LOCAL))
                    {
                        vec_name->push_back(info);
                    }
                    //printf("Buffer: %s\n", buf);
                }
            }
        }
    }

    free(adapter_addresses);
    return true;
}

#else

bool IPFinder::getIPs(std::vector<info_IP>* vec_name, bool return_loopback)
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    // TODO arm64 doesn't seem to support getifaddrs
    if (getifaddrs(&ifaddr) == -1) {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == NULL || (ifa->ifa_flags & IFF_RUNNING) == 0)
            continue;

        family = ifa->ifa_addr->sa_family;

        if (family == AF_INET)
        {
            s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
                    host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            if (s != 0) {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                freeifaddrs(ifaddr);
                exit(EXIT_FAILURE);
            }
            info_IP info;
            info.type = IP4;
            info.name = std::string(host);
            info.dev = std::string(ifa->ifa_name);
            parseIP4(info);

            if (return_loopback || info.type != IP4_LOCAL)
                vec_name->push_back(info);
        }
        else if(family == AF_INET6)
        {
            s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6),
                    host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            if (s != 0) {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                freeifaddrs(ifaddr);
                exit(EXIT_FAILURE);
            }
            info_IP info;
            info.type = IP6;
            info.name = std::string(host);
            info.dev = std::string(ifa->ifa_name);
            if(parseIP6(info))
            {
                if (return_loopback || info.type != IP6_LOCAL)
                    vec_name->push_back(info);
            }
            //printf("<Interface>: %s \t <Address> %s\n", ifa->ifa_name, host);
        }
    }

    freeifaddrs(ifaddr);
    return true;
}
#endif

bool IPFinder::getIP4Address(LocatorList_t* locators)
{
    std::vector<info_IP> ip_names;
    if(IPFinder::getIPs(&ip_names))
    {

        locators->clear();
        for(auto it=ip_names.begin();
                it!=ip_names.end();++it)
        {
            if (it->type == IP4)
            {
                locators->push_back(it->locator);
            }
        }
        return true;
    }
    return false;
}

bool IPFinder::getAllIPAddress(LocatorList_t* locators)
{
    std::vector<info_IP> ip_names;
    if (IPFinder::getIPs(&ip_names))
    {
        locators->clear();
        for (auto it = ip_names.begin();
                it != ip_names.end(); ++it)
        {
            if (it->type == IP6)
            {
                locators->push_back(it->locator);
            }
            else if (it->type == IP4)
            {
                locators->push_back(it->locator);
            }
        }
        return true;
    }
    return false;
}

bool IPFinder::getIP6Address(LocatorList_t* locators)
{
    std::vector<info_IP> ip_names;
    if (IPFinder::getIPs(&ip_names))
    {

        locators->clear();
        for (auto it = ip_names.begin();
                it != ip_names.end(); ++it)
        {
            if (it->type == IP6)
            {
                locators->push_back(it->locator);
            }
        }
        return true;
    }
    return false;
}

bool IPFinder::parseIP4(info_IP& info)
{
    info.locator.kind = 1;
    info.locator.port = 0;
    IPLocator::setIPv4(info.locator, info.name);
    if (IPLocator::isLocal(info.locator))
    {
        info.type = IP4_LOCAL;
    }
    return true;
}
bool IPFinder::parseIP6(info_IP& info)
{
    info.locator.kind = LOCATOR_KIND_UDPv6;
    info.locator.port = 0;
    IPLocator::setIPv6(info.locator, info.name);
    if (IPLocator::isLocal(info.locator))
    {
        info.type = IP6_LOCAL;
    }
    /*
       cout << "IPSTRING: ";
       for (auto it : hexdigits)
       cout << it << " ";
       cout << endl;
       cout << "LOCATOR: " << *loc << endl;
       */
    return true;
}

std::string IPFinder::getIPv4Address(const std::string &name)
{
    addrinfo hints;
    addrinfo *result;
    char str[INET_ADDRSTRLEN];

    memset(&hints, 0, sizeof(addrinfo));
    hints.ai_addr = nullptr;
    hints.ai_family = AF_INET;
    hints.ai_socktype = 0;
    hints.ai_flags = AI_PASSIVE;
    hints.ai_protocol = 0;
    hints.ai_canonname = nullptr;
    hints.ai_next = nullptr;

    int s = getaddrinfo(name.c_str(), nullptr, &hints, &result);

    if ( (s == 0) && (inet_ntop(AF_INET, result[0].ai_addr, str, INET_ADDRSTRLEN) != nullptr) )
    {
        freeaddrinfo(result);
        return str;
    }

    freeaddrinfo(result);
    return "";
}

std::string IPFinder::getIPv6Address(const std::string &name)
{
    addrinfo hints;
    addrinfo *result;
    char str[INET6_ADDRSTRLEN];

    memset(&hints, 0, sizeof(addrinfo));
    hints.ai_addr = nullptr;
    hints.ai_family = AF_INET6;
    hints.ai_socktype = 0;
    hints.ai_flags = AI_PASSIVE;
    hints.ai_protocol = 0;
    hints.ai_canonname = nullptr;
    hints.ai_next = nullptr;

    int s = getaddrinfo(name.c_str(), nullptr, &hints, &result);

    if ( (s == 0) && (inet_ntop(AF_INET6, result[0].ai_addr, str, INET6_ADDRSTRLEN) != nullptr) )
    {
        freeaddrinfo(result);
        return str;
    }

    freeaddrinfo(result);
    return "";
}<commit_msg>add freebsd support (#1143)<commit_after>// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.

/**
 * @file IPFinder.cpp
 *
 */

#include <fastrtps/utils/IPFinder.h>
#include <fastrtps/utils/IPLocator.h>

#if defined(_WIN32)
#pragma comment(lib, "Iphlpapi.lib")
#include <stdio.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <ws2tcpip.h>
#include <assert.h>
#else
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <net/if.h>
#endif

#if defined(__FreeBSD__)
#include <netinet/in.h>
#endif

#include <cstddef>
#include <cstring>

using namespace eprosima::fastrtps::rtps;

IPFinder::IPFinder() {
}

IPFinder::~IPFinder() {
}

#if defined(_WIN32)

#define DEFAULT_ADAPTER_ADDRESSES_SIZE 15360

bool IPFinder::getIPs(std::vector<info_IP>* vec_name, bool return_loopback)
{
    DWORD rv, size = DEFAULT_ADAPTER_ADDRESSES_SIZE;
    PIP_ADAPTER_ADDRESSES adapter_addresses, aa;
    PIP_ADAPTER_UNICAST_ADDRESS ua;

    adapter_addresses = (PIP_ADAPTER_ADDRESSES)malloc(DEFAULT_ADAPTER_ADDRESSES_SIZE);

    rv = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, adapter_addresses, &size);

    if (rv != ERROR_SUCCESS)
    {
        adapter_addresses = (PIP_ADAPTER_ADDRESSES)realloc(adapter_addresses, size);

        rv = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, adapter_addresses, &size);
    }

    if (rv != ERROR_SUCCESS)
    {
        fprintf(stderr, "GetAdaptersAddresses() failed...");
        free(adapter_addresses);
        return false;
    }

    for (aa = adapter_addresses; aa != NULL; aa = aa->Next) {
        if (aa->OperStatus == 1) //is ENABLED
        {
            for (ua = aa->FirstUnicastAddress; ua != NULL; ua = ua->Next) {
                char buf[BUFSIZ];

                int family = ua->Address.lpSockaddr->sa_family;

                if (family == AF_INET || family == AF_INET6) //IP4
                {
                    //printf("\t%s ",  family == AF_INET ? "IPv4":"IPv6");
                    memset(buf, 0, BUFSIZ);
                    getnameinfo(ua->Address.lpSockaddr, ua->Address.iSockaddrLength, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
                    info_IP info;
                    info.type = family == AF_INET ? IP4 : IP6;
                    info.name = std::string(buf);
                    info.dev = std::string(aa->AdapterName);

                    // Currently not supported interfaces that not support multicast.
                    if(aa->Flags & 0x0010)
                        continue;

                    if (info.type == IP4)
                    {
                        parseIP4(info);
                    }
                    else if (info.type == IP6)
                    {
                        parseIP6(info);
                    }

                    if(return_loopback || (info.type != IP6_LOCAL && info.type != IP4_LOCAL))
                    {
                        vec_name->push_back(info);
                    }
                    //printf("Buffer: %s\n", buf);
                }
            }
        }
    }

    free(adapter_addresses);
    return true;
}

#else

bool IPFinder::getIPs(std::vector<info_IP>* vec_name, bool return_loopback)
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    // TODO arm64 doesn't seem to support getifaddrs
    if (getifaddrs(&ifaddr) == -1) {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == NULL || (ifa->ifa_flags & IFF_RUNNING) == 0)
            continue;

        family = ifa->ifa_addr->sa_family;

        if (family == AF_INET)
        {
            s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
                    host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            if (s != 0) {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                freeifaddrs(ifaddr);
                exit(EXIT_FAILURE);
            }
            info_IP info;
            info.type = IP4;
            info.name = std::string(host);
            info.dev = std::string(ifa->ifa_name);
            parseIP4(info);

            if (return_loopback || info.type != IP4_LOCAL)
                vec_name->push_back(info);
        }
        else if(family == AF_INET6)
        {
            s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6),
                    host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            if (s != 0) {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                freeifaddrs(ifaddr);
                exit(EXIT_FAILURE);
            }
            info_IP info;
            info.type = IP6;
            info.name = std::string(host);
            info.dev = std::string(ifa->ifa_name);
            if(parseIP6(info))
            {
                if (return_loopback || info.type != IP6_LOCAL)
                    vec_name->push_back(info);
            }
            //printf("<Interface>: %s \t <Address> %s\n", ifa->ifa_name, host);
        }
    }

    freeifaddrs(ifaddr);
    return true;
}
#endif

bool IPFinder::getIP4Address(LocatorList_t* locators)
{
    std::vector<info_IP> ip_names;
    if(IPFinder::getIPs(&ip_names))
    {

        locators->clear();
        for(auto it=ip_names.begin();
                it!=ip_names.end();++it)
        {
            if (it->type == IP4)
            {
                locators->push_back(it->locator);
            }
        }
        return true;
    }
    return false;
}

bool IPFinder::getAllIPAddress(LocatorList_t* locators)
{
    std::vector<info_IP> ip_names;
    if (IPFinder::getIPs(&ip_names))
    {
        locators->clear();
        for (auto it = ip_names.begin();
                it != ip_names.end(); ++it)
        {
            if (it->type == IP6)
            {
                locators->push_back(it->locator);
            }
            else if (it->type == IP4)
            {
                locators->push_back(it->locator);
            }
        }
        return true;
    }
    return false;
}

bool IPFinder::getIP6Address(LocatorList_t* locators)
{
    std::vector<info_IP> ip_names;
    if (IPFinder::getIPs(&ip_names))
    {

        locators->clear();
        for (auto it = ip_names.begin();
                it != ip_names.end(); ++it)
        {
            if (it->type == IP6)
            {
                locators->push_back(it->locator);
            }
        }
        return true;
    }
    return false;
}

bool IPFinder::parseIP4(info_IP& info)
{
    info.locator.kind = 1;
    info.locator.port = 0;
    IPLocator::setIPv4(info.locator, info.name);
    if (IPLocator::isLocal(info.locator))
    {
        info.type = IP4_LOCAL;
    }
    return true;
}
bool IPFinder::parseIP6(info_IP& info)
{
    info.locator.kind = LOCATOR_KIND_UDPv6;
    info.locator.port = 0;
    IPLocator::setIPv6(info.locator, info.name);
    if (IPLocator::isLocal(info.locator))
    {
        info.type = IP6_LOCAL;
    }
    /*
       cout << "IPSTRING: ";
       for (auto it : hexdigits)
       cout << it << " ";
       cout << endl;
       cout << "LOCATOR: " << *loc << endl;
       */
    return true;
}

std::string IPFinder::getIPv4Address(const std::string &name)
{
    addrinfo hints;
    addrinfo *result;
    char str[INET_ADDRSTRLEN];

    memset(&hints, 0, sizeof(addrinfo));
    hints.ai_addr = nullptr;
    hints.ai_family = AF_INET;
    hints.ai_socktype = 0;
    hints.ai_flags = AI_PASSIVE;
    hints.ai_protocol = 0;
    hints.ai_canonname = nullptr;
    hints.ai_next = nullptr;

    int s = getaddrinfo(name.c_str(), nullptr, &hints, &result);

    if ( (s == 0) && (inet_ntop(AF_INET, result[0].ai_addr, str, INET_ADDRSTRLEN) != nullptr) )
    {
        freeaddrinfo(result);
        return str;
    }

    freeaddrinfo(result);
    return "";
}

std::string IPFinder::getIPv6Address(const std::string &name)
{
    addrinfo hints;
    addrinfo *result;
    char str[INET6_ADDRSTRLEN];

    memset(&hints, 0, sizeof(addrinfo));
    hints.ai_addr = nullptr;
    hints.ai_family = AF_INET6;
    hints.ai_socktype = 0;
    hints.ai_flags = AI_PASSIVE;
    hints.ai_protocol = 0;
    hints.ai_canonname = nullptr;
    hints.ai_next = nullptr;

    int s = getaddrinfo(name.c_str(), nullptr, &hints, &result);

    if ( (s == 0) && (inet_ntop(AF_INET6, result[0].ai_addr, str, INET6_ADDRSTRLEN) != nullptr) )
    {
        freeaddrinfo(result);
        return str;
    }

    freeaddrinfo(result);
    return "";
}
<|endoftext|>


<commit_before>/**
 * @file nmf.cpp
 * @author Mohan Rajendran
 *
 * Implementation of NMF class to perform Non-Negative Matrix Factorization
 * on the given matrix.
 */

namespace mlpack {
namespace nmf {

/**
 * Construct the NMF object.
 */
template<typename InitializationRule,
         typename WUpdateRule,
         typename HUpdateRule>
NMF<InitializationRule, WUpdateRule, HUpdateRule>::NMF(
    const size_t maxIterations,
    const double minResidue,
    const InitializationRule initializeRule,
    const WUpdateRule wUpdate,
    const HUpdateRule hUpdate) :
    maxIterations(maxIterations),
    minResidue(minResidue),
    initializeRule(initializeRule),
    wUpdate(wUpdate),
    hUpdate(hUpdate)
{
  if (minResidue < 0.0)
  {
    Log::Warn << "NMF::NMF(): minResidue must be a positive value ("
        << minResidue << " given). Setting to the default value of 1e-10.\n";
    this->minResidue = 1e-10;
  }
}

/**
 * Apply Non-Negative Matrix Factorization to the provided matrix.
 *
 * @param V Input matrix to be factorized
 * @param W Basis matrix to be output
 * @param H Encoding matrix to output
 * @param r Rank r of the factorization
 */
template<typename InitializationRule,
         typename WUpdateRule,
         typename HUpdateRule>
void NMF<InitializationRule, WUpdateRule, HUpdateRule>::Apply(
    const arma::mat& V,
    const size_t r,
    arma::mat& W,
    arma::mat& H) const
{
  const size_t n = V.n_rows;
  const size_t m = V.n_cols;

  // Initialize W and H.
  initializeRule.Initialize(V, r, W, H);

  Log::Info << "Initialized W and H." << std::endl;

  size_t iteration = 1;
  const size_t nm = n * m;
  double residue = minResidue;
  double normOld;
  double norm;
  arma::mat WH;

  while (residue >= minResidue && iteration != maxIterations)
  {
    // Update step.
    // Update the value of W and H based on the Update Rules provided
    wUpdate.Update(V, W, H);
    hUpdate.Update(V, W, H);

    // Calculate norm of WH after each iteration.
    WH = W * H;
    norm = sqrt(accu(WH % WH) / nm);

    if (iteration != 0)
    {
      residue = fabs(normOld - norm);
      residue /= normOld;
    }

    normOld = norm;

    iteration++;
  }

  Log::Info << "NMF converged to residue of " << sqrt(residue) << " in "
      << iteration << " iterations." << std::endl;
}

}; // namespace nmf
}; // namespace mlpack
<commit_msg>Clean up warning.<commit_after>/**
 * @file nmf.cpp
 * @author Mohan Rajendran
 *
 * Implementation of NMF class to perform Non-Negative Matrix Factorization
 * on the given matrix.
 */

namespace mlpack {
namespace nmf {

/**
 * Construct the NMF object.
 */
template<typename InitializationRule,
         typename WUpdateRule,
         typename HUpdateRule>
NMF<InitializationRule, WUpdateRule, HUpdateRule>::NMF(
    const size_t maxIterations,
    const double minResidue,
    const InitializationRule initializeRule,
    const WUpdateRule wUpdate,
    const HUpdateRule hUpdate) :
    maxIterations(maxIterations),
    minResidue(minResidue),
    initializeRule(initializeRule),
    wUpdate(wUpdate),
    hUpdate(hUpdate)
{
  if (minResidue < 0.0)
  {
    Log::Warn << "NMF::NMF(): minResidue must be a positive value ("
        << minResidue << " given). Setting to the default value of 1e-10.\n";
    this->minResidue = 1e-10;
  }
}

/**
 * Apply Non-Negative Matrix Factorization to the provided matrix.
 *
 * @param V Input matrix to be factorized
 * @param W Basis matrix to be output
 * @param H Encoding matrix to output
 * @param r Rank r of the factorization
 */
template<typename InitializationRule,
         typename WUpdateRule,
         typename HUpdateRule>
void NMF<InitializationRule, WUpdateRule, HUpdateRule>::Apply(
    const arma::mat& V,
    const size_t r,
    arma::mat& W,
    arma::mat& H) const
{
  const size_t n = V.n_rows;
  const size_t m = V.n_cols;

  // Initialize W and H.
  initializeRule.Initialize(V, r, W, H);

  Log::Info << "Initialized W and H." << std::endl;

  size_t iteration = 1;
  const size_t nm = n * m;
  double residue = minResidue;
  double normOld = 0;
  double norm = 0;
  arma::mat WH;

  while (residue >= minResidue && iteration != maxIterations)
  {
    // Update step.
    // Update the value of W and H based on the Update Rules provided
    wUpdate.Update(V, W, H);
    hUpdate.Update(V, W, H);

    // Calculate norm of WH after each iteration.
    WH = W * H;
    norm = sqrt(accu(WH % WH) / nm);

    if (iteration != 0)
    {
      residue = fabs(normOld - norm);
      residue /= normOld;
    }

    normOld = norm;

    iteration++;
  }

  Log::Info << "NMF converged to residue of " << sqrt(residue) << " in "
      << iteration << " iterations." << std::endl;
}

}; // namespace nmf
}; // namespace mlpack
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS impress63 (1.40.160); FILE MERGED 2005/07/08 12:44:40 cl 1.40.160.1: #i51550# always create model with persist in CreateData()<commit_after><|endoftext|>


<commit_before>// $RCSfile: $
// $Revision: $ $Date: $
// Auth: Samson Bonfante (bonfante@steptools.com)
//
// Copyright (c) 1991-2016 by STEP Tools Inc.
//
// 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 "nodeMachineState.h"
#include "nodeUtils.h"
#include <stp_schema.h>
#include <future>

StixSimGeomType GeomTypeFromString(char* typ)
{
    if (!strcmp(typ, "MESH"))
    {
	return STIXSIM_GT_MESH;
    }
    if (!strcmp(typ, "POLYLINE"))
    {
	return STIXSIM_GT_POLYLINE;
    }
    else
    {
	return STIXSIM_GT_NULL;
    }
}

NAN_METHOD(machineState::New)
{

    if (info.IsConstructCall()){
    	if (info.Length() == 0){
    	    return;
    	}
        else if(info.Length() == 1 || (info.Length() == 2 && info[1]->BooleanValue() == false)){
        	char * b;
        	v8StringToChar(info[0], b);
        	machineState * ms = new machineState();
        	ms->_ms = MachineState::InitializeState(b);
        	delete[] b;
        	ms->Wrap(info.This());
        	info.GetReturnValue().Set(info.This());
        }
        else if(info.Length() == 2){
            char * b;
            v8StringToChar(info[0], b);
            bool c = info[1]->BooleanValue();
            machineState * ms = new machineState();
            ms->_ms = MachineState::InitializeState(b, c);
            delete[] b;
            ms->Wrap(info.This());
            info.GetReturnValue().Set(info.This());
        }
        else{
            return;
        }
    }
    else{
	   return;
    }
}

NAN_METHOD(machineState::AdvanceState)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    int rtnval = ms->_ms->AdvanceState();
    v8::Local<v8::Int32> rtn = Nan::New(rtnval);
    v8::Local<v8::Promise::Resolver> pmise = v8::Promise::Resolver::New(info.GetIsolate());
    std::async(std::launch::async, [pmise, rtn, ms]() {ms->_ms->WaitForStateUpdate(); pmise->Resolve(rtn); });
    info.GetReturnValue().Set(pmise);
}

NAN_METHOD(machineState::GetGeometryJSON)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    //This function has a 2 argument and a no argument version.
    if (info.Length() == 0)
    {
	RoseStringObject rtn;
	ms->_ms->GetGeometryJSON(rtn);
	info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
	return;
    }
    else
    {
	if (info.Length() != 2) return; // invalid number of arguments
	if (info[0]->IsUndefined()) return; //No Given ID
	if (info[1]->IsUndefined()) return; //No Given Typ
	if (!info[0]->IsString()) return; //ID is not valid
	if (!info[1]->IsString()) return; //Typ is not valid
	char * id;
	v8StringToChar(info[0], id);
	RoseObject * obj = ms->_ms->FindObjectByID(id);
	if (!obj)
	{
	    delete[] id;
	    return; //No Object Associated with given ID
	}
	char * typ;
	v8StringToChar(info[1], typ);
	RoseStringObject rtn;
	ms->_ms->GetGeometryJSON(rtn, id, obj, GeomTypeFromString(typ));
	info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
	delete[] id;
	delete[] typ;
	return;
    }
}

NAN_METHOD(machineState::GetDeltaGeometryJSON)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info.Length() != 1) //Function takes one argument
	return;
    if (!info[0]->IsNumber()) { // argument of wrong type
	return;
    }
    RoseStringObject rtn;
    ms->_ms->GetDynamicGeometryJSON(rtn,Nan::To<int32_t>(info[0]).FromJust());
    info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
    return;
}

NAN_METHOD(machineState::GetDeltaStateJSON)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    RoseStringObject rtn;
    ms->_ms->GetStateJSON(rtn,false);
    info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
    return;
}

NAN_METHOD(machineState::GetKeyStateJSON)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    RoseStringObject rtn;
    ms->_ms->GetStateJSON(rtn,true);
    info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
    return;
}

NAN_METHOD(machineState::GoToWS)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info.Length() != 1) //Function takes one argument
    return;
    RoseObject * obj = ms->_ms->design()->findByEntityId(Nan::To<int32_t>(info[0]).FromJust());
    if (!obj)
    return;
    stp_machining_workingstep * ws = ROSE_CAST(stp_machining_workingstep, obj);
    if(!ws)
    return;
    int rtnval = ms->_ms->GoToWS(ws);
    info.GetReturnValue().Set(rtnval);
    return;
}

NAN_METHOD(machineState::GetEIDfromUUID)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info.Length() != 1) //Function takes one argument
    return;
    if(!info[0]->IsString())
    return;
    char * uuid = 0;
    v8StringToChar(info[0], uuid);
    RoseObject * obj = ms->_ms->FindObjectByID(uuid);
    if (!obj)
    return;
    int rtnval = obj->entity_id();
    info.GetReturnValue().Set(Nan::New(rtnval));
    return;
}

NAN_METHOD(machineState::LoadMachine)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info[0]->IsUndefined()) return;
    char * b;
    v8StringToChar(info[0], b);
    bool success = ms->_ms->SetMachine(b);
    info.GetReturnValue().Set(success);
    delete[] b;

    return;
}

NAN_METHOD(machineState::NextWS)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    ms->_ms->GoToNextWS();
    return;
}

NAN_METHOD(machineState::PrevWS)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    ms->_ms->GoToPrevWS();
    return;
}

NAN_METHOD(machineState::GetPrevWSID)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    int id = ms->_ms->GetPrevWSID();
    info.GetReturnValue().Set(id);
    return;
}

NAN_METHOD(machineState::GetWSID)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    int id = ms->_ms->GetWSID();
    info.GetReturnValue().Set(id);
    return;
}

NAN_METHOD(machineState::GetNextWSID)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    int id = ms->_ms->GetNextWSID();
    info.GetReturnValue().Set(id);
    return;
}

NAN_METHOD(machineState::GetCurrentFeedrate)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    double feed = ms->_ms->GetCurrentFeedrate();
    info.GetReturnValue().Set(feed);
    return;
}

NAN_METHOD(machineState::GetCurrentSpindleSpeed)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    double speed = ms->_ms->GetCurrentSpindleSpeed();
    info.GetReturnValue().Set(speed);
    return;
}

NAN_METHOD(machineState::SetToolPosition)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info.Length() != 6) return;    // bad input

    double xyz[3];
    double ijk[3];

    for (int i=0; i<3; i++) {
	if (info[i]->IsUndefined()) return; // throw ex
	if (!info[i]->IsNumber()) return; // needs to be a number

	Nan::Maybe<double> num = Nan::To<double>(info[i]);

	xyz[i] = num.FromJust();
    }

    for (int i=3; i<6; i++) {
	if (info[i]->IsUndefined()) return; // bad input
	if (!info[i]->IsNumber()) return; // check for number

	Nan::Maybe<double> num = Nan::To<double>(info[i]);

	ijk[i - 3] = num.FromJust();
    }

    ms->_ms->SetToolPosition(xyz, ijk);
    v8::Local<v8::Promise::Resolver> pmise = v8::Promise::Resolver::New(info.GetIsolate());
    std::async(std::launch::async, [pmise, ms]() {ms->_ms->WaitForStateUpdate(); pmise->Resolve(Nan::Null()); });
    info.GetReturnValue().Set(pmise);
    return;
}

NAN_MODULE_INIT(machineState::Init)
{
    v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
    tpl->SetClassName(Nan::New("machineState").ToLocalChecked());
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    Nan::SetPrototypeMethod(tpl, "AdvanceState", AdvanceState);
    Nan::SetPrototypeMethod(tpl, "GetGeometryJSON", GetGeometryJSON);
    Nan::SetPrototypeMethod(tpl, "GetDeltaGeometryJSON", GetDeltaGeometryJSON);
    Nan::SetPrototypeMethod(tpl, "GetDeltaStateJSON", GetDeltaStateJSON);
    Nan::SetPrototypeMethod(tpl, "GetKeyStateJSON", GetKeyStateJSON);
    Nan::SetPrototypeMethod(tpl, "GoToWS", GoToWS);
    Nan::SetPrototypeMethod(tpl, "GetEIDfromUUID", GetEIDfromUUID);
    Nan::SetPrototypeMethod(tpl, "LoadMachine", LoadMachine);
    Nan::SetPrototypeMethod(tpl, "NextWS", NextWS);
    Nan::SetPrototypeMethod(tpl, "PrevWS", PrevWS);
    Nan::SetPrototypeMethod(tpl, "GetPrevWSID", GetPrevWSID);
    Nan::SetPrototypeMethod(tpl, "GetWSID", GetWSID);
    Nan::SetPrototypeMethod(tpl, "GetNextWSID", GetNextWSID);
    Nan::SetPrototypeMethod(tpl, "GetCurrentFeedrate", GetCurrentFeedrate);
    Nan::SetPrototypeMethod(tpl, "GetCurrentSpindleSpeed", GetCurrentSpindleSpeed);
    Nan::SetPrototypeMethod(tpl, "SetToolPosition", SetToolPosition);
    constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
    Nan::Set(target, Nan::New("machineState").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());

    MachineState::init();
}
<commit_msg>node didn't like the Null? Maybe?<commit_after>// $RCSfile: $
// $Revision: $ $Date: $
// Auth: Samson Bonfante (bonfante@steptools.com)
//
// Copyright (c) 1991-2016 by STEP Tools Inc.
//
// 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 "nodeMachineState.h"
#include "nodeUtils.h"
#include <stp_schema.h>
#include <future>

StixSimGeomType GeomTypeFromString(char* typ)
{
    if (!strcmp(typ, "MESH"))
    {
	return STIXSIM_GT_MESH;
    }
    if (!strcmp(typ, "POLYLINE"))
    {
	return STIXSIM_GT_POLYLINE;
    }
    else
    {
	return STIXSIM_GT_NULL;
    }
}

NAN_METHOD(machineState::New)
{

    if (info.IsConstructCall()){
    	if (info.Length() == 0){
    	    return;
    	}
        else if(info.Length() == 1 || (info.Length() == 2 && info[1]->BooleanValue() == false)){
        	char * b;
        	v8StringToChar(info[0], b);
        	machineState * ms = new machineState();
        	ms->_ms = MachineState::InitializeState(b);
        	delete[] b;
        	ms->Wrap(info.This());
        	info.GetReturnValue().Set(info.This());
        }
        else if(info.Length() == 2){
            char * b;
            v8StringToChar(info[0], b);
            bool c = info[1]->BooleanValue();
            machineState * ms = new machineState();
            ms->_ms = MachineState::InitializeState(b, c);
            delete[] b;
            ms->Wrap(info.This());
            info.GetReturnValue().Set(info.This());
        }
        else{
            return;
        }
    }
    else{
	   return;
    }
}

NAN_METHOD(machineState::AdvanceState)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    int rtnval = ms->_ms->AdvanceState();
    v8::Local<v8::Int32> rtn = Nan::New(rtnval);
    v8::Local<v8::Promise::Resolver> pmise = v8::Promise::Resolver::New(info.GetIsolate());
    std::async(std::launch::async, [pmise, rtn, ms]() {ms->_ms->WaitForStateUpdate(); pmise->Resolve(rtn); });
    info.GetReturnValue().Set(pmise);
}

NAN_METHOD(machineState::GetGeometryJSON)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    //This function has a 2 argument and a no argument version.
    if (info.Length() == 0)
    {
	RoseStringObject rtn;
	ms->_ms->GetGeometryJSON(rtn);
	info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
	return;
    }
    else
    {
	if (info.Length() != 2) return; // invalid number of arguments
	if (info[0]->IsUndefined()) return; //No Given ID
	if (info[1]->IsUndefined()) return; //No Given Typ
	if (!info[0]->IsString()) return; //ID is not valid
	if (!info[1]->IsString()) return; //Typ is not valid
	char * id;
	v8StringToChar(info[0], id);
	RoseObject * obj = ms->_ms->FindObjectByID(id);
	if (!obj)
	{
	    delete[] id;
	    return; //No Object Associated with given ID
	}
	char * typ;
	v8StringToChar(info[1], typ);
	RoseStringObject rtn;
	ms->_ms->GetGeometryJSON(rtn, id, obj, GeomTypeFromString(typ));
	info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
	delete[] id;
	delete[] typ;
	return;
    }
}

NAN_METHOD(machineState::GetDeltaGeometryJSON)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info.Length() != 1) //Function takes one argument
	return;
    if (!info[0]->IsNumber()) { // argument of wrong type
	return;
    }
    RoseStringObject rtn;
    ms->_ms->GetDynamicGeometryJSON(rtn,Nan::To<int32_t>(info[0]).FromJust());
    info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
    return;
}

NAN_METHOD(machineState::GetDeltaStateJSON)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    RoseStringObject rtn;
    ms->_ms->GetStateJSON(rtn,false);
    info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
    return;
}

NAN_METHOD(machineState::GetKeyStateJSON)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    RoseStringObject rtn;
    ms->_ms->GetStateJSON(rtn,true);
    info.GetReturnValue().Set(CharTov8String(rtn.as_const()));
    return;
}

NAN_METHOD(machineState::GoToWS)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info.Length() != 1) //Function takes one argument
    return;
    RoseObject * obj = ms->_ms->design()->findByEntityId(Nan::To<int32_t>(info[0]).FromJust());
    if (!obj)
    return;
    stp_machining_workingstep * ws = ROSE_CAST(stp_machining_workingstep, obj);
    if(!ws)
    return;
    int rtnval = ms->_ms->GoToWS(ws);
    info.GetReturnValue().Set(rtnval);
    return;
}

NAN_METHOD(machineState::GetEIDfromUUID)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info.Length() != 1) //Function takes one argument
    return;
    if(!info[0]->IsString())
    return;
    char * uuid = 0;
    v8StringToChar(info[0], uuid);
    RoseObject * obj = ms->_ms->FindObjectByID(uuid);
    if (!obj)
    return;
    int rtnval = obj->entity_id();
    info.GetReturnValue().Set(Nan::New(rtnval));
    return;
}

NAN_METHOD(machineState::LoadMachine)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info[0]->IsUndefined()) return;
    char * b;
    v8StringToChar(info[0], b);
    bool success = ms->_ms->SetMachine(b);
    info.GetReturnValue().Set(success);
    delete[] b;

    return;
}

NAN_METHOD(machineState::NextWS)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    ms->_ms->GoToNextWS();
    return;
}

NAN_METHOD(machineState::PrevWS)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    ms->_ms->GoToPrevWS();
    return;
}

NAN_METHOD(machineState::GetPrevWSID)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    int id = ms->_ms->GetPrevWSID();
    info.GetReturnValue().Set(id);
    return;
}

NAN_METHOD(machineState::GetWSID)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    int id = ms->_ms->GetWSID();
    info.GetReturnValue().Set(id);
    return;
}

NAN_METHOD(machineState::GetNextWSID)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    int id = ms->_ms->GetNextWSID();
    info.GetReturnValue().Set(id);
    return;
}

NAN_METHOD(machineState::GetCurrentFeedrate)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    double feed = ms->_ms->GetCurrentFeedrate();
    info.GetReturnValue().Set(feed);
    return;
}

NAN_METHOD(machineState::GetCurrentSpindleSpeed)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (!info[0]->IsUndefined()) return; //This function takes no arguments.
    double speed = ms->_ms->GetCurrentSpindleSpeed();
    info.GetReturnValue().Set(speed);
    return;
}

NAN_METHOD(machineState::SetToolPosition)
{
    machineState * ms = Nan::ObjectWrap::Unwrap<machineState>(info.This());
    if (!ms || !(ms->_ms)) return;
    if (info.Length() != 6) return;    // bad input

    double xyz[3];
    double ijk[3];

    for (int i=0; i<3; i++) {
	if (info[i]->IsUndefined()) return; // throw ex
	if (!info[i]->IsNumber()) return; // needs to be a number

	Nan::Maybe<double> num = Nan::To<double>(info[i]);

	xyz[i] = num.FromJust();
    }

    for (int i=3; i<6; i++) {
	if (info[i]->IsUndefined()) return; // bad input
	if (!info[i]->IsNumber()) return; // check for number

	Nan::Maybe<double> num = Nan::To<double>(info[i]);

	ijk[i - 3] = num.FromJust();
    }

    ms->_ms->SetToolPosition(xyz, ijk);
    v8::Local<v8::Promise::Resolver> pmise = v8::Promise::Resolver::New(info.GetIsolate());
    v8::Local<v8::Int32> rtn = Nan::New(1);
    std::async(std::launch::async, [pmise,rtn, ms]() {ms->_ms->WaitForStateUpdate(); pmise->Resolve(rtn); });
    info.GetReturnValue().Set(pmise);
    return;
}

NAN_MODULE_INIT(machineState::Init)
{
    v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
    tpl->SetClassName(Nan::New("machineState").ToLocalChecked());
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    Nan::SetPrototypeMethod(tpl, "AdvanceState", AdvanceState);
    Nan::SetPrototypeMethod(tpl, "GetGeometryJSON", GetGeometryJSON);
    Nan::SetPrototypeMethod(tpl, "GetDeltaGeometryJSON", GetDeltaGeometryJSON);
    Nan::SetPrototypeMethod(tpl, "GetDeltaStateJSON", GetDeltaStateJSON);
    Nan::SetPrototypeMethod(tpl, "GetKeyStateJSON", GetKeyStateJSON);
    Nan::SetPrototypeMethod(tpl, "GoToWS", GoToWS);
    Nan::SetPrototypeMethod(tpl, "GetEIDfromUUID", GetEIDfromUUID);
    Nan::SetPrototypeMethod(tpl, "LoadMachine", LoadMachine);
    Nan::SetPrototypeMethod(tpl, "NextWS", NextWS);
    Nan::SetPrototypeMethod(tpl, "PrevWS", PrevWS);
    Nan::SetPrototypeMethod(tpl, "GetPrevWSID", GetPrevWSID);
    Nan::SetPrototypeMethod(tpl, "GetWSID", GetWSID);
    Nan::SetPrototypeMethod(tpl, "GetNextWSID", GetNextWSID);
    Nan::SetPrototypeMethod(tpl, "GetCurrentFeedrate", GetCurrentFeedrate);
    Nan::SetPrototypeMethod(tpl, "GetCurrentSpindleSpeed", GetCurrentSpindleSpeed);
    Nan::SetPrototypeMethod(tpl, "SetToolPosition", SetToolPosition);
    constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked());
    Nan::Set(target, Nan::New("machineState").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());

    MachineState::init();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tbx_ww.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: cl $ $Date: 2002-05-28 13:02:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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 for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SD_TBX_WW_HXX
#define _SD_TBX_WW_HXX

#ifndef _SDRESID_HXX
#include <sdresid.hxx>
#endif

#ifndef _SFXTBXMGR_HXX //autogen
#include <sfx2/tbxmgr.hxx>
#endif

#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif

//------------------------------------------------------------------------

class SdPopupWindowTbx : public SfxPopupWindow
{
private:
    SfxToolBoxManager   aTbx;
    SdResId             aSdResIdWin;
    SdResId             aSdResIdTbx;
    WindowAlign         eTbxAlign;
    Link                aSelectLink;

    DECL_LINK( TbxSelectHdl, ToolBox * );

public:
    SdPopupWindowTbx( USHORT nId, WindowAlign eAlign,
                      SdResId aRIdWin, SdResId aRIdTbx, SfxBindings& rBindings );
    ~SdPopupWindowTbx();

    virtual SfxPopupWindow* Clone() const;

    virtual void PopupModeEnd();

    void         StartSelection() { aTbx.GetToolBox().StartSelection(); }
    void         Update();
};

//------------------------------------------------------------------------

class SdTbxControl : public SfxToolBoxControl
{
private:
    BOOL    IsCheckable( USHORT nSId );

public:
            SFX_DECL_TOOLBOX_CONTROL();

            SdTbxControl(USHORT nId, ToolBox& rTbx, SfxBindings& rBind );
            ~SdTbxControl() {}

    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();
    virtual void StateChanged( USHORT nSId, SfxItemState eState,
                                const SfxPoolItem* pState );
};

#endif      // _SD_TBX_WW_HXX

<commit_msg>INTEGRATION: CWS dba03 (1.2.84); FILE MERGED 2003/03/05 10:43:28 af 1.2.84.1: #107817# Added method for adapting size of text shape flyer to CTL state.<commit_after>/*************************************************************************
 *
 *  $RCSfile: tbx_ww.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-01 13:44:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library 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 for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SD_TBX_WW_HXX
#define _SD_TBX_WW_HXX

#ifndef _SDRESID_HXX
#include <sdresid.hxx>
#endif

#ifndef _SFXTBXMGR_HXX //autogen
#include <sfx2/tbxmgr.hxx>
#endif

#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif

//------------------------------------------------------------------------

class SdPopupWindowTbx : public SfxPopupWindow
{
private:
    SfxToolBoxManager   aTbx;
    SdResId             aSdResIdWin;
    SdResId             aSdResIdTbx;
    WindowAlign         eTbxAlign;
    Link                aSelectLink;

    DECL_LINK( TbxSelectHdl, ToolBox * );

public:
    SdPopupWindowTbx( USHORT nId, WindowAlign eAlign,
                      SdResId aRIdWin, SdResId aRIdTbx, SfxBindings& rBindings );
    ~SdPopupWindowTbx();

    virtual SfxPopupWindow* Clone() const;

    virtual void PopupModeEnd();

    void         StartSelection() { aTbx.GetToolBox().StartSelection(); }
    void         Update();

private:
    /** Adapt the toolbox to whether CTL is active or not.  If CTL is not
        active then all toolbox items that describe CTL specific shapes are
        deleted from it and its size is re-calculated.
    */
    void AdaptToCTL (void);
};

//------------------------------------------------------------------------

class SdTbxControl : public SfxToolBoxControl
{
private:
    BOOL    IsCheckable( USHORT nSId );

public:
            SFX_DECL_TOOLBOX_CONTROL();

            SdTbxControl(USHORT nId, ToolBox& rTbx, SfxBindings& rBind );
            ~SdTbxControl() {}

    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();
    virtual void StateChanged( USHORT nSId, SfxItemState eState,
                                const SfxPoolItem* pState );
};

#endif      // _SD_TBX_WW_HXX

<|endoftext|>


<commit_before>/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2021, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "game-state.h"
#include "models/common/externalfilelist.h"
#include "models/entity/entityromdata.h"
#include "models/lz4/lz4.h"
#include "models/rooms/rooms.h"

namespace UnTech::Scripting {

std::shared_ptr<const GameStateData>
compileGameState(const GameState& input,
                 const ExternalFileList<Rooms::RoomInput>& rooms, const Entity::EntityRomData& entityRomData,
                 ErrorList& err)
{
    bool valid = true;
    auto addError = [&](const auto... msg) {
        err.addErrorString(msg...);
        valid = false;
    };

    if (input.flags.size() > GameState::MAX_FLAGS) {
        addError("Too many flags (", input.flags.size(), ", max: ", GameState::MAX_FLAGS, ")");
    }
    if (input.words.size() > GameState::MAX_WORDS) {
        err.addErrorString("Too many words (", input.words.size(), ", max: ", GameState::MAX_WORDS, ")");
    }

    const auto roomId = rooms.indexOf(input.startingRoom);
    unsigned entranceId = INT_MAX;
    if (roomId < rooms.size()) {
        if (const auto* room = rooms.at(roomId)) {
            entranceId = room->entrances.indexOf(input.startingEntrance);
        }
    }

    if (!input.startingRoom.isValid()) {
        addError("Missing startingRoom");
    }
    else if (!input.startingEntrance.isValid()) {
        addError("Missing startingEntrance");
    }
    else if (roomId > UINT8_MAX) {
        addError("Cannot find room: ", input.startingRoom);
    }
    else if (entranceId > UINT8_MAX) {
        addError("Cannot find room entrance: ", input.startingEntrance);
    }

    const unsigned playerId = entityRomData.players.indexOf(input.startingPlayer);
    if (playerId > UINT8_MAX) {
        addError("Cannot find player: ", input.startingPlayer);
    }

    if (!valid) {
        return nullptr;
    }

    auto ret = std::make_shared<GameStateData>();

    auto processList = [&](auto& map, const auto& list, const auto typeName) {
        map.reserve(list.size());

        unsigned lastIndex = 0;

        for (unsigned i = 0; i < list.size(); i++) {
            const auto& item = list.at(i);
            if (item.name.isValid()) {
                lastIndex = i;

                const auto [it, inserted] = map.emplace(item.name, GameStateData::Value{ i, item.room });
                if (!inserted) {
                    addError("Duplicate ", typeName, " detected: ", item.name);
                }
            }
        }

        return lastIndex + 1;
    };
    ret->nFlags = processList(ret->flags, input.flags, "flag");
    ret->nWords = processList(ret->words, input.words, "word");

    {
        static_assert(2 * GameState::MAX_WORDS == 0x100);

        ret->initialGameState.resize(2 * GameState::MAX_WORDS + 3);

        auto it = ret->initialGameState.begin();

        for (const auto& w : input.words) {
            *it++ = w.initialValue & 0xff;
            *it++ = (w.initialValue >> 8) & 0xff;
        }
        assert(it < ret->initialGameState.begin() + 2 * GameState::MAX_WORDS);

        it = ret->initialGameState.begin() + 2 * GameState::MAX_WORDS;

        *it++ = roomId;
        *it++ = entranceId;
        *it++ = playerId;

        assert(it == ret->initialGameState.end());
    }

    if (!valid) {
        ret = nullptr;
    }

    return ret;
}
const int GameStateData::GAME_STATE_FORMAT_VERSION = 1;

std::vector<uint8_t> GameStateData::exportSnesData() const
{
    return lz4HcCompress(initialGameState);
}

void writeGameStateConstants(const GameState& input, const GameStateData& inputData, std::ostream& out)
{
    out << "constant Project.GameState.N_FLAGS = " << inputData.nFlags
        << "\nconstant Project.GameState.MAX_FLAGS = " << input.MAX_FLAGS
        << "\nconstant Project.GameState.N_WORDS = " << inputData.nWords
        << "\nconstant Project.GameState.MAX_WORDS = " << input.MAX_WORDS
        << "\n"
           "\n"
           "namespace Project.GameState.Words {";

    for (unsigned i = 0; i < input.words.size(); i++) {
        const auto& word = input.words.at(i);

        // Only add global words to game state constants
        if (word.name.isValid() && !word.room.isValid()) {
            out << "\n  constant " << word.name << " = GameState.wordData + " << (i * 2);
        }
    }

    out << "\n}\n\n";
}

}
<commit_msg>Fix assert error if there are too many GameState words<commit_after>/*
 * This file is part of the UnTech Editor Suite.
 * Copyright (c) 2016 - 2021, Marcus Rowe <undisbeliever@gmail.com>.
 * Distributed under The MIT License: https://opensource.org/licenses/MIT
 */

#include "game-state.h"
#include "models/common/externalfilelist.h"
#include "models/entity/entityromdata.h"
#include "models/lz4/lz4.h"
#include "models/rooms/rooms.h"

namespace UnTech::Scripting {

std::shared_ptr<const GameStateData>
compileGameState(const GameState& input,
                 const ExternalFileList<Rooms::RoomInput>& rooms, const Entity::EntityRomData& entityRomData,
                 ErrorList& err)
{
    bool valid = true;
    auto addError = [&](const auto... msg) {
        err.addErrorString(msg...);
        valid = false;
    };

    if (input.flags.size() > GameState::MAX_FLAGS) {
        addError("Too many flags (", input.flags.size(), ", max: ", GameState::MAX_FLAGS, ")");
    }
    if (input.words.size() > GameState::MAX_WORDS) {
        addError("Too many words (", input.words.size(), ", max: ", GameState::MAX_WORDS, ")");
    }

    const auto roomId = rooms.indexOf(input.startingRoom);
    unsigned entranceId = INT_MAX;
    if (roomId < rooms.size()) {
        if (const auto* room = rooms.at(roomId)) {
            entranceId = room->entrances.indexOf(input.startingEntrance);
        }
    }

    if (!input.startingRoom.isValid()) {
        addError("Missing startingRoom");
    }
    else if (!input.startingEntrance.isValid()) {
        addError("Missing startingEntrance");
    }
    else if (roomId > UINT8_MAX) {
        addError("Cannot find room: ", input.startingRoom);
    }
    else if (entranceId > UINT8_MAX) {
        addError("Cannot find room entrance: ", input.startingEntrance);
    }

    const unsigned playerId = entityRomData.players.indexOf(input.startingPlayer);
    if (playerId > UINT8_MAX) {
        addError("Cannot find player: ", input.startingPlayer);
    }

    if (!valid) {
        return nullptr;
    }

    auto ret = std::make_shared<GameStateData>();

    auto processList = [&](auto& map, const auto& list, const auto typeName) {
        map.reserve(list.size());

        unsigned lastIndex = 0;

        for (unsigned i = 0; i < list.size(); i++) {
            const auto& item = list.at(i);
            if (item.name.isValid()) {
                lastIndex = i;

                const auto [it, inserted] = map.emplace(item.name, GameStateData::Value{ i, item.room });
                if (!inserted) {
                    addError("Duplicate ", typeName, " detected: ", item.name);
                }
            }
        }

        return lastIndex + 1;
    };
    ret->nFlags = processList(ret->flags, input.flags, "flag");
    ret->nWords = processList(ret->words, input.words, "word");

    {
        static_assert(2 * GameState::MAX_WORDS == 0x100);

        ret->initialGameState.resize(2 * GameState::MAX_WORDS + 3);

        auto it = ret->initialGameState.begin();

        for (const auto& w : input.words) {
            *it++ = w.initialValue & 0xff;
            *it++ = (w.initialValue >> 8) & 0xff;
        }
        assert(it <= ret->initialGameState.begin() + 2 * GameState::MAX_WORDS);

        it = ret->initialGameState.begin() + 2 * GameState::MAX_WORDS;

        *it++ = roomId;
        *it++ = entranceId;
        *it++ = playerId;

        assert(it == ret->initialGameState.end());
    }

    if (!valid) {
        ret = nullptr;
    }

    return ret;
}
const int GameStateData::GAME_STATE_FORMAT_VERSION = 1;

std::vector<uint8_t> GameStateData::exportSnesData() const
{
    return lz4HcCompress(initialGameState);
}

void writeGameStateConstants(const GameState& input, const GameStateData& inputData, std::ostream& out)
{
    out << "constant Project.GameState.N_FLAGS = " << inputData.nFlags
        << "\nconstant Project.GameState.MAX_FLAGS = " << input.MAX_FLAGS
        << "\nconstant Project.GameState.N_WORDS = " << inputData.nWords
        << "\nconstant Project.GameState.MAX_WORDS = " << input.MAX_WORDS
        << "\n"
           "\n"
           "namespace Project.GameState.Words {";

    for (unsigned i = 0; i < input.words.size(); i++) {
        const auto& word = input.words.at(i);

        // Only add global words to game state constants
        if (word.name.isValid() && !word.room.isValid()) {
            out << "\n  constant " << word.name << " = GameState.wordData + " << (i * 2);
        }
    }

    out << "\n}\n\n";
}

}
<|endoftext|>