<commit_before>/*
 * Copyright (c) 2018, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "CellularDevice.h"
#include "CellularContext.h"
#include "CellularUtil.h"
#include "CellularLog.h"
#include "CellularTargets.h"
#include "EventQueue.h"

namespace mbed {

MBED_WEAK CellularDevice *CellularDevice::get_default_instance()
{
    return get_target_default_instance();
}

MBED_WEAK CellularDevice *CellularDevice::get_target_default_instance()
{
    return NULL;
}

CellularDevice::CellularDevice(FileHandle *fh) : _network_ref_count(0), _sms_ref_count(0),
    _info_ref_count(0), _fh(fh), _queue(5 * EVENTS_EVENT_SIZE), _state_machine(0), _nw(0), _status_cb(0)
{
    MBED_ASSERT(fh);
    set_sim_pin(NULL);
    set_plmn(NULL);
}

CellularDevice::~CellularDevice()
{
    tr_debug("CellularDevice destruct");
}

void CellularDevice::stop()
{
    MBED_ASSERT(_state_machine);
    _state_machine->stop();
}

FileHandle &CellularDevice::get_file_handle() const
{
    return *_fh;
}

events::EventQueue *CellularDevice::get_queue()
{
    return &_queue;
}

CellularContext *CellularDevice::get_context_list() const
{
    return NULL;
}

void CellularDevice::set_sim_pin(const char *sim_pin)
{
    if (sim_pin) {
        strncpy(_sim_pin, sim_pin, sizeof(_sim_pin));
        _sim_pin[sizeof(_sim_pin) - 1] = '\0';
    } else {
        memset(_sim_pin, 0, sizeof(_sim_pin));
    }
}

void CellularDevice::set_plmn(const char *plmn)
{
    if (plmn) {
        strncpy(_plmn, plmn, sizeof(_plmn));
        _plmn[sizeof(_plmn) - 1] = '\0';
    } else {
        memset(_plmn, 0, sizeof(_plmn));
    }
}

nsapi_error_t CellularDevice::set_device_ready()
{
    return start_state_machine(CellularStateMachine::STATE_DEVICE_READY);
}

nsapi_error_t CellularDevice::set_sim_ready()
{
    return start_state_machine(CellularStateMachine::STATE_SIM_PIN);
}

nsapi_error_t CellularDevice::register_to_network()
{
    return start_state_machine(CellularStateMachine::STATE_REGISTERING_NETWORK);
}

nsapi_error_t CellularDevice::attach_to_network()
{
    return start_state_machine(CellularStateMachine::STATE_ATTACHING_NETWORK);
}

nsapi_error_t CellularDevice::create_state_machine()
{
    nsapi_error_t err = NSAPI_ERROR_OK;
    if (!_state_machine) {
        _state_machine = new CellularStateMachine(*this, *get_queue());
        _state_machine->set_cellular_callback(callback(this, &CellularDevice::cellular_callback));
        err = _state_machine->start_dispatch();
        if (err) {
            tr_error("Start state machine failed.");
            delete _state_machine;
            _state_machine = NULL;
        }
    }
    return err;
}

nsapi_error_t CellularDevice::start_state_machine(CellularStateMachine::CellularState target_state)
{
    _mutex.lock();
    nsapi_error_t err = create_state_machine();
    if (err) {
        return err;
    }

    CellularStateMachine::CellularState current_state, targeted_state;

    bool is_running = _state_machine->get_current_status(current_state, targeted_state);

    if (current_state >= target_state) { // can stm be in this state but failed?
        _mutex.unlock();
        return NSAPI_ERROR_ALREADY;
    } else if (is_running && targeted_state >= target_state) {
        _mutex.unlock();
        return NSAPI_ERROR_IN_PROGRESS;
    }

    err = _state_machine->run_to_state(target_state);
    _mutex.unlock();

    return err;
}

void CellularDevice::attach(Callback<void(nsapi_event_t, intptr_t)> status_cb)
{
    _status_cb = status_cb;
}

void CellularDevice::cellular_callback(nsapi_event_t ev, intptr_t ptr)
{
    if (ev >= NSAPI_EVENT_CELLULAR_STATUS_BASE && ev <= NSAPI_EVENT_CELLULAR_STATUS_END) {
        cell_callback_data_t *ptr_data = (cell_callback_data_t *)ptr;
        tr_debug("callback: %d, err: %d, data: %d", ev, ptr_data->error, ptr_data->status_data);
        cellular_connection_status_t cell_ev = (cellular_connection_status_t)ev;
        if (cell_ev == CellularRegistrationStatusChanged && _state_machine) {
            // broadcast only network registration changes to state machine
            _state_machine->cellular_event_changed(ev, ptr);
        }

        if (cell_ev == CellularDeviceReady && ptr_data->error == NSAPI_ERROR_OK) {
            // Here we can create mux and give new filehandles as mux reserves the one what was in use.
            // if mux we would need to set new filehandle:_state_machine->set_filehandle( get fh from mux);
            _nw = open_network(_fh);
            // Attach to network so we can get update status from the network
            _nw->attach(callback(this, &CellularDevice::cellular_callback));
            if (strlen(_plmn)) {
                _state_machine->set_plmn(_plmn);
            }
        } else if (cell_ev == CellularSIMStatusChanged && ptr_data->error == NSAPI_ERROR_OK &&
                   ptr_data->status_data == SimStatePinNeeded) {
            if (strlen(_sim_pin)) {
                _state_machine->set_sim_pin(_sim_pin);
            }
        }
    } else {
        tr_debug("callback: %d, ptr: %d", ev, ptr);
        if (ev == NSAPI_EVENT_CONNECTION_STATUS_CHANGE && ptr == NSAPI_STATUS_DISCONNECTED) {
            // we have been disconnected, reset state machine so that application can start connect sequence again
            if (_state_machine) {
                _state_machine->reset();
            }
        }
    }

    // broadcast network and cellular changes to state machine and CellularContext.
    CellularContext *curr = get_context_list();
    while (curr) {
        curr->cellular_callback(ev, ptr);
        curr = curr->_next;
    }

    // forward to callback function if set by attach(...)
    if (_status_cb) {
        _status_cb(ev, ptr);
    }
}

nsapi_error_t CellularDevice::shutdown()
{
    CellularContext *curr = get_context_list();
    while (curr) {
        curr->cellular_callback(NSAPI_EVENT_CONNECTION_STATUS_CHANGE, NSAPI_STATUS_DISCONNECTED);
        curr = (CellularContext *)curr->_next;
    }
    return NSAPI_ERROR_OK;
}

} // namespace mbed
<commit_msg>Cellular: Fix CellularDevice mutex unlock<commit_after>/*
 * Copyright (c) 2018, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 "CellularDevice.h"
#include "CellularContext.h"
#include "CellularUtil.h"
#include "CellularLog.h"
#include "CellularTargets.h"
#include "EventQueue.h"

namespace mbed {

MBED_WEAK CellularDevice *CellularDevice::get_default_instance()
{
    return get_target_default_instance();
}

MBED_WEAK CellularDevice *CellularDevice::get_target_default_instance()
{
    return NULL;
}

CellularDevice::CellularDevice(FileHandle *fh) : _network_ref_count(0), _sms_ref_count(0),
    _info_ref_count(0), _fh(fh), _queue(5 * EVENTS_EVENT_SIZE), _state_machine(0), _nw(0), _status_cb(0)
{
    MBED_ASSERT(fh);
    set_sim_pin(NULL);
    set_plmn(NULL);
}

CellularDevice::~CellularDevice()
{
    tr_debug("CellularDevice destruct");
}

void CellularDevice::stop()
{
    MBED_ASSERT(_state_machine);
    _state_machine->stop();
}

FileHandle &CellularDevice::get_file_handle() const
{
    return *_fh;
}

events::EventQueue *CellularDevice::get_queue()
{
    return &_queue;
}

CellularContext *CellularDevice::get_context_list() const
{
    return NULL;
}

void CellularDevice::set_sim_pin(const char *sim_pin)
{
    if (sim_pin) {
        strncpy(_sim_pin, sim_pin, sizeof(_sim_pin));
        _sim_pin[sizeof(_sim_pin) - 1] = '\0';
    } else {
        memset(_sim_pin, 0, sizeof(_sim_pin));
    }
}

void CellularDevice::set_plmn(const char *plmn)
{
    if (plmn) {
        strncpy(_plmn, plmn, sizeof(_plmn));
        _plmn[sizeof(_plmn) - 1] = '\0';
    } else {
        memset(_plmn, 0, sizeof(_plmn));
    }
}

nsapi_error_t CellularDevice::set_device_ready()
{
    return start_state_machine(CellularStateMachine::STATE_DEVICE_READY);
}

nsapi_error_t CellularDevice::set_sim_ready()
{
    return start_state_machine(CellularStateMachine::STATE_SIM_PIN);
}

nsapi_error_t CellularDevice::register_to_network()
{
    return start_state_machine(CellularStateMachine::STATE_REGISTERING_NETWORK);
}

nsapi_error_t CellularDevice::attach_to_network()
{
    return start_state_machine(CellularStateMachine::STATE_ATTACHING_NETWORK);
}

nsapi_error_t CellularDevice::create_state_machine()
{
    nsapi_error_t err = NSAPI_ERROR_OK;
    if (!_state_machine) {
        _state_machine = new CellularStateMachine(*this, *get_queue());
        _state_machine->set_cellular_callback(callback(this, &CellularDevice::cellular_callback));
        err = _state_machine->start_dispatch();
        if (err) {
            tr_error("Start state machine failed.");
            delete _state_machine;
            _state_machine = NULL;
        }
    }
    return err;
}

nsapi_error_t CellularDevice::start_state_machine(CellularStateMachine::CellularState target_state)
{
    _mutex.lock();
    nsapi_error_t err = create_state_machine();
    if (err) {
        _mutex.unlock();
        return err;
    }

    CellularStateMachine::CellularState current_state, targeted_state;

    bool is_running = _state_machine->get_current_status(current_state, targeted_state);

    if (current_state >= target_state) { // can stm be in this state but failed?
        _mutex.unlock();
        return NSAPI_ERROR_ALREADY;
    } else if (is_running && targeted_state >= target_state) {
        _mutex.unlock();
        return NSAPI_ERROR_IN_PROGRESS;
    }

    err = _state_machine->run_to_state(target_state);
    _mutex.unlock();

    return err;
}

void CellularDevice::attach(Callback<void(nsapi_event_t, intptr_t)> status_cb)
{
    _status_cb = status_cb;
}

void CellularDevice::cellular_callback(nsapi_event_t ev, intptr_t ptr)
{
    if (ev >= NSAPI_EVENT_CELLULAR_STATUS_BASE && ev <= NSAPI_EVENT_CELLULAR_STATUS_END) {
        cell_callback_data_t *ptr_data = (cell_callback_data_t *)ptr;
        tr_debug("callback: %d, err: %d, data: %d", ev, ptr_data->error, ptr_data->status_data);
        cellular_connection_status_t cell_ev = (cellular_connection_status_t)ev;
        if (cell_ev == CellularRegistrationStatusChanged && _state_machine) {
            // broadcast only network registration changes to state machine
            _state_machine->cellular_event_changed(ev, ptr);
        }

        if (cell_ev == CellularDeviceReady && ptr_data->error == NSAPI_ERROR_OK) {
            // Here we can create mux and give new filehandles as mux reserves the one what was in use.
            // if mux we would need to set new filehandle:_state_machine->set_filehandle( get fh from mux);
            _nw = open_network(_fh);
            // Attach to network so we can get update status from the network
            _nw->attach(callback(this, &CellularDevice::cellular_callback));
            if (strlen(_plmn)) {
                _state_machine->set_plmn(_plmn);
            }
        } else if (cell_ev == CellularSIMStatusChanged && ptr_data->error == NSAPI_ERROR_OK &&
                   ptr_data->status_data == SimStatePinNeeded) {
            if (strlen(_sim_pin)) {
                _state_machine->set_sim_pin(_sim_pin);
            }
        }
    } else {
        tr_debug("callback: %d, ptr: %d", ev, ptr);
        if (ev == NSAPI_EVENT_CONNECTION_STATUS_CHANGE && ptr == NSAPI_STATUS_DISCONNECTED) {
            // we have been disconnected, reset state machine so that application can start connect sequence again
            if (_state_machine) {
                _state_machine->reset();
            }
        }
    }

    // broadcast network and cellular changes to state machine and CellularContext.
    CellularContext *curr = get_context_list();
    while (curr) {
        curr->cellular_callback(ev, ptr);
        curr = curr->_next;
    }

    // forward to callback function if set by attach(...)
    if (_status_cb) {
        _status_cb(ev, ptr);
    }
}

nsapi_error_t CellularDevice::shutdown()
{
    CellularContext *curr = get_context_list();
    while (curr) {
        curr->cellular_callback(NSAPI_EVENT_CONNECTION_STATUS_CHANGE, NSAPI_STATUS_DISCONNECTED);
        curr = (CellularContext *)curr->_next;
    }
    return NSAPI_ERROR_OK;
}

} // namespace mbed
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/fnet/frt/frt.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <thread>

using vespalib::BenchmarkTimer;

struct Rpc : FRT_Invokable {
    FastOS_ThreadPool thread_pool;
    FNET_Transport    transport;
    FRT_Supervisor    orb;
    Rpc(size_t num_threads)
        : thread_pool(128 * 1024), transport(num_threads), orb(&transport, &thread_pool) {}
    void start() {
        ASSERT_TRUE(transport.Start(&thread_pool));
    }
    uint32_t listen() {
        ASSERT_TRUE(orb.Listen(0));
        return orb.GetListenPort();
    }
    FRT_Target *connect(uint32_t port) {
        return orb.GetTarget(port);
    }
    ~Rpc() {
        transport.ShutDown(true);
        thread_pool.Close();
    }
};

struct Server : Rpc {
    uint32_t port;
    Server(size_t num_threads) : Rpc(num_threads), port(listen()) {
        init_rpc();
        start();
    }
    void init_rpc() {
        FRT_ReflectionBuilder rb(&orb);
        rb.DefineMethod("inc", "l", "l", FRT_METHOD(Server::rpc_inc), this);
        rb.MethodDesc("increment a 64-bit integer");
        rb.ParamDesc("in", "an integer (64 bit)");
        rb.ReturnDesc("out", "in + 1 (64 bit)");
    }
    void rpc_inc(FRT_RPCRequest *req) {
        FRT_Values &params = *req->GetParams();
        FRT_Values &ret    = *req->GetReturn();
        ret.AddInt64(params[0]._intval64 + 1);
    }
};

struct Client : Rpc {
    uint32_t port;
    Client(size_t num_threads, const Server &server) : Rpc(num_threads), port(server.port) {
        start();
    }
    FRT_Target *connect() { return Rpc::connect(port); }
};

struct Result {
    std::vector<double> req_per_sec;
    Result(size_t num_threads) : req_per_sec(num_threads, 0.0) {}
    double throughput() const {
        double sum = 0.0;
        for (double sample: req_per_sec) {
            sum += sample;
        }
        return sum;
    }
    double latency_ms() const {
        double avg_req_per_sec = throughput() / req_per_sec.size();
        double avg_sec_per_req = 1.0 / avg_req_per_sec;
        return avg_sec_per_req * 1000.0;
    }
    void print() const {
        fprintf(stderr, "total throughput: %f req/s\n", throughput());
        fprintf(stderr, "average latency : %f ms\n", latency_ms());
    }
};

void perform_test(size_t thread_id, Client &client, Result &result) {
    uint64_t seq = 0;
    FRT_Target *target = client.connect();
    FRT_RPCRequest *req = client.orb.AllocRPCRequest();
    auto invoke = [&seq, target, &client, &req](){
        req = client.orb.AllocRPCRequest(req);
        req->SetMethodName("inc");
        req->GetParams()->AddInt64(seq);
        target->InvokeSync(req, 60.0);
        ASSERT_TRUE(req->CheckReturnTypes("l"));
        uint64_t ret = req->GetReturn()->GetValue(0)._intval64;
        EXPECT_EQUAL(ret, seq + 1);
        seq = ret;
    };
    size_t loop_cnt = 128;
    BenchmarkTimer::benchmark(invoke, invoke, 0.5);
    BenchmarkTimer timer(1.5);
    while (timer.has_budget()) {
        timer.before();
        for (size_t i = 0; i < loop_cnt; ++i) {
            invoke();
        }
        timer.after();
    }
    double t = timer.min_time();
    BenchmarkTimer::benchmark(invoke, invoke, 0.5);
    EXPECT_GREATER_EQUAL(seq, loop_cnt);
    result.req_per_sec[thread_id] = double(loop_cnt) / t;
    req->SubRef();
    target->SubRef();
    TEST_BARRIER();
    if (thread_id == 0) {
        result.print();
    }
}

TEST_MT_FFF("parallel rpc with 1/1 transport threads and 128 user threads",
            128, Server(1), Client(1, f1), Result(num_threads)) { perform_test(thread_id, f2, f3); }

TEST_MT_FFF("parallel rpc with 8/8 transport threads and 128 user threads",
            128, Server(8), Client(8, f1), Result(num_threads)) { perform_test(thread_id, f2, f3); }

TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>run micro-benchmark with various crypto engines (null/xor/tls)<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/fnet/frt/frt.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/vespalib/net/crypto_engine.h>
#include <vespa/vespalib/net/tls/tls_crypto_engine.h>
#include <vespa/vespalib/test/make_tls_options_for_testing.h>
#include <thread>

using namespace vespalib;

struct Rpc : FRT_Invokable {
    FastOS_ThreadPool thread_pool;
    FNET_Transport    transport;
    FRT_Supervisor    orb;
    Rpc(CryptoEngine::SP crypto, size_t num_threads)
        : thread_pool(128 * 1024), transport(crypto, num_threads), orb(&transport, &thread_pool) {}
    void start() {
        ASSERT_TRUE(transport.Start(&thread_pool));
    }
    uint32_t listen() {
        ASSERT_TRUE(orb.Listen(0));
        return orb.GetListenPort();
    }
    FRT_Target *connect(uint32_t port) {
        return orb.GetTarget(port);
    }
    ~Rpc() {
        transport.ShutDown(true);
        thread_pool.Close();
    }
};

struct Server : Rpc {
    uint32_t port;
    Server(CryptoEngine::SP crypto, size_t num_threads) : Rpc(crypto, num_threads), port(listen()) {
        init_rpc();
        start();
    }
    void init_rpc() {
        FRT_ReflectionBuilder rb(&orb);
        rb.DefineMethod("inc", "l", "l", FRT_METHOD(Server::rpc_inc), this);
        rb.MethodDesc("increment a 64-bit integer");
        rb.ParamDesc("in", "an integer (64 bit)");
        rb.ReturnDesc("out", "in + 1 (64 bit)");
    }
    void rpc_inc(FRT_RPCRequest *req) {
        FRT_Values &params = *req->GetParams();
        FRT_Values &ret    = *req->GetReturn();
        ret.AddInt64(params[0]._intval64 + 1);
    }
};

struct Client : Rpc {
    uint32_t port;
    Client(CryptoEngine::SP crypto, size_t num_threads, const Server &server) : Rpc(crypto, num_threads), port(server.port) {
        start();
    }
    FRT_Target *connect() { return Rpc::connect(port); }
};

struct Result {
    std::vector<double> req_per_sec;
    Result(size_t num_threads) : req_per_sec(num_threads, 0.0) {}
    double throughput() const {
        double sum = 0.0;
        for (double sample: req_per_sec) {
            sum += sample;
        }
        return sum;
    }
    double latency_ms() const {
        double avg_req_per_sec = throughput() / req_per_sec.size();
        double avg_sec_per_req = 1.0 / avg_req_per_sec;
        return avg_sec_per_req * 1000.0;
    }
    void print() const {
        fprintf(stderr, "total throughput: %f req/s\n", throughput());
        fprintf(stderr, "average latency : %f ms\n", latency_ms());
    }
};

void perform_test(size_t thread_id, Client &client, Result &result) {
    uint64_t seq = 0;
    FRT_Target *target = client.connect();
    FRT_RPCRequest *req = client.orb.AllocRPCRequest();
    auto invoke = [&seq, target, &client, &req](){
        req = client.orb.AllocRPCRequest(req);
        req->SetMethodName("inc");
        req->GetParams()->AddInt64(seq);
        target->InvokeSync(req, 60.0);
        ASSERT_TRUE(req->CheckReturnTypes("l"));
        uint64_t ret = req->GetReturn()->GetValue(0)._intval64;
        EXPECT_EQUAL(ret, seq + 1);
        seq = ret;
    };
    size_t loop_cnt = 128;
    BenchmarkTimer::benchmark(invoke, invoke, 0.5);
    BenchmarkTimer timer(1.5);
    while (timer.has_budget()) {
        timer.before();
        for (size_t i = 0; i < loop_cnt; ++i) {
            invoke();
        }
        timer.after();
    }
    double t = timer.min_time();
    BenchmarkTimer::benchmark(invoke, invoke, 0.5);
    EXPECT_GREATER_EQUAL(seq, loop_cnt);
    result.req_per_sec[thread_id] = double(loop_cnt) / t;
    req->SubRef();
    target->SubRef();
    TEST_BARRIER();
    if (thread_id == 0) {
        result.print();
    }
}

CryptoEngine::SP null_crypto = std::make_shared<NullCryptoEngine>();
CryptoEngine::SP xor_crypto = std::make_shared<XorCryptoEngine>();
CryptoEngine::SP tls_crypto = std::make_shared<vespalib::TlsCryptoEngine>(vespalib::test::make_tls_options_for_testing());

TEST_MT_FFF("parallel rpc with 1/1 transport threads and 128 user threads (no encryption)",
            128, Server(null_crypto, 1), Client(null_crypto, 1, f1), Result(num_threads)) { perform_test(thread_id, f2, f3); }

TEST_MT_FFF("parallel rpc with 1/1 transport threads and 128 user threads (xor encryption)",
            128, Server(xor_crypto, 1), Client(xor_crypto, 1, f1), Result(num_threads)) { perform_test(thread_id, f2, f3); }

TEST_MT_FFF("parallel rpc with 1/1 transport threads and 128 user threads (tls encryption)",
            128, Server(tls_crypto, 1), Client(tls_crypto, 1, f1), Result(num_threads)) { perform_test(thread_id, f2, f3); }

TEST_MT_FFF("parallel rpc with 8/8 transport threads and 128 user threads (no encryption)",
            128, Server(null_crypto, 8), Client(null_crypto, 8, f1), Result(num_threads)) { perform_test(thread_id, f2, f3); }

TEST_MT_FFF("parallel rpc with 8/8 transport threads and 128 user threads (xor encryption)",
            128, Server(xor_crypto, 8), Client(xor_crypto, 8, f1), Result(num_threads)) { perform_test(thread_id, f2, f3); }

TEST_MT_FFF("parallel rpc with 8/8 transport threads and 128 user threads (tls encryption)",
            128, Server(tls_crypto, 8), Client(tls_crypto, 8, f1), Result(num_threads)) { perform_test(thread_id, f2, f3); }

TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>/*
 *  Copyright 2008-2009 NVIDIA Corporation
 *
 *  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 <thrust/detail/raw_buffer.h>
#include <thrust/distance.h>
#include <thrust/copy.h>

namespace thrust
{

namespace detail
{

template<typename T, typename Space>
  raw_buffer<T,Space>
    ::raw_buffer(size_type n)
      :m_begin(m_allocator.allocate(n)),
       m_end(m_begin + n)
{
} // end raw_buffer::raw_buffer()

template<typename T, typename Space>
  template<typename InputIterator>
    raw_buffer<T,Space>
      ::raw_buffer(InputIterator first, InputIterator last)
        :m_begin(m_allocator.allocate(thrust::distance(first, last))),
         m_end(m_begin + thrust::distance(first,last))
{
  thrust::copy(first, last, begin());
} // end raw_buffer::raw_buffer()

template<typename T, typename Space>
  raw_buffer<T,Space>
    ::~raw_buffer(void)
{
  m_allocator.deallocate(&*m_begin, size());
} // end raw_buffer::~raw_buffer()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::size_type raw_buffer<T,Space>
    ::size(void) const
{
  return m_end - m_begin;
} // end raw_buffer::size()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::iterator raw_buffer<T,Space>
    ::begin(void)
{
  return m_begin;
} // end raw_buffer::begin()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>
    ::begin(void) const
{
  return m_begin;
} // end raw_buffer::begin()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>
    ::cbegin(void) const
{
  return m_begin;
} // end raw_buffer::cbegin()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::iterator raw_buffer<T,Space>
    ::end(void)
{
  return m_end;
} // end raw_buffer::end()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>
    ::end(void) const
{
  return m_end;
} // end raw_buffer::end()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>
    ::cend(void) const
{
  return m_end;
} // end raw_buffer::cend()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::reference raw_buffer<T,Space>
    ::operator[](size_type n)
{
  return m_begin[n];
} // end raw_buffer::operator[]()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_reference raw_buffer<T,Space>
    ::operator[](size_type n) const
{
  return m_begin[n];
} // end raw_buffer::operator[]()

} // end detail

} // end thrust

<commit_msg>Eliminate MSVC compiler warnings in raw_buffer's constructors.<commit_after>/*
 *  Copyright 2008-2009 NVIDIA Corporation
 *
 *  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 <thrust/detail/raw_buffer.h>
#include <thrust/distance.h>
#include <thrust/copy.h>

namespace thrust
{

namespace detail
{

template<typename T, typename Space>
  raw_buffer<T,Space>
    ::raw_buffer(size_type n)
{
  m_begin = m_allocator.allocate(n);
  m_end = m_begin + n;
} // end raw_buffer::raw_buffer()

template<typename T, typename Space>
  template<typename InputIterator>
    raw_buffer<T,Space>
      ::raw_buffer(InputIterator first, InputIterator last)
{
  size_type n = thrust::distance(first,last);
  m_begin = m_allocator.allocate(n);
  m_end = m_begin + n;
  thrust::copy(first, last, begin());
} // end raw_buffer::raw_buffer()

template<typename T, typename Space>
  raw_buffer<T,Space>
    ::~raw_buffer(void)
{
  m_allocator.deallocate(&*m_begin, size());
} // end raw_buffer::~raw_buffer()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::size_type raw_buffer<T,Space>
    ::size(void) const
{
  return m_end - m_begin;
} // end raw_buffer::size()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::iterator raw_buffer<T,Space>
    ::begin(void)
{
  return m_begin;
} // end raw_buffer::begin()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>
    ::begin(void) const
{
  return m_begin;
} // end raw_buffer::begin()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>
    ::cbegin(void) const
{
  return m_begin;
} // end raw_buffer::cbegin()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::iterator raw_buffer<T,Space>
    ::end(void)
{
  return m_end;
} // end raw_buffer::end()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>
    ::end(void) const
{
  return m_end;
} // end raw_buffer::end()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_iterator raw_buffer<T,Space>
    ::cend(void) const
{
  return m_end;
} // end raw_buffer::cend()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::reference raw_buffer<T,Space>
    ::operator[](size_type n)
{
  return m_begin[n];
} // end raw_buffer::operator[]()

template<typename T, typename Space>
  typename raw_buffer<T,Space>::const_reference raw_buffer<T,Space>
    ::operator[](size_type n) const
{
  return m_begin[n];
} // end raw_buffer::operator[]()

} // end detail

} // end thrust

<|endoftext|>


<commit_before>#include "commandProcessor.h"

String floatToString(float input)
{
	int first = int(input);
	String result = String(first);

	input -= first;
	input *= 1000;

	result += "." + String(int(input));

	return result;
}

long int lastTime = 0;

CommandProcessor::CommandProcessor()
{
	// Twiddle thumbs
}

void CommandProcessor::setup(RobotArm* robotArm)
{
	this->arm = robotArm;
}

// Loop function for the CommandProcessor
// Call in the Arduino loop function
void CommandProcessor::loop()
{
	if(Serial.available() > 0)
	{
		String command = Serial.readString();

		if(command.indexOf("setJointAngle") >= 0)
		{
			this->setJointAngle(command);
		}
		else if(command.indexOf("getJointAngle") >= 0)
		{
			this->getJointAngle(command);
		}
		else if(command.indexOf("getJointLimits") >= 0)
		{
			this->getJointLimits(command);
		}
		else if(command.indexOf("getJointGains") >= 0)
		{
			this->getJointGains(command);
		}
		else if(command.indexOf("setJointGains") >= 0)
		{
			this->setJointGains(command);
		}
		else if(command.indexOf("getJointError") >= 0)
		{
			this->getJointError(command);
		}
		else if(command.indexOf("setClawState") >= 0)
		{
			this->setClawState(command);
		}
	}

	if(millis() - lastTime >= 100)
	{
		this->armStatus();
		lastTime = millis();
	}
}

void CommandProcessor::armStatus()
{
	float error0 = this->arm->getPIMotorSpeed()->getAngleError(0, this->arm->getJointAngle(0));

	float error1 = this->arm->getPIMotorSpeed()->getAngleError(1, this->arm->getJointAngle(1));

	float error2 = this->arm->getPIMotorSpeed()->getAngleError(2, this->arm->getJointAngle(2));

	float error3 = this->arm->getPIMotorSpeed()->getAngleError(3, this->arm->getJointAngle(3));

	float error4 = this->arm->getPIMotorSpeed()->getAngleError(4, this->arm->getJointAngle(4));

	Serial.println("armStatus " + floatToString(this->arm->getJointAngle(0))
	               + " " + floatToString(this->arm->getJointAngle(1)) + " "
	               + floatToString(this->arm->getJointAngle(2)) + " "
	               + floatToString(this->arm->getJointAngle(3)) + " "
	               + floatToString(this->arm->getJointAngle(4)) + " "
	               + floatToString(error0)
	               + " " + floatToString(error1)
	               + " " + floatToString(error2)
	               + " " + floatToString(error3)
	               + " " + floatToString(error4));

}

// -----------------------------------------------
// Commands --------------------------------------
// -----------------------------------------------

// Command to set a joint to a specific angle
void CommandProcessor::setJointAngle(String command)
{
	int jointNumber = command.substring(14,15).toInt();
	int angle = command.substring(16).toInt();

	this->arm->setJointAngle(jointNumber, angle);

	Serial.println("jointSetPoint " + String(jointNumber) + " " + String(angle));
}

void CommandProcessor::getJointAngle(String command)
{
	int jointNumber = command.substring(14, 15).toInt();
	int angle = this->arm->getJointAngle(jointNumber);

	Serial.println("jointAngle " + String(jointNumber) + " " + String(angle));

}

void CommandProcessor::getJointLimits(String command)
{
	int jointNumber = command.substring(15, 16).toInt();
	int min = this->arm->getJointMinimum(jointNumber);
	int max = this->arm->getJointMaximum(jointNumber);

	Serial.println("jointLimits " + String(jointNumber) + " " + String(min) + " " + String(max));
}

void CommandProcessor::getJointGains(String command)
{
	int jointNumber = command.substring(14, 15).toInt();

	float PGain = this->arm->getPIMotorSpeed()->getProportionalGain(jointNumber);
	int newPGain = int(PGain * 100.0);

	float IGain = this->arm->getPIMotorSpeed()->getIntegralGain(jointNumber);
	int newIGain = int(IGain * 100.0);

	float DGain = 0.0; //this->arm->getPIMotorSpeed()->getDerivativeGain(jointNumber);
	int newDGain = DGain * 100;

	Serial.println("jointGains " + String(jointNumber) + " " + String(newPGain / 100) + "." + String(newPGain % 100) + " " + String(newIGain / 100) + "."
		+ String(newIGain % 100) + " " + String(newDGain / 100) + "." + String(newDGain % 100));
}

void CommandProcessor::setJointGains(String command)
{
	int jointNumber = command.substring(14, 15).toInt();
	float proportionalgain = command.substring(16, 17).toInt() + float(command.substring(18, 20).toInt()) / 100;
	float integralgain = command.substring(21, 22).toInt() + float(command.substring(23, 25).toInt()) / 100;
	float derivativegain = command.substring(26, 27).toInt() + float(command.substring(28, 30).toInt()) / 100;

	this->arm->getPIMotorSpeed()->setProportionalGain(jointNumber, proportionalgain);
	this->arm->getPIMotorSpeed()->setIntegralGain(jointNumber, integralgain);
	//this->arm->getPIMotorSpeed()->setDerivativeGain(jointNumber, derivativegain);
}

void CommandProcessor::getJointError(String command)
{
	int jointNumber = command.substring(14, 15).toInt();
	float error = this->arm->getPIMotorSpeed()->getAngleError(jointNumber, this->arm->getJointAngle(jointNumber));
	int newError = error * 100;

	Serial.println("jointError " + String(jointNumber) + " " + String(newError / 100) + "." + String(abs(newError % 100)));
}

void CommandProcessor::setClawState(String command)
{
	int commandState = command.substring(13, 14).toInt();

	if(commandState == 0)
	{
		this->arm->openClaw();
	}
	else if(commandState == 2)
	{
		this->arm->closeClaw();
	}
	else
	{
		this->arm->brakeClaw();
	}
}<commit_msg>Fix bug in floatToString<commit_after>#include "commandProcessor.h"

String floatToString(float input)
{
	int first = int(input);
	String result = String(first);

	input -= first;
	input *= 1000;

	if(input < 0)
	{
		input *= -1;
	}

	result += "." + String(int(input));

	return result;
}

long int lastTime = 0;

CommandProcessor::CommandProcessor()
{
	// Twiddle thumbs
}

void CommandProcessor::setup(RobotArm* robotArm)
{
	this->arm = robotArm;
}

// Loop function for the CommandProcessor
// Call in the Arduino loop function
void CommandProcessor::loop()
{
	if(Serial.available() > 0)
	{
		String command = Serial.readString();

		if(command.indexOf("setJointAngle") >= 0)
		{
			this->setJointAngle(command);
		}
		else if(command.indexOf("getJointAngle") >= 0)
		{
			this->getJointAngle(command);
		}
		else if(command.indexOf("getJointLimits") >= 0)
		{
			this->getJointLimits(command);
		}
		else if(command.indexOf("getJointGains") >= 0)
		{
			this->getJointGains(command);
		}
		else if(command.indexOf("setJointGains") >= 0)
		{
			this->setJointGains(command);
		}
		else if(command.indexOf("getJointError") >= 0)
		{
			this->getJointError(command);
		}
		else if(command.indexOf("setClawState") >= 0)
		{
			this->setClawState(command);
		}
	}

	if(millis() - lastTime >= 100)
	{
		this->armStatus();
		lastTime = millis();
	}
}

void CommandProcessor::armStatus()
{
	float error0 = this->arm->getPIMotorSpeed()->getAngleError(0, this->arm->getJointAngle(0));
	float error1 = this->arm->getPIMotorSpeed()->getAngleError(1, this->arm->getJointAngle(1));
	float error2 = this->arm->getPIMotorSpeed()->getAngleError(2, this->arm->getJointAngle(2));
	float error3 = this->arm->getPIMotorSpeed()->getAngleError(3, this->arm->getJointAngle(3));
	float error4 = this->arm->getPIMotorSpeed()->getAngleError(4, this->arm->getJointAngle(4));

	Serial.println("armStatus " + floatToString(this->arm->getJointAngle(0))
	               + " " + floatToString(this->arm->getJointAngle(1)) + " "
	               + floatToString(this->arm->getJointAngle(2)) + " "
	               + floatToString(this->arm->getJointAngle(3)) + " "
	               + floatToString(this->arm->getJointAngle(4)) + " "
	               + floatToString(error0)
	               + " " + floatToString(error1)
	               + " " + floatToString(error2)
	               + " " + floatToString(error3)
	               + " " + floatToString(error4));

}

// -----------------------------------------------
// Commands --------------------------------------
// -----------------------------------------------

// Command to set a joint to a specific angle
void CommandProcessor::setJointAngle(String command)
{
	int jointNumber = command.substring(14,15).toInt();
	int angle = command.substring(16).toInt();

	this->arm->setJointAngle(jointNumber, angle);

	Serial.println("jointSetPoint " + String(jointNumber) + " " + String(angle));
}

void CommandProcessor::getJointAngle(String command)
{
	int jointNumber = command.substring(14, 15).toInt();
	int angle = this->arm->getJointAngle(jointNumber);

	Serial.println("jointAngle " + String(jointNumber) + " " + String(angle));

}

void CommandProcessor::getJointLimits(String command)
{
	int jointNumber = command.substring(15, 16).toInt();
	int min = this->arm->getJointMinimum(jointNumber);
	int max = this->arm->getJointMaximum(jointNumber);

	Serial.println("jointLimits " + String(jointNumber) + " " + String(min) + " " + String(max));
}

void CommandProcessor::getJointGains(String command)
{
	int jointNumber = command.substring(14, 15).toInt();

	float PGain = this->arm->getPIMotorSpeed()->getProportionalGain(jointNumber);
	int newPGain = int(PGain * 100.0);

	float IGain = this->arm->getPIMotorSpeed()->getIntegralGain(jointNumber);
	int newIGain = int(IGain * 100.0);

	float DGain = 0.0; //this->arm->getPIMotorSpeed()->getDerivativeGain(jointNumber);
	int newDGain = DGain * 100;

	Serial.println("jointGains " + String(jointNumber) + " " + String(newPGain / 100) + "." + String(newPGain % 100) + " " + String(newIGain / 100) + "."
		+ String(newIGain % 100) + " " + String(newDGain / 100) + "." + String(newDGain % 100));
}

void CommandProcessor::setJointGains(String command)
{
	int jointNumber = command.substring(14, 15).toInt();
	float proportionalgain = command.substring(16, 17).toInt() + float(command.substring(18, 20).toInt()) / 100;
	float integralgain = command.substring(21, 22).toInt() + float(command.substring(23, 25).toInt()) / 100;
	float derivativegain = command.substring(26, 27).toInt() + float(command.substring(28, 30).toInt()) / 100;

	this->arm->getPIMotorSpeed()->setProportionalGain(jointNumber, proportionalgain);
	this->arm->getPIMotorSpeed()->setIntegralGain(jointNumber, integralgain);
	//this->arm->getPIMotorSpeed()->setDerivativeGain(jointNumber, derivativegain);
}

void CommandProcessor::getJointError(String command)
{
	int jointNumber = command.substring(14, 15).toInt();
	float error = this->arm->getPIMotorSpeed()->getAngleError(jointNumber, this->arm->getJointAngle(jointNumber));
	int newError = error * 100;

	Serial.println("jointError " + String(jointNumber) + " " + String(newError / 100) + "." + String(abs(newError % 100)));
}

void CommandProcessor::setClawState(String command)
{
	int commandState = command.substring(13, 14).toInt();

	if(commandState == 0)
	{
		this->arm->openClaw();
	}
	else if(commandState == 2)
	{
		this->arm->closeClaw();
	}
	else
	{
		this->arm->brakeClaw();
	}
}<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org.  If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/

#include "precompiled_shell.hxx"
#include "sal/config.h"

#include "QFont"
#include "QString"
#include "kemailsettings.h"
#include "kglobalsettings.h"
#include "kprotocolmanager.h"

#include "com/sun/star/uno/Any.hxx"
#include "cppu/unotype.hxx"
#include "osl/diagnose.h"
#include "osl/file.h"
#include "rtl/string.h"
#include "rtl/ustring.hxx"

#include "kde4access.hxx"

#define SPACE      ' '
#define COMMA      ','
#define SEMI_COLON ';'

namespace kde4access {

namespace {

namespace css = com::sun::star ;
namespace uno = css::uno ;

}

css::beans::Optional< css::uno::Any > getValue(rtl::OUString const & id) {
    if (id.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ExternalMailer"))) {
        KEMailSettings aEmailSettings;
        QString aClientProgram;
        ::rtl::OUString sClientProgram;

        aClientProgram = aEmailSettings.getSetting( KEMailSettings::ClientProgram );
        if ( aClientProgram.isEmpty() )
            aClientProgram = "kmail";
        else
            aClientProgram = aClientProgram.section(SPACE, 0, 0);
        sClientProgram = (const sal_Unicode *) aClientProgram.utf16();
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( sClientProgram ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("SourceViewFontHeight")))
    {
        QFont aFixedFont;
        short nFontHeight;

        aFixedFont = KGlobalSettings::fixedFont();
        nFontHeight = aFixedFont.pointSize();
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( nFontHeight ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("SourceViewFontName")))
    {
        QFont aFixedFont;
        QString aFontName;
        :: rtl::OUString sFontName;

        aFixedFont = KGlobalSettings::fixedFont();
        aFontName = aFixedFont.family();
        sFontName = (const sal_Unicode *) aFontName.utf16();
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( sFontName ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("EnableATToolSupport")))
    {
        /* does not make much sense without an accessibility bridge */
        sal_Bool ATToolSupport = sal_False;
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( rtl::OUString::valueOf( ATToolSupport ) ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("WorkPathVariable")))
    {
        QString aDocumentsDir( KGlobalSettings::documentPath() );
        rtl::OUString sDocumentsDir;
        rtl::OUString sDocumentsURL;
        if ( aDocumentsDir.endsWith(QChar('/')) )
            aDocumentsDir.truncate ( aDocumentsDir.length() - 1 );
        sDocumentsDir = (const sal_Unicode *) aDocumentsDir.utf16();
        osl_getFileURLFromSystemPath( sDocumentsDir.pData, &sDocumentsURL.pData );
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( sDocumentsURL ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetFTPProxyName")))
    {
        QString aFTPProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aFTPProxy = KProtocolManager::proxyFor( "FTP" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aFTPProxy = KProtocolManager::proxyForUrl( KUrl("ftp://ftp.openoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aFTPProxy.isEmpty() )
        {
            KUrl aProxy(aFTPProxy);
            ::rtl::OUString sProxy = (const sal_Unicode *) aProxy.host().utf16();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( sProxy ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetFTPProxyPort")))
    {
        QString aFTPProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aFTPProxy = KProtocolManager::proxyFor( "FTP" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aFTPProxy = KProtocolManager::proxyForUrl( KUrl("ftp://ftp.openoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aFTPProxy.isEmpty() )
        {
            KUrl aProxy(aFTPProxy);
            sal_Int32 nPort = aProxy.port();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( nPort ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetHTTPProxyName")))
    {
        QString aHTTPProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aHTTPProxy = KProtocolManager::proxyFor( "HTTP" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aHTTPProxy = KProtocolManager::proxyForUrl( KUrl("http://http.openoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aHTTPProxy.isEmpty() )
        {
            KUrl aProxy(aHTTPProxy);
            ::rtl::OUString sProxy = (const sal_Unicode *) aProxy.host().utf16();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( sProxy ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetHTTPProxyPort")))
    {
        QString aHTTPProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aHTTPProxy = KProtocolManager::proxyFor( "HTTP" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aHTTPProxy = KProtocolManager::proxyForUrl( KUrl("http://http.openoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aHTTPProxy.isEmpty() )
        {
            KUrl aProxy(aHTTPProxy);
            sal_Int32 nPort = aProxy.port();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( nPort ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetHTTPSProxyName")))
    {
        QString aHTTPSProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aHTTPSProxy = KProtocolManager::proxyFor( "HTTPS" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aHTTPSProxy = KProtocolManager::proxyForUrl( KUrl("https://https.openoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aHTTPSProxy.isEmpty() )
        {
            KUrl aProxy(aHTTPSProxy);
            ::rtl::OUString sProxy = (const sal_Unicode *) aProxy.host().utf16();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( sProxy ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetHTTPSProxyPort")))
    {
        QString aHTTPSProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aHTTPSProxy = KProtocolManager::proxyFor( "HTTPS" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aHTTPSProxy = KProtocolManager::proxyForUrl( KUrl("https://https.openoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aHTTPSProxy.isEmpty() )
        {
            KUrl aProxy(aHTTPSProxy);
            sal_Int32 nPort = aProxy.port();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( nPort ) );
        }
    } else if (id.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ooInetNoProxy"))) {
        QString aNoProxyFor;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
            aNoProxyFor = KProtocolManager::noProxyFor();
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aNoProxyFor.isEmpty() )
        {
            ::rtl::OUString sNoProxyFor;

            aNoProxyFor = aNoProxyFor.replace( COMMA, SEMI_COLON );
            sNoProxyFor = (const sal_Unicode *) aNoProxyFor.utf16();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( sNoProxyFor ) );
        }
    } else if (id.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ooInetProxyType"))) {
        int nProxyType;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
            nProxyType = 1;
            break;
        default:                            // No proxy is used
            nProxyType = 0;
        }
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( (sal_Int32) nProxyType ) );
    } else {
        OSL_ASSERT(false); // this cannot happen
    }
    return css::beans::Optional< css::uno::Any >();
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Changing a few more strings to read "LibreOffice"<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org.  If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/

#include "precompiled_shell.hxx"
#include "sal/config.h"

#include "QFont"
#include "QString"
#include "kemailsettings.h"
#include "kglobalsettings.h"
#include "kprotocolmanager.h"

#include "com/sun/star/uno/Any.hxx"
#include "cppu/unotype.hxx"
#include "osl/diagnose.h"
#include "osl/file.h"
#include "rtl/string.h"
#include "rtl/ustring.hxx"

#include "kde4access.hxx"

#define SPACE      ' '
#define COMMA      ','
#define SEMI_COLON ';'

namespace kde4access {

namespace {

namespace css = com::sun::star ;
namespace uno = css::uno ;

}

css::beans::Optional< css::uno::Any > getValue(rtl::OUString const & id) {
    if (id.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ExternalMailer"))) {
        KEMailSettings aEmailSettings;
        QString aClientProgram;
        ::rtl::OUString sClientProgram;

        aClientProgram = aEmailSettings.getSetting( KEMailSettings::ClientProgram );
        if ( aClientProgram.isEmpty() )
            aClientProgram = "kmail";
        else
            aClientProgram = aClientProgram.section(SPACE, 0, 0);
        sClientProgram = (const sal_Unicode *) aClientProgram.utf16();
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( sClientProgram ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("SourceViewFontHeight")))
    {
        QFont aFixedFont;
        short nFontHeight;

        aFixedFont = KGlobalSettings::fixedFont();
        nFontHeight = aFixedFont.pointSize();
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( nFontHeight ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("SourceViewFontName")))
    {
        QFont aFixedFont;
        QString aFontName;
        :: rtl::OUString sFontName;

        aFixedFont = KGlobalSettings::fixedFont();
        aFontName = aFixedFont.family();
        sFontName = (const sal_Unicode *) aFontName.utf16();
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( sFontName ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("EnableATToolSupport")))
    {
        /* does not make much sense without an accessibility bridge */
        sal_Bool ATToolSupport = sal_False;
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( rtl::OUString::valueOf( ATToolSupport ) ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("WorkPathVariable")))
    {
        QString aDocumentsDir( KGlobalSettings::documentPath() );
        rtl::OUString sDocumentsDir;
        rtl::OUString sDocumentsURL;
        if ( aDocumentsDir.endsWith(QChar('/')) )
            aDocumentsDir.truncate ( aDocumentsDir.length() - 1 );
        sDocumentsDir = (const sal_Unicode *) aDocumentsDir.utf16();
        osl_getFileURLFromSystemPath( sDocumentsDir.pData, &sDocumentsURL.pData );
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( sDocumentsURL ) );
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetFTPProxyName")))
    {
        QString aFTPProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aFTPProxy = KProtocolManager::proxyFor( "FTP" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aFTPProxy = KProtocolManager::proxyForUrl( KUrl("ftp://ftp.libreoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aFTPProxy.isEmpty() )
        {
            KUrl aProxy(aFTPProxy);
            ::rtl::OUString sProxy = (const sal_Unicode *) aProxy.host().utf16();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( sProxy ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetFTPProxyPort")))
    {
        QString aFTPProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aFTPProxy = KProtocolManager::proxyFor( "FTP" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aFTPProxy = KProtocolManager::proxyForUrl( KUrl("ftp://ftp.libreoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aFTPProxy.isEmpty() )
        {
            KUrl aProxy(aFTPProxy);
            sal_Int32 nPort = aProxy.port();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( nPort ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetHTTPProxyName")))
    {
        QString aHTTPProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aHTTPProxy = KProtocolManager::proxyFor( "HTTP" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aHTTPProxy = KProtocolManager::proxyForUrl( KUrl("http://http.libreoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aHTTPProxy.isEmpty() )
        {
            KUrl aProxy(aHTTPProxy);
            ::rtl::OUString sProxy = (const sal_Unicode *) aProxy.host().utf16();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( sProxy ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetHTTPProxyPort")))
    {
        QString aHTTPProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aHTTPProxy = KProtocolManager::proxyFor( "HTTP" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aHTTPProxy = KProtocolManager::proxyForUrl( KUrl("http://http.libreoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aHTTPProxy.isEmpty() )
        {
            KUrl aProxy(aHTTPProxy);
            sal_Int32 nPort = aProxy.port();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( nPort ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetHTTPSProxyName")))
    {
        QString aHTTPSProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aHTTPSProxy = KProtocolManager::proxyFor( "HTTPS" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aHTTPSProxy = KProtocolManager::proxyForUrl( KUrl("https://https.libreoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aHTTPSProxy.isEmpty() )
        {
            KUrl aProxy(aHTTPSProxy);
            ::rtl::OUString sProxy = (const sal_Unicode *) aProxy.host().utf16();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( sProxy ) );
        }
    } else if (id.equalsAsciiL(
                   RTL_CONSTASCII_STRINGPARAM("ooInetHTTPSProxyPort")))
    {
        QString aHTTPSProxy;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
            aHTTPSProxy = KProtocolManager::proxyFor( "HTTPS" );
            break;
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
// In such cases, the proxy address is not stored in KDE, but determined dynamically.
// The proxy address may depend on the requested address, on the time of the day, on the speed of the wind...
// The best we can do here is to ask the current value for a given address.
            aHTTPSProxy = KProtocolManager::proxyForUrl( KUrl("https://https.libreoffice.org") );
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aHTTPSProxy.isEmpty() )
        {
            KUrl aProxy(aHTTPSProxy);
            sal_Int32 nPort = aProxy.port();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( nPort ) );
        }
    } else if (id.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ooInetNoProxy"))) {
        QString aNoProxyFor;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
            aNoProxyFor = KProtocolManager::noProxyFor();
            break;
        default:                            // No proxy is used
            break;
        }
        if ( !aNoProxyFor.isEmpty() )
        {
            ::rtl::OUString sNoProxyFor;

            aNoProxyFor = aNoProxyFor.replace( COMMA, SEMI_COLON );
            sNoProxyFor = (const sal_Unicode *) aNoProxyFor.utf16();
            return css::beans::Optional< css::uno::Any >(
                true, uno::makeAny( sNoProxyFor ) );
        }
    } else if (id.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("ooInetProxyType"))) {
        int nProxyType;
        switch ( KProtocolManager::proxyType() )
        {
        case KProtocolManager::ManualProxy: // Proxies are manually configured
        case KProtocolManager::PACProxy:    // A proxy configuration URL has been given
        case KProtocolManager::WPADProxy:   // A proxy should be automatically discovered
        case KProtocolManager::EnvVarProxy: // Use the proxy values set through environment variables
            nProxyType = 1;
            break;
        default:                            // No proxy is used
            nProxyType = 0;
        }
        return css::beans::Optional< css::uno::Any >(
            true, uno::makeAny( (sal_Int32) nProxyType ) );
    } else {
        OSL_ASSERT(false); // this cannot happen
    }
    return css::beans::Optional< css::uno::Any >();
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include <google/protobuf/message.h>

#include "MockSocket.h" //To mock out the communication with the front-end.
#include "ArcusCommunicationTest.h"
#include "../src/FffProcessor.h"
#include "../src/communication/ArcusCommunicationPrivate.h" //To access the private fields of this communication class.
#include "../src/settings/types/LayerIndex.h"

namespace cura
{
    CPPUNIT_TEST_SUITE_REGISTRATION(ArcusCommunicationTest);

    void ArcusCommunicationTest::setUp()
    {
        ip = "0.0.0.0";
        port = 12345;
        socket = new MockSocket();
        ac = new ArcusCommunication();
        ac->setSocketMock(socket);

        // from: PolygonConnectorTest
        test_square.emplace_back(0, 0);
        test_square.emplace_back(1000, 0);
        test_square.emplace_back(1000, 1000);
        test_square.emplace_back(0, 1000);
        test_shapes.add(test_square);

        test_square2.emplace_back(1100, 1500);
        test_square2.emplace_back(2000, 1500);
        test_square2.emplace_back(2000, -500);
        test_square2.emplace_back(1100, -500);
        test_shapes.add(test_square2);

        test_triangle.emplace_back(0, 2100);
        test_triangle.emplace_back(500, 1100);
        test_triangle.emplace_back(1500, 2100);
        test_shapes.add(test_triangle);

        for (double a = 0; a < 1.0; a += .05)
        {
            test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * M_PI)*500, std::sin(a * 2 * M_PI)*500));
        }
        test_shapes.add(test_circle);

        test_convex_shape.emplace_back(-300, 0);
        test_convex_shape.emplace_back(-100, 500);
        test_convex_shape.emplace_back(-100, 600);
        test_convex_shape.emplace_back(-200, 1000);
        test_convex_shape.emplace_back(-500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1600, 1100);
        test_convex_shape.emplace_back(-700, 200);
        test_shapes.add(test_convex_shape);
    }

    void ArcusCommunicationTest::tearDown()
    {
        delete ac;
        ac = nullptr;
    }

    void ArcusCommunicationTest::flushGCodeTest()
    {
        //Before there is g-code, no messages should be sent if we were to flush.
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.empty());

        //Input some 'g-code' to flush.
        const std::string test_gcode = "This Fibonacci joke is as bad as the last two you heard combined.\n"
                                       "It's pretty cool how the Chinese made a language entirely out of tattoos."; //Multi-line to see flushing behaviour.
        ac->private_data->gcode_output_stream.write(test_gcode.c_str(), test_gcode.size());

        //Call the function we're testing. This time it should give us a message.
        ac->flushGCode();

        CPPUNIT_ASSERT_EQUAL(size_t(1), socket->sent_messages.size());
        const proto::GCodeLayer* message = dynamic_cast<proto::GCodeLayer*>(socket->sent_messages.front().get());
        CPPUNIT_ASSERT_EQUAL(test_gcode, message->data());
    }

    void ArcusCommunicationTest::isSequentialTest()
    {
        CPPUNIT_ASSERT(!ac->isSequential());
    }

    void ArcusCommunicationTest::hasSliceTest()
    {
        CPPUNIT_ASSERT(ac->hasSlice());
        ac->private_data->slice_count = 1;
        CPPUNIT_ASSERT_MESSAGE("Can't slice more than once.", !ac->hasSlice());
    }

    void ArcusCommunicationTest::sendGCodePrefixTest()
    {
        const std::string& prefix = "bladibla";

        ac->sendGCodePrefix(prefix);
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
        bool found_prefix = false;
        for (auto message : socket->sent_messages)
        {
            if (message->DebugString().find(prefix) != std::string::npos)
            {
                found_prefix = true;
                break;
            }
        }
        CPPUNIT_ASSERT(found_prefix);
    }

    void ArcusCommunicationTest::sendFinishedSlicingTest()
    {
        ac->sendFinishedSlicing();
        CPPUNIT_ASSERT_EQUAL(size_t(1), socket->sent_messages.size());
    }

    void ArcusCommunicationTest::sendLayerCompleteTest()
    {
        const LayerIndex layer_nr = 10;
        constexpr coord_t layer_z = 20;
        constexpr coord_t layer_thickness = 30;
        ac->sendLayerComplete(layer_nr, layer_z, layer_thickness);
        const std::shared_ptr<proto::LayerOptimized> message = ac->private_data->getOptimizedLayerById(layer_nr);
        CPPUNIT_ASSERT_EQUAL_MESSAGE("getOptimizedLayerById() must return a layer with the correct ID.",
                                     static_cast<google::protobuf::int32>(layer_nr), message->id());
        CPPUNIT_ASSERT_EQUAL(static_cast<float>(layer_z), message->height());
        CPPUNIT_ASSERT_EQUAL(static_cast<float>(layer_thickness), message->thickness());
    }

    void ArcusCommunicationTest::sendProgressTest()
    {
        ac->sendProgress(10);;
        ac->sendProgress(50);
    }

    void ArcusCommunicationTest::setLayerForSendTest()
    {
        ac->setLayerForSend(42);
    }

    void ArcusCommunicationTest::setExtruderForSendTest()
    {

    }

    void ArcusCommunicationTest::sliceNextTest()
    {
        ac->sliceNext();
    }
}

<commit_msg>Fix test for sending progress<commit_after>//Copyright (c) 2018 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.

#include <google/protobuf/message.h>

#include "MockSocket.h" //To mock out the communication with the front-end.
#include "ArcusCommunicationTest.h"
#include "../src/FffProcessor.h"
#include "../src/communication/ArcusCommunicationPrivate.h" //To access the private fields of this communication class.
#include "../src/settings/types/LayerIndex.h"

namespace cura
{
    CPPUNIT_TEST_SUITE_REGISTRATION(ArcusCommunicationTest);

    void ArcusCommunicationTest::setUp()
    {
        ip = "0.0.0.0";
        port = 12345;
        socket = new MockSocket();
        ac = new ArcusCommunication();
        ac->setSocketMock(socket);

        // from: PolygonConnectorTest
        test_square.emplace_back(0, 0);
        test_square.emplace_back(1000, 0);
        test_square.emplace_back(1000, 1000);
        test_square.emplace_back(0, 1000);
        test_shapes.add(test_square);

        test_square2.emplace_back(1100, 1500);
        test_square2.emplace_back(2000, 1500);
        test_square2.emplace_back(2000, -500);
        test_square2.emplace_back(1100, -500);
        test_shapes.add(test_square2);

        test_triangle.emplace_back(0, 2100);
        test_triangle.emplace_back(500, 1100);
        test_triangle.emplace_back(1500, 2100);
        test_shapes.add(test_triangle);

        for (double a = 0; a < 1.0; a += .05)
        {
            test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * M_PI)*500, std::sin(a * 2 * M_PI)*500));
        }
        test_shapes.add(test_circle);

        test_convex_shape.emplace_back(-300, 0);
        test_convex_shape.emplace_back(-100, 500);
        test_convex_shape.emplace_back(-100, 600);
        test_convex_shape.emplace_back(-200, 1000);
        test_convex_shape.emplace_back(-500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1500, 1500);
        test_convex_shape.emplace_back(-1600, 1100);
        test_convex_shape.emplace_back(-700, 200);
        test_shapes.add(test_convex_shape);
    }

    void ArcusCommunicationTest::tearDown()
    {
        delete ac;
        ac = nullptr;
    }

    void ArcusCommunicationTest::flushGCodeTest()
    {
        //Before there is g-code, no messages should be sent if we were to flush.
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.empty());

        //Input some 'g-code' to flush.
        const std::string test_gcode = "This Fibonacci joke is as bad as the last two you heard combined.\n"
                                       "It's pretty cool how the Chinese made a language entirely out of tattoos."; //Multi-line to see flushing behaviour.
        ac->private_data->gcode_output_stream.write(test_gcode.c_str(), test_gcode.size());

        //Call the function we're testing. This time it should give us a message.
        ac->flushGCode();

        CPPUNIT_ASSERT_EQUAL(size_t(1), socket->sent_messages.size());
        const proto::GCodeLayer* message = dynamic_cast<proto::GCodeLayer*>(socket->sent_messages.back().get());
        CPPUNIT_ASSERT_EQUAL(test_gcode, message->data());
    }

    void ArcusCommunicationTest::isSequentialTest()
    {
        CPPUNIT_ASSERT(!ac->isSequential());
    }

    void ArcusCommunicationTest::hasSliceTest()
    {
        CPPUNIT_ASSERT(ac->hasSlice());
        ac->private_data->slice_count = 1;
        CPPUNIT_ASSERT_MESSAGE("Can't slice more than once.", !ac->hasSlice());
    }

    void ArcusCommunicationTest::sendGCodePrefixTest()
    {
        const std::string& prefix = "bladibla";

        ac->sendGCodePrefix(prefix);
        ac->flushGCode();
        CPPUNIT_ASSERT(socket->sent_messages.size() > 0);
        bool found_prefix = false;
        for (auto message : socket->sent_messages)
        {
            if (message->DebugString().find(prefix) != std::string::npos)
            {
                found_prefix = true;
                break;
            }
        }
        CPPUNIT_ASSERT(found_prefix);
    }

    void ArcusCommunicationTest::sendFinishedSlicingTest()
    {
        ac->sendFinishedSlicing();
        CPPUNIT_ASSERT_EQUAL(size_t(1), socket->sent_messages.size());
    }

    void ArcusCommunicationTest::sendLayerCompleteTest()
    {
        const LayerIndex layer_nr = 10;
        constexpr coord_t layer_z = 20;
        constexpr coord_t layer_thickness = 30;
        ac->sendLayerComplete(layer_nr, layer_z, layer_thickness);
        const std::shared_ptr<proto::LayerOptimized> message = ac->private_data->getOptimizedLayerById(layer_nr);
        CPPUNIT_ASSERT_EQUAL_MESSAGE("getOptimizedLayerById() must return a layer with the correct ID.",
                                     static_cast<google::protobuf::int32>(layer_nr), message->id());
        CPPUNIT_ASSERT_EQUAL(static_cast<float>(layer_z), message->height());
        CPPUNIT_ASSERT_EQUAL(static_cast<float>(layer_thickness), message->thickness());
    }

    void ArcusCommunicationTest::sendProgressTest()
    {
        ac->private_data->object_count = 2; //If there are two objects, all progress should get halved.

        ac->sendProgress(10);
        CPPUNIT_ASSERT_EQUAL(size_t(1), socket->sent_messages.size());
        proto::Progress* message = dynamic_cast<proto::Progress*>(socket->sent_messages.back().get());
        CPPUNIT_ASSERT_EQUAL(float(5), message->amount());

        ac->sendProgress(50);
        CPPUNIT_ASSERT_EQUAL(size_t(2), socket->sent_messages.size());
        message = dynamic_cast<proto::Progress*>(socket->sent_messages.back().get());
        CPPUNIT_ASSERT_EQUAL(float(25), message->amount());
    }

    void ArcusCommunicationTest::setLayerForSendTest()
    {
        ac->setLayerForSend(42);
    }

    void ArcusCommunicationTest::setExtruderForSendTest()
    {

    }

    void ArcusCommunicationTest::sliceNextTest()
    {
        ac->sliceNext();
    }
}

<|endoftext|>