<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "webkit/glue/plugins/plugin_list.h"

#include "base/file_util.h"
#include "base/path_service.h"

namespace NPAPI {

void PluginList::PlatformInit() {
}

void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) {
  // For now, just look in the plugins/ under the exe directory.
  // TODO(port): this is not correct.  Rather than getting halfway there,
  // this is a one-off and its replacement should follow Firefox exactly.
  FilePath dir;
  PathService::Get(base::DIR_EXE, &dir);
  plugin_dirs->push_back(dir.Append("plugins"));
}

void PluginList::LoadPluginsFromDir(const FilePath& path) {
  file_util::FileEnumerator enumerator(path,
                                       false, // not recursive
                                       file_util::FileEnumerator::FILES);
  for (FilePath path = enumerator.Next(); !path.value().empty();
       path = enumerator.Next()) {
    LoadPlugin(path);
  }
}

bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info) {
  // The equivalent Windows code verifies we haven't loaded a newer version
  // of the same plugin, and then blacklists some known bad plugins.
  // The equivalent Mac code verifies that plugins encountered first in the
  // plugin list clobber later entries.
  // TODO(evanm): figure out which behavior is appropriate for Linux.
  // We don't need either yet as I'm just testing with Flash for now.
  return true;
}

void PluginList::LoadInternalPlugins() {
  // none for now
}

} // namespace NPAPI
<commit_msg>linux: obey standard system paths for plugins<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "webkit/glue/plugins/plugin_list.h"

#include "base/file_util.h"
#include "base/path_service.h"

namespace NPAPI {

void PluginList::PlatformInit() {
}

void PluginList::GetPluginDirectories(std::vector<FilePath>* plugin_dirs) {
  // Mozilla code to reference:
  // http://mxr.mozilla.org/firefox/ident?i=NS_APP_PLUGINS_DIR_LIST
  // and tens of accompanying files (mxr is very helpful).
  // This code carefully matches their behavior for compat reasons.

  // 1) MOZ_PLUGIN_PATH env variable.
  const char* moz_plugin_path = getenv("MOZ_PLUGIN_PATH");
  if (moz_plugin_path)
    plugin_dirs->push_back(FilePath(moz_plugin_path));

  // 2) NS_USER_PLUGINS_DIR: ~/.mozilla/plugins.
  // TODO(evanm): should we do anything here?

  // 3) NS_APP_PLUGINS_DIR: the binary dir + "plugins/".
  FilePath dir;
  PathService::Get(base::DIR_EXE, &dir);
  plugin_dirs->push_back(dir.Append("plugins"));

  // 4) NS_SYSTEM_PLUGINS_DIR:
  // TODO(evanm): when we support 64-bit platforms, we'll need to fix this
  // to be conditional.
  COMPILE_ASSERT(sizeof(int)==4, fix_system_lib_path);
  plugin_dirs->push_back(FilePath("/usr/lib/mozilla/plugins"));
}

void PluginList::LoadPluginsFromDir(const FilePath& path) {
  file_util::FileEnumerator enumerator(path,
                                       false, // not recursive
                                       file_util::FileEnumerator::FILES);
  for (FilePath path = enumerator.Next(); !path.value().empty();
       path = enumerator.Next()) {
    LoadPlugin(path);
  }
}

bool PluginList::ShouldLoadPlugin(const WebPluginInfo& info) {
  // The equivalent Windows code verifies we haven't loaded a newer version
  // of the same plugin, and then blacklists some known bad plugins.
  // The equivalent Mac code verifies that plugins encountered first in the
  // plugin list clobber later entries.
  // TODO(evanm): figure out which behavior is appropriate for Linux.
  // We don't need either yet as I'm just testing with Flash for now.
  return true;
}

void PluginList::LoadInternalPlugins() {
  // none for now
}

} // namespace NPAPI
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SKNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW_ARGS(SkNWayCanvas, (0,0));
}
<commit_msg>fix include name (masked by case insensitiviy on windows)<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkNullCanvas.h"

#include "SkCanvas.h"
#include "SkNWayCanvas.h"

SkCanvas* SkCreateNullCanvas() {
    // An N-Way canvas forwards calls to N canvas's. When N == 0 it's
    // effectively a null canvas.
    return SkNEW_ARGS(SkNWayCanvas, (0,0));
}
<|endoftext|>


<commit_before>#include <assert.h>
#include <errno.h>
#include <iostream>
#include <new>
#include <sstream>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <core/CHIPError.h>
#include <inet/InetLayer.h>
#include <inet/UDPEndPoint.h>
#include <support/CHIPLogging.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>

#include <controller/CHIPDeviceController.h>

extern "C" {
#include "chip-zcl/chip-zcl.h"
#include "gen/gen-cluster-id.h"
#include "gen/gen-command-id.h"
#include "gen/gen-types.h"
} // extern "C"

// Delay, in seconds, between sends for the echo case.
#define SEND_DELAY 5

using namespace ::chip;
using namespace ::chip::Inet;

// NOTE: Remote device ID is in sync with the echo server device id
//       At some point, we may want to add an option to connect to a device without
//       knowing its id, because the ID can be learned on the first response that is received.
constexpr NodeId kLocalDeviceId  = 112233;
constexpr NodeId kRemoteDeviceId = 12344321;

static const unsigned char local_private_key[] = { 0x00, 0xd1, 0x90, 0xd9, 0xb3, 0x95, 0x1c, 0x5f, 0xa4, 0xe7, 0x47,
                                                   0x92, 0x5b, 0x0a, 0xa9, 0xa7, 0xc1, 0x1c, 0xe7, 0x06, 0x10, 0xe2,
                                                   0xdd, 0x16, 0x41, 0x52, 0x55, 0xb7, 0xb8, 0x80, 0x8d, 0x87, 0xa1 };

static const unsigned char remote_public_key[] = { 0x04, 0xe2, 0x07, 0x64, 0xff, 0x6f, 0x6a, 0x91, 0xd9, 0xc2, 0xc3, 0x0a, 0xc4,
                                                   0x3c, 0x56, 0x4b, 0x42, 0x8a, 0xf3, 0xb4, 0x49, 0x29, 0x39, 0x95, 0xa2, 0xf7,
                                                   0x02, 0x8c, 0xa5, 0xce, 0xf3, 0xc9, 0xca, 0x24, 0xc5, 0xd4, 0x5c, 0x60, 0x79,
                                                   0x48, 0x30, 0x3c, 0x53, 0x86, 0xd9, 0x23, 0xe6, 0x61, 0x1f, 0x5a, 0x3d, 0xdf,
                                                   0x9f, 0xdc, 0x35, 0xea, 0xd0, 0xde, 0x16, 0x7e, 0x64, 0xde, 0x7f, 0x3c, 0xa6 };

static const char * PAYLOAD = "Message from Standalone CHIP echo client!";

static void EchoKeyExchange(chip::DeviceController::ChipDeviceController * controller, Transport::PeerConnectionState * state,
                            void * appReqState)
{
    CHIP_ERROR err = controller->ManualKeyExchange(state, remote_public_key, sizeof(remote_public_key), local_private_key,
                                                   sizeof(local_private_key));

    if (err != CHIP_NO_ERROR)
    {
        fprintf(stderr, "Failed to exchange keys");
    }
}

// Device Manager Callbacks
static void EchoResponse(chip::DeviceController::ChipDeviceController * deviceController, void * appReqState,
                         System::PacketBuffer * buffer)
{
    char src_addr[INET_ADDRSTRLEN];
    char dest_addr[INET_ADDRSTRLEN];
    size_t data_len = buffer->DataLength();

    printf("UDP packet received from :%zu bytes)\n", static_cast<size_t>(buffer->DataLength()));

    // attempt to print the incoming message
    char msg_buffer[data_len];
    msg_buffer[data_len] = 0; // Null-terminate whatever we received and treat like a string...
    memcpy(msg_buffer, buffer->Start(), data_len);
    int compare = strncmp(msg_buffer, PAYLOAD, data_len);
    if (compare == 0)
    {
        printf("Got expected Message...\n");
    }
    else
    {
        printf("Didn't get the expected Echo. Compare: %d\n", compare);
        printf("\nSend: %s \nRecv: %s\n", PAYLOAD, msg_buffer);
    }

    System::PacketBuffer::Free(buffer);
}

static void ReceiveError(chip::DeviceController::ChipDeviceController * deviceController, void * appReqState, CHIP_ERROR error,
                         const IPPacketInfo * pi)
{
    printf("ERROR: %s\n Got UDP error\n", ErrorStr(error));
}

void ShowUsage(const char * executable)
{
    fprintf(stderr,
            "Usage: \n"
            "  %s device-ip-address device-port command [params]\n"
            "  Supported commands and their parameters:\n"
            "    echo\n"
            "    off endpoint-id\n"
            "    on endpoint-id\n"
            "    toggle endpoint-id\n",
            executable);
}

bool DetermineAddress(int argc, char * argv[], IPAddress * hostAddr, uint16_t * port)
{
    if (argc < 3)
    {
        return false;
    }

    if (!IPAddress::FromString(argv[1], *hostAddr))
    {
        fputs("Error: Invalid device IP address", stderr);
        return false;
    }

    std::string port_str(argv[2]);
    std::stringstream ss(port_str);
    ss >> *port;
    if (ss.fail() || !ss.eof())
    {
        fputs("Error: Invalid device port", stderr);
        return false;
    }

    return true;
}

enum class Command
{
    Off,
    On,
    Toggle,
    Echo,
};

template <int N>
bool EqualsLiteral(const char * str, const char (&literal)[N])
{
    return strncmp(str, literal, N) == 0;
}

bool DetermineCommand(int argc, char * argv[], Command * command)
{
    if (argc < 4)
    {
        return false;
    }

    if (EqualsLiteral(argv[3], "off"))
    {
        *command = Command::Off;
        return true;
    }

    if (EqualsLiteral(argv[3], "on"))
    {
        *command = Command::On;
        return true;
    }

    if (EqualsLiteral(argv[3], "toggle"))
    {
        *command = Command::Toggle;
        return true;
    }

    if (EqualsLiteral(argv[3], "echo"))
    {
        *command = Command::Echo;
        return true;
    }

    fprintf(stderr, "Unknown command: %s\n", argv[3]);
    return false;
}

union CommandArgs
{
    ChipZclEndpointId_t endpointId;
};

bool DetermineCommandArgs(int argc, char * argv[], Command command, CommandArgs * commandArgs)
{
    if (command == Command::Echo)
    {
        // No args.
        return true;
    }

    if (command != Command::On && command != Command::Off && command != Command::Toggle)
    {
        fprintf(stderr, "Need to define arg handling for command '%d'\n", int(command));
        return false;
    }

    if (argc < 5)
    {
        return false;
    }

    std::string endpoint_str(argv[4]);
    std::stringstream ss(endpoint_str);
    // stringstream treats uint8_t as char, which is not what we want here.
    uint16_t endpoint;
    ss >> endpoint;
    if (ss.fail() || !ss.eof() || endpoint > UINT8_MAX)
    {
        fprintf(stderr, "Error: Invalid endpoint id '%s'", argv[4]);
        return false;
    }
    commandArgs->endpointId = endpoint;

    return true;
}

// Handle the echo case, where we just send a string and expect to get it back.
void DoEcho(DeviceController::ChipDeviceController * controller, const IPAddress & host_addr, uint16_t port)
{
    size_t payload_len = strlen(PAYLOAD);

    // Run the client
    char host_ip_str[40];
    host_addr.ToString(host_ip_str, sizeof(host_ip_str));
    while (1)
    {
        // Reallocate buffer on each run, as the secure transport encrypts and
        // overwrites the buffer from previous iteration.
        auto * buffer = System::PacketBuffer::NewWithAvailableSize(payload_len);
        memcpy(buffer->Start(), PAYLOAD, payload_len);
        buffer->SetDataLength(payload_len);

        controller->SendMessage(NULL, buffer);
        printf("Msg sent to server at %s:%d\n", host_ip_str, port);

        controller->ServiceEvents();

        sleep(SEND_DELAY);
    }
}

// Handle the on/off/toggle case, where we are sending a ZCL command and not
// expecting a response at all.
void DoOnOff(DeviceController::ChipDeviceController * controller, Command command, ChipZclEndpointId_t endpoint)
{
    ChipZclCommandId_t zclCommand;
    switch (command)
    {
    case Command::Off:
        zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_OFF;
        break;
    case Command::On:
        zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_ON;
        break;
    case Command::Toggle:
        zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_TOGGLE;
        break;
    default:
        fprintf(stderr, "Unknown command: %d\n", command);
        return;
    }

    // Make sure our buffer is big enough, but this will need a better setup!
    static const size_t bufferSize = 1024;
    auto * buffer                  = System::PacketBuffer::NewWithAvailableSize(bufferSize);

    ChipZclBuffer_t * zcl_buffer = (ChipZclBuffer_t *) buffer;
    ChipZclCommandContext_t ctx  = {
        endpoint,                       // endpointId
        CHIP_ZCL_CLUSTER_ON_OFF,        // clusterId
        true,                           // clusterSpecific
        false,                          // mfgSpecific
        0,                              // mfgCode
        zclCommand,                     // commandId
        ZCL_DIRECTION_CLIENT_TO_SERVER, // direction
        0,                              // payloadStartIndex
        nullptr,                        // request
        nullptr                         // response
    };
    chipZclEncodeZclHeader(zcl_buffer, &ctx);

#ifdef DEBUG
    const size_t data_len = chipZclBufferDataLength(zcl_buffer);

    fprintf(stderr, "SENDING: %zu ", data_len);
    for (size_t i = 0; i < data_len; ++i)
    {
        fprintf(stderr, "%d ", chipZclBufferPointer(zcl_buffer)[i]);
    }
    fprintf(stderr, "\n");
#endif

    controller->SendMessage(NULL, buffer);
    controller->ServiceEvents();
}

// ================================================================================
// Main Code
// ================================================================================
int main(int argc, char * argv[])
{
    IPAddress host_addr;
    uint16_t port;
    Command command;
    CHIP_ERROR err;
    CommandArgs commandArgs;
    if (!DetermineAddress(argc, argv, &host_addr, &port) || !DetermineCommand(argc, argv, &command) ||
        !DetermineCommandArgs(argc, argv, command, &commandArgs))
    {
        ShowUsage(argv[0]);
        return -1;
    }

    auto * controller = new DeviceController::ChipDeviceController();
    err               = controller->Init(kLocalDeviceId);
    VerifyOrExit(err == CHIP_NO_ERROR, fprintf(stderr, "Failed to initialize the device controller"));

    err = controller->ConnectDevice(kRemoteDeviceId, host_addr, NULL, EchoKeyExchange, EchoResponse, ReceiveError, port);
    VerifyOrExit(err == CHIP_NO_ERROR, fprintf(stderr, "Failed to connect to the device"));

    if (command == Command::Echo)
    {
        DoEcho(controller, host_addr, port);
    }
    else
    {
        DoOnOff(controller, command, commandArgs.endpointId);
    }

exit:
    if (err != CHIP_NO_ERROR)
    {
        fprintf(stderr, "ERROR: %s\n", ErrorStr(err));
    }
    controller->Shutdown();
    delete controller;

    return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE;
}

extern "C" {
// We have to have this empty callback, because the ZCL code links against it.
void chipZclPostAttributeChangeCallback(uint8_t endpoint, ChipZclClusterId clusterId, ChipZclAttributeId attributeId, uint8_t mask,
                                        uint16_t manufacturerCode, uint8_t type, uint8_t size, uint8_t * value)
{}
} // extern "C"
<commit_msg>Fix awkward wording into in log message<commit_after>#include <assert.h>
#include <errno.h>
#include <iostream>
#include <new>
#include <sstream>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <core/CHIPError.h>
#include <inet/InetLayer.h>
#include <inet/UDPEndPoint.h>
#include <support/CHIPLogging.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>

#include <controller/CHIPDeviceController.h>

extern "C" {
#include "chip-zcl/chip-zcl.h"
#include "gen/gen-cluster-id.h"
#include "gen/gen-command-id.h"
#include "gen/gen-types.h"
} // extern "C"

// Delay, in seconds, between sends for the echo case.
#define SEND_DELAY 5

using namespace ::chip;
using namespace ::chip::Inet;

// NOTE: Remote device ID is in sync with the echo server device id
//       At some point, we may want to add an option to connect to a device without
//       knowing its id, because the ID can be learned on the first response that is received.
constexpr NodeId kLocalDeviceId  = 112233;
constexpr NodeId kRemoteDeviceId = 12344321;

static const unsigned char local_private_key[] = { 0x00, 0xd1, 0x90, 0xd9, 0xb3, 0x95, 0x1c, 0x5f, 0xa4, 0xe7, 0x47,
                                                   0x92, 0x5b, 0x0a, 0xa9, 0xa7, 0xc1, 0x1c, 0xe7, 0x06, 0x10, 0xe2,
                                                   0xdd, 0x16, 0x41, 0x52, 0x55, 0xb7, 0xb8, 0x80, 0x8d, 0x87, 0xa1 };

static const unsigned char remote_public_key[] = { 0x04, 0xe2, 0x07, 0x64, 0xff, 0x6f, 0x6a, 0x91, 0xd9, 0xc2, 0xc3, 0x0a, 0xc4,
                                                   0x3c, 0x56, 0x4b, 0x42, 0x8a, 0xf3, 0xb4, 0x49, 0x29, 0x39, 0x95, 0xa2, 0xf7,
                                                   0x02, 0x8c, 0xa5, 0xce, 0xf3, 0xc9, 0xca, 0x24, 0xc5, 0xd4, 0x5c, 0x60, 0x79,
                                                   0x48, 0x30, 0x3c, 0x53, 0x86, 0xd9, 0x23, 0xe6, 0x61, 0x1f, 0x5a, 0x3d, 0xdf,
                                                   0x9f, 0xdc, 0x35, 0xea, 0xd0, 0xde, 0x16, 0x7e, 0x64, 0xde, 0x7f, 0x3c, 0xa6 };

static const char * PAYLOAD = "Message from Standalone CHIP echo client!";

static void EchoKeyExchange(chip::DeviceController::ChipDeviceController * controller, Transport::PeerConnectionState * state,
                            void * appReqState)
{
    CHIP_ERROR err = controller->ManualKeyExchange(state, remote_public_key, sizeof(remote_public_key), local_private_key,
                                                   sizeof(local_private_key));

    if (err != CHIP_NO_ERROR)
    {
        fprintf(stderr, "Failed to exchange keys");
    }
}

// Device Manager Callbacks
static void EchoResponse(chip::DeviceController::ChipDeviceController * deviceController, void * appReqState,
                         System::PacketBuffer * buffer)
{
    size_t data_len = buffer->DataLength();

    printf("UDP packet received: %zu bytes\n", static_cast<size_t>(buffer->DataLength()));

    // attempt to print the incoming message
    char msg_buffer[data_len];
    msg_buffer[data_len] = 0; // Null-terminate whatever we received and treat like a string...
    memcpy(msg_buffer, buffer->Start(), data_len);
    int compare = strncmp(msg_buffer, PAYLOAD, data_len);
    if (compare == 0)
    {
        printf("Got expected Message...\n");
    }
    else
    {
        printf("Didn't get the expected Echo. Compare: %d\n", compare);
        printf("\nSend: %s \nRecv: %s\n", PAYLOAD, msg_buffer);
    }

    System::PacketBuffer::Free(buffer);
}

static void ReceiveError(chip::DeviceController::ChipDeviceController * deviceController, void * appReqState, CHIP_ERROR error,
                         const IPPacketInfo * pi)
{
    printf("ERROR: %s\n Got UDP error\n", ErrorStr(error));
}

void ShowUsage(const char * executable)
{
    fprintf(stderr,
            "Usage: \n"
            "  %s device-ip-address device-port command [params]\n"
            "  Supported commands and their parameters:\n"
            "    echo\n"
            "    off endpoint-id\n"
            "    on endpoint-id\n"
            "    toggle endpoint-id\n",
            executable);
}

bool DetermineAddress(int argc, char * argv[], IPAddress * hostAddr, uint16_t * port)
{
    if (argc < 3)
    {
        return false;
    }

    if (!IPAddress::FromString(argv[1], *hostAddr))
    {
        fputs("Error: Invalid device IP address", stderr);
        return false;
    }

    std::string port_str(argv[2]);
    std::stringstream ss(port_str);
    ss >> *port;
    if (ss.fail() || !ss.eof())
    {
        fputs("Error: Invalid device port", stderr);
        return false;
    }

    return true;
}

enum class Command
{
    Off,
    On,
    Toggle,
    Echo,
};

template <int N>
bool EqualsLiteral(const char * str, const char (&literal)[N])
{
    return strncmp(str, literal, N) == 0;
}

bool DetermineCommand(int argc, char * argv[], Command * command)
{
    if (argc < 4)
    {
        return false;
    }

    if (EqualsLiteral(argv[3], "off"))
    {
        *command = Command::Off;
        return true;
    }

    if (EqualsLiteral(argv[3], "on"))
    {
        *command = Command::On;
        return true;
    }

    if (EqualsLiteral(argv[3], "toggle"))
    {
        *command = Command::Toggle;
        return true;
    }

    if (EqualsLiteral(argv[3], "echo"))
    {
        *command = Command::Echo;
        return true;
    }

    fprintf(stderr, "Unknown command: %s\n", argv[3]);
    return false;
}

union CommandArgs
{
    ChipZclEndpointId_t endpointId;
};

bool DetermineCommandArgs(int argc, char * argv[], Command command, CommandArgs * commandArgs)
{
    if (command == Command::Echo)
    {
        // No args.
        return true;
    }

    if (command != Command::On && command != Command::Off && command != Command::Toggle)
    {
        fprintf(stderr, "Need to define arg handling for command '%d'\n", int(command));
        return false;
    }

    if (argc < 5)
    {
        return false;
    }

    std::string endpoint_str(argv[4]);
    std::stringstream ss(endpoint_str);
    // stringstream treats uint8_t as char, which is not what we want here.
    uint16_t endpoint;
    ss >> endpoint;
    if (ss.fail() || !ss.eof() || endpoint > UINT8_MAX)
    {
        fprintf(stderr, "Error: Invalid endpoint id '%s'", argv[4]);
        return false;
    }
    commandArgs->endpointId = endpoint;

    return true;
}

// Handle the echo case, where we just send a string and expect to get it back.
void DoEcho(DeviceController::ChipDeviceController * controller, const IPAddress & host_addr, uint16_t port)
{
    size_t payload_len = strlen(PAYLOAD);

    // Run the client
    char host_ip_str[40];
    host_addr.ToString(host_ip_str, sizeof(host_ip_str));
    while (1)
    {
        // Reallocate buffer on each run, as the secure transport encrypts and
        // overwrites the buffer from previous iteration.
        auto * buffer = System::PacketBuffer::NewWithAvailableSize(payload_len);
        memcpy(buffer->Start(), PAYLOAD, payload_len);
        buffer->SetDataLength(payload_len);

        controller->SendMessage(NULL, buffer);
        printf("Msg sent to server at %s:%d\n", host_ip_str, port);

        controller->ServiceEvents();

        sleep(SEND_DELAY);
    }
}

// Handle the on/off/toggle case, where we are sending a ZCL command and not
// expecting a response at all.
void DoOnOff(DeviceController::ChipDeviceController * controller, Command command, ChipZclEndpointId_t endpoint)
{
    ChipZclCommandId_t zclCommand;
    switch (command)
    {
    case Command::Off:
        zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_OFF;
        break;
    case Command::On:
        zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_ON;
        break;
    case Command::Toggle:
        zclCommand = CHIP_ZCL_CLUSTER_ON_OFF_SERVER_COMMAND_TOGGLE;
        break;
    default:
        fprintf(stderr, "Unknown command: %d\n", command);
        return;
    }

    // Make sure our buffer is big enough, but this will need a better setup!
    static const size_t bufferSize = 1024;
    auto * buffer                  = System::PacketBuffer::NewWithAvailableSize(bufferSize);

    ChipZclBuffer_t * zcl_buffer = (ChipZclBuffer_t *) buffer;
    ChipZclCommandContext_t ctx  = {
        endpoint,                       // endpointId
        CHIP_ZCL_CLUSTER_ON_OFF,        // clusterId
        true,                           // clusterSpecific
        false,                          // mfgSpecific
        0,                              // mfgCode
        zclCommand,                     // commandId
        ZCL_DIRECTION_CLIENT_TO_SERVER, // direction
        0,                              // payloadStartIndex
        nullptr,                        // request
        nullptr                         // response
    };
    chipZclEncodeZclHeader(zcl_buffer, &ctx);

#ifdef DEBUG
    const size_t data_len = chipZclBufferDataLength(zcl_buffer);

    fprintf(stderr, "SENDING: %zu ", data_len);
    for (size_t i = 0; i < data_len; ++i)
    {
        fprintf(stderr, "%d ", chipZclBufferPointer(zcl_buffer)[i]);
    }
    fprintf(stderr, "\n");
#endif

    controller->SendMessage(NULL, buffer);
    controller->ServiceEvents();
}

// ================================================================================
// Main Code
// ================================================================================
int main(int argc, char * argv[])
{
    IPAddress host_addr;
    uint16_t port;
    Command command;
    CHIP_ERROR err;
    CommandArgs commandArgs;
    if (!DetermineAddress(argc, argv, &host_addr, &port) || !DetermineCommand(argc, argv, &command) ||
        !DetermineCommandArgs(argc, argv, command, &commandArgs))
    {
        ShowUsage(argv[0]);
        return -1;
    }

    auto * controller = new DeviceController::ChipDeviceController();
    err               = controller->Init(kLocalDeviceId);
    VerifyOrExit(err == CHIP_NO_ERROR, fprintf(stderr, "Failed to initialize the device controller"));

    err = controller->ConnectDevice(kRemoteDeviceId, host_addr, NULL, EchoKeyExchange, EchoResponse, ReceiveError, port);
    VerifyOrExit(err == CHIP_NO_ERROR, fprintf(stderr, "Failed to connect to the device"));

    if (command == Command::Echo)
    {
        DoEcho(controller, host_addr, port);
    }
    else
    {
        DoOnOff(controller, command, commandArgs.endpointId);
    }

exit:
    if (err != CHIP_NO_ERROR)
    {
        fprintf(stderr, "ERROR: %s\n", ErrorStr(err));
    }
    controller->Shutdown();
    delete controller;

    return (err == CHIP_NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE;
}

extern "C" {
// We have to have this empty callback, because the ZCL code links against it.
void chipZclPostAttributeChangeCallback(uint8_t endpoint, ChipZclClusterId clusterId, ChipZclAttributeId attributeId, uint8_t mask,
                                        uint16_t manufacturerCode, uint8_t type, uint8_t size, uint8_t * value)
{}
} // extern "C"
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/resource_fetcher.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/message_loop.h"
#include "base/timer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "webkit/glue/unittest_test_server.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell_test.h"

using WebKit::WebFrame;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;
using webkit_glue::ResourceFetcher;
using webkit_glue::ResourceFetcherWithTimeout;

namespace {

class ResourceFetcherTests : public TestShellTest {
 protected:
  UnittestTestServer test_server_;
};

static const int kMaxWaitTimeMs = 5000;

class FetcherDelegate {
 public:
  FetcherDelegate()
      : completed_(false),
        timed_out_(false) {
    // Start a repeating timer waiting for the download to complete.  The
    // callback has to be a static function, so we hold on to our instance.
    FetcherDelegate::instance_ = this;
    StartTimer();
  }

  virtual ~FetcherDelegate() {}

  ResourceFetcher::Callback NewCallback() {
    return base::Bind(&FetcherDelegate::OnURLFetchComplete,
                      base::Unretained(this));
  }

  virtual void OnURLFetchComplete(const WebURLResponse& response,
                                  const std::string& data) {
    response_ = response;
    data_ = data;
    completed_ = true;
    timer_.Stop();
    MessageLoop::current()->Quit();
  }

  bool completed() const { return completed_; }
  bool timed_out() const { return timed_out_; }

  std::string data() const { return data_; }
  const WebURLResponse& response() const { return response_; }

  // Wait for the request to complete or timeout.  We use a loop here b/c the
  // testing infrastructure (test_shell) can generate spurious calls to the
  // MessageLoop's Quit method.
  void WaitForResponse() {
    while (!completed() && !timed_out())
      MessageLoop::current()->Run();
  }

  void StartTimer() {
    timer_.Start(FROM_HERE,
                 base::TimeDelta::FromMilliseconds(kMaxWaitTimeMs),
                 this,
                 &FetcherDelegate::TimerFired);
  }

  void TimerFired() {
    ASSERT_FALSE(completed_);

    timed_out_ = true;
    MessageLoop::current()->Quit();
    FAIL() << "fetch timed out";
  }

  static FetcherDelegate* instance_;

 private:
  base::OneShotTimer<FetcherDelegate> timer_;
  bool completed_;
  bool timed_out_;
  WebURLResponse response_;
  std::string data_;
};

FetcherDelegate* FetcherDelegate::instance_ = NULL;

// Test a fetch from the test server.
// Flaky, http://crbug.com/51622.
TEST_F(ResourceFetcherTests, FLAKY_ResourceFetcherDownload) {
  ASSERT_TRUE(test_server_.Start());

  WebFrame* frame = test_shell_->webView()->mainFrame();

  GURL url(test_server_.GetURL("files/test_shell/index.html"));
  scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);
  scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcher(
      url, frame, WebURLRequest::TargetIsMainFrame, delegate->NewCallback()));

  delegate->WaitForResponse();

  ASSERT_TRUE(delegate->completed());
  EXPECT_EQ(delegate->response().httpStatusCode(), 200);
  std::string text = delegate->data();
  EXPECT_TRUE(text.find("What is this page?") != std::string::npos);

  // Test 404 response.
  url = test_server_.GetURL("files/thisfiledoesntexist.html");
  delegate.reset(new FetcherDelegate);
  fetcher.reset(new ResourceFetcher(url, frame,
                                    WebURLRequest::TargetIsMainFrame,
                                    delegate->NewCallback()));

  delegate->WaitForResponse();

  ASSERT_TRUE(delegate->completed());
  EXPECT_EQ(delegate->response().httpStatusCode(), 404);
  EXPECT_TRUE(delegate->data().find("Not Found.") != std::string::npos);
}

// Flaky, http://crbug.com/51622.
TEST_F(ResourceFetcherTests, FLAKY_ResourceFetcherDidFail) {
  ASSERT_TRUE(test_server_.Start());

  WebFrame* frame = test_shell_->webView()->mainFrame();

  // Try to fetch a page on a site that doesn't exist.
  GURL url("http://localhost:1339/doesnotexist");
  scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);
  scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcher(
      url, frame, WebURLRequest::TargetIsMainFrame, delegate->NewCallback()));

  delegate->WaitForResponse();

  // When we fail, we still call the Delegate callback but we pass in empty
  // values.
  EXPECT_TRUE(delegate->completed());
  EXPECT_TRUE(delegate->response().isNull());
  EXPECT_EQ(delegate->data(), std::string());
  EXPECT_FALSE(delegate->timed_out());
}

TEST_F(ResourceFetcherTests, ResourceFetcherTimeout) {
  ASSERT_TRUE(test_server_.Start());

  WebFrame* frame = test_shell_->webView()->mainFrame();

  // Grab a page that takes at least 1 sec to respond, but set the fetcher to
  // timeout in 0 sec.
  GURL url(test_server_.GetURL("slow?1"));
  scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);
  scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcherWithTimeout(
      url, frame, WebURLRequest::TargetIsMainFrame,
      0, delegate->NewCallback()));

  delegate->WaitForResponse();

  // When we timeout, we still call the Delegate callback but we pass in empty
  // values.
  EXPECT_TRUE(delegate->completed());
  EXPECT_TRUE(delegate->response().isNull());
  EXPECT_EQ(delegate->data(), std::string());
  EXPECT_FALSE(delegate->timed_out());
}

class EvilFetcherDelegate : public FetcherDelegate {
 public:
  virtual ~EvilFetcherDelegate() {}

  void SetFetcher(ResourceFetcher* fetcher) {
    fetcher_.reset(fetcher);
  }

  virtual void OnURLFetchComplete(const WebURLResponse& response,
                                  const std::string& data) {
    // Destroy the ResourceFetcher here.  We are testing that upon returning
    // to the ResourceFetcher that it does not crash.
    fetcher_.reset();
    FetcherDelegate::OnURLFetchComplete(response, data);
  }

 private:
  scoped_ptr<ResourceFetcher> fetcher_;
};

TEST_F(ResourceFetcherTests, ResourceFetcherDeletedInCallback) {
  ASSERT_TRUE(test_server_.Start());

  WebFrame* frame = test_shell_->webView()->mainFrame();

  // Grab a page that takes at least 1 sec to respond, but set the fetcher to
  // timeout in 0 sec.
  GURL url(test_server_.GetURL("slow?1"));
  scoped_ptr<EvilFetcherDelegate> delegate(new EvilFetcherDelegate);
  scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcherWithTimeout(
      url, frame, WebURLRequest::TargetIsMainFrame,
      0, delegate->NewCallback()));
  delegate->SetFetcher(fetcher.release());

  delegate->WaitForResponse();
  EXPECT_FALSE(delegate->timed_out());
}

}  // namespace
<commit_msg>Flakiness cleanup: disable flaky tests under webkit/<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/resource_fetcher.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/message_loop.h"
#include "base/timer.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "webkit/glue/unittest_test_server.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell_test.h"

using WebKit::WebFrame;
using WebKit::WebURLRequest;
using WebKit::WebURLResponse;
using webkit_glue::ResourceFetcher;
using webkit_glue::ResourceFetcherWithTimeout;

namespace {

class ResourceFetcherTests : public TestShellTest {
 protected:
  UnittestTestServer test_server_;
};

static const int kMaxWaitTimeMs = 5000;

class FetcherDelegate {
 public:
  FetcherDelegate()
      : completed_(false),
        timed_out_(false) {
    // Start a repeating timer waiting for the download to complete.  The
    // callback has to be a static function, so we hold on to our instance.
    FetcherDelegate::instance_ = this;
    StartTimer();
  }

  virtual ~FetcherDelegate() {}

  ResourceFetcher::Callback NewCallback() {
    return base::Bind(&FetcherDelegate::OnURLFetchComplete,
                      base::Unretained(this));
  }

  virtual void OnURLFetchComplete(const WebURLResponse& response,
                                  const std::string& data) {
    response_ = response;
    data_ = data;
    completed_ = true;
    timer_.Stop();
    MessageLoop::current()->Quit();
  }

  bool completed() const { return completed_; }
  bool timed_out() const { return timed_out_; }

  std::string data() const { return data_; }
  const WebURLResponse& response() const { return response_; }

  // Wait for the request to complete or timeout.  We use a loop here b/c the
  // testing infrastructure (test_shell) can generate spurious calls to the
  // MessageLoop's Quit method.
  void WaitForResponse() {
    while (!completed() && !timed_out())
      MessageLoop::current()->Run();
  }

  void StartTimer() {
    timer_.Start(FROM_HERE,
                 base::TimeDelta::FromMilliseconds(kMaxWaitTimeMs),
                 this,
                 &FetcherDelegate::TimerFired);
  }

  void TimerFired() {
    ASSERT_FALSE(completed_);

    timed_out_ = true;
    MessageLoop::current()->Quit();
    FAIL() << "fetch timed out";
  }

  static FetcherDelegate* instance_;

 private:
  base::OneShotTimer<FetcherDelegate> timer_;
  bool completed_;
  bool timed_out_;
  WebURLResponse response_;
  std::string data_;
};

FetcherDelegate* FetcherDelegate::instance_ = NULL;

// Test a fetch from the test server.
// Flaky, http://crbug.com/51622.
TEST_F(ResourceFetcherTests, DISABLED_ResourceFetcherDownload) {
  ASSERT_TRUE(test_server_.Start());

  WebFrame* frame = test_shell_->webView()->mainFrame();

  GURL url(test_server_.GetURL("files/test_shell/index.html"));
  scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);
  scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcher(
      url, frame, WebURLRequest::TargetIsMainFrame, delegate->NewCallback()));

  delegate->WaitForResponse();

  ASSERT_TRUE(delegate->completed());
  EXPECT_EQ(delegate->response().httpStatusCode(), 200);
  std::string text = delegate->data();
  EXPECT_TRUE(text.find("What is this page?") != std::string::npos);

  // Test 404 response.
  url = test_server_.GetURL("files/thisfiledoesntexist.html");
  delegate.reset(new FetcherDelegate);
  fetcher.reset(new ResourceFetcher(url, frame,
                                    WebURLRequest::TargetIsMainFrame,
                                    delegate->NewCallback()));

  delegate->WaitForResponse();

  ASSERT_TRUE(delegate->completed());
  EXPECT_EQ(delegate->response().httpStatusCode(), 404);
  EXPECT_TRUE(delegate->data().find("Not Found.") != std::string::npos);
}

// Flaky, http://crbug.com/51622.
TEST_F(ResourceFetcherTests, DISABLED_ResourceFetcherDidFail) {
  ASSERT_TRUE(test_server_.Start());

  WebFrame* frame = test_shell_->webView()->mainFrame();

  // Try to fetch a page on a site that doesn't exist.
  GURL url("http://localhost:1339/doesnotexist");
  scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);
  scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcher(
      url, frame, WebURLRequest::TargetIsMainFrame, delegate->NewCallback()));

  delegate->WaitForResponse();

  // When we fail, we still call the Delegate callback but we pass in empty
  // values.
  EXPECT_TRUE(delegate->completed());
  EXPECT_TRUE(delegate->response().isNull());
  EXPECT_EQ(delegate->data(), std::string());
  EXPECT_FALSE(delegate->timed_out());
}

TEST_F(ResourceFetcherTests, ResourceFetcherTimeout) {
  ASSERT_TRUE(test_server_.Start());

  WebFrame* frame = test_shell_->webView()->mainFrame();

  // Grab a page that takes at least 1 sec to respond, but set the fetcher to
  // timeout in 0 sec.
  GURL url(test_server_.GetURL("slow?1"));
  scoped_ptr<FetcherDelegate> delegate(new FetcherDelegate);
  scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcherWithTimeout(
      url, frame, WebURLRequest::TargetIsMainFrame,
      0, delegate->NewCallback()));

  delegate->WaitForResponse();

  // When we timeout, we still call the Delegate callback but we pass in empty
  // values.
  EXPECT_TRUE(delegate->completed());
  EXPECT_TRUE(delegate->response().isNull());
  EXPECT_EQ(delegate->data(), std::string());
  EXPECT_FALSE(delegate->timed_out());
}

class EvilFetcherDelegate : public FetcherDelegate {
 public:
  virtual ~EvilFetcherDelegate() {}

  void SetFetcher(ResourceFetcher* fetcher) {
    fetcher_.reset(fetcher);
  }

  virtual void OnURLFetchComplete(const WebURLResponse& response,
                                  const std::string& data) {
    // Destroy the ResourceFetcher here.  We are testing that upon returning
    // to the ResourceFetcher that it does not crash.
    fetcher_.reset();
    FetcherDelegate::OnURLFetchComplete(response, data);
  }

 private:
  scoped_ptr<ResourceFetcher> fetcher_;
};

TEST_F(ResourceFetcherTests, ResourceFetcherDeletedInCallback) {
  ASSERT_TRUE(test_server_.Start());

  WebFrame* frame = test_shell_->webView()->mainFrame();

  // Grab a page that takes at least 1 sec to respond, but set the fetcher to
  // timeout in 0 sec.
  GURL url(test_server_.GetURL("slow?1"));
  scoped_ptr<EvilFetcherDelegate> delegate(new EvilFetcherDelegate);
  scoped_ptr<ResourceFetcher> fetcher(new ResourceFetcherWithTimeout(
      url, frame, WebURLRequest::TargetIsMainFrame,
      0, delegate->NewCallback()));
  delegate->SetFetcher(fetcher.release());

  delegate->WaitForResponse();
  EXPECT_FALSE(delegate->timed_out());
}

}  // namespace
<|endoftext|>


<commit_before>// Program.cpp

#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "interface/MarkedObject.h"
#include "interface/PropertyString.h"
#include "interface/Tool.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
#include "Adaptive.h"
#include "Op.h"

bool COperations::CanAdd(HeeksObj* object)
{
	return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType || object->GetType() == AdaptiveType;
}

void COperations::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "Operations" );
	root->LinkEndChild( element );
	WriteBaseXML(element);
}

//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
	COperations* new_object = new COperations;
	new_object->ReadBaseXML(pElem);
	return new_object;
}

static COperations* object_for_tools = NULL;

class SetAllActive: public Tool{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("Set All Operations Active");}
	void Run()
	{
		for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
		{
			if(COp::IsAnOperation(object->GetType()))
			{
				((COp*)object)->m_active = true;
				heeksCAD->WasModified(object);
			}
		}
	}
	wxString BitmapPath(){ return _T("setactive");}
};

static SetAllActive set_all_active;

class SetAllInactive: public Tool{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("Set All Operations Inactive");}
	void Run()
	{
		for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
		{
			if(COp::IsAnOperation(object->GetType()))
			{
				((COp*)object)->m_active = false;
				heeksCAD->WasModified(object);
			}
		}
	}
	wxString BitmapPath(){ return _T("setinactive");}
};

static SetAllInactive set_all_inactive;

void COperations::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
	object_for_tools = this;
	t_list->push_back(&set_all_active);
	t_list->push_back(&set_all_inactive);

	ObjList::GetTools(t_list, p);
}

CProgram::CProgram():m_machine(_T("nc.iso")), m_output_file(_T("test.tap")), m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
}

HeeksObj *CProgram::MakeACopy(void)const
{
	return new CProgram(*this);
}

void CProgram::CopyFrom(const HeeksObj* object)
{
	operator=(*((CProgram*)object));
}

static void on_set_machine(const wxChar* value, HeeksObj* object){((CProgram*)object)->m_machine = value;}
static void on_set_output_file(const wxChar* value, HeeksObj* object){((CProgram*)object)->m_output_file = value;}

void CProgram::GetProperties(std::list<Property *> *list)
{
	list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
	list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
	HeeksObj::GetProperties(list);
}

bool CProgram::CanAdd(HeeksObj* object)
{
	return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}

bool CProgram::CanAddTo(HeeksObj* owner)
{
	return owner->GetType() == DocumentType;
}

void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
	if(marked_object->m_map.size() > 0)
	{
		MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
		if(sub_marked_object)
		{
			HeeksObj* object = sub_marked_object->m_map.begin()->first;
			if(object && object->GetType() == NCCodeType)
			{
				((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
			}
		}
	}
}

void CProgram::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "Program" );
	root->LinkEndChild( element );
	element->SetAttribute("machine", Ttc(m_machine.c_str()));
	element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
	element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));

	WriteBaseXML(element);
}

bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
	if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
	if(object->GetType() == OperationsType)m_operations = (COperations*)object;
	return ObjList::Add(object, prev_object);
}

void CProgram::Remove(HeeksObj* object)
{
	 // these shouldn't happen, though
	if(object == m_nc_code)m_nc_code = NULL;
	else if(object == m_operations)m_operations = NULL;

	ObjList::Remove(object);
}

// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
	CProgram* new_object = new CProgram;

	// get the attributes
	for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
	{
		std::string name(a->Name());
		if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
		else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
		else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
	}

	new_object->ReadBaseXML(pElem);
	theApp.m_program = new_object;

	return new_object;
}

void CProgram::RewritePythonProgram()
{
	theApp.m_program_canvas->m_textCtrl->Clear();
	CZigZag::number_for_stl_file = 1;
	CAdaptive::number_for_stl_file = 1;

	bool profile_op_exists = false;
	bool pocket_op_exists = false;
	bool zigzag_op_exists = false;
	bool adaptive_op_exists = false;
	for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
	{
		if(object->GetType() == ProfileType)
		{
			if(((CProfile*)object)->m_active)profile_op_exists = true;
		}
		else if(object->GetType() == PocketType)
		{
			if(((CPocket*)object)->m_active)pocket_op_exists = true;
		}
		else if(object->GetType() == ZigZagType)
		{
			if(((CZigZag*)object)->m_active)zigzag_op_exists = true;
		}
		else if(object->GetType() == AdaptiveType)
		{
			if(((CAdaptive*)object)->m_active)adaptive_op_exists = true;
		}
	}

	// add standard stuff at the top

	// kurve related things
	if(profile_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
	}

	// area related things
	if(pocket_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
	}

	// pycam stuff
	if(zigzag_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
	}

	// actp
	if(adaptive_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp_funcs\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
	}

	// machine general stuff
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));

	// specific machine
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));

	// output file
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));

	// begin program
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));

	// write the operations
	for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
	{
		switch(object->GetType())
		{
		case ProfileType:
			if(((CProfile*)object)->m_active)((CProfile*)object)->AppendTextToProgram();
			break;
		case PocketType:
			if(((CPocket*)object)->m_active)((CPocket*)object)->AppendTextToProgram();
			break;
		case ZigZagType:
			if(((CZigZag*)object)->m_active)((CZigZag*)object)->AppendTextToProgram();
			break;
		case AdaptiveType:
			if(((CAdaptive*)object)->m_active)((CAdaptive*)object)->AppendTextToProgram();
			break;
		}
	}
}

ProgramUserType CProgram::GetUserType()
{
	if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
	if(m_script_edited)return ProgramUserTypeScript;
	if(m_operations->GetFirstChild())return ProgramUserTypeTree;
	return ProgramUserTypeUnkown;
}

void CProgram::UpdateFromUserType()
{
#if 0
	switch(GetUserType())
	{
	case ProgramUserTypeUnkown:

	case tree:
   Enable "Operations" icon in tree
     editing the tree, recreates the python script
   Read only "Program" window
     pressing "Post-process" creates the NC code ( and backplots it )
   Read only "Output" window
   Disable all buttons on "Output" window

	}
#endif
}
<commit_msg>fixed "Remember machine" http://code.google.com/p/heekscnc/issues/detail?id=72<commit_after>// Program.cpp

#include "stdafx.h"
#include "Program.h"
#include "PythonStuff.h"
#include "tinyxml/tinyxml.h"
#include "ProgramCanvas.h"
#include "NCCode.h"
#include "interface/MarkedObject.h"
#include "interface/PropertyString.h"
#include "interface/Tool.h"
#include "Profile.h"
#include "Pocket.h"
#include "ZigZag.h"
#include "Adaptive.h"
#include "Op.h"
#include "CNCConfig.h"

bool COperations::CanAdd(HeeksObj* object)
{
	return object->GetType() == ProfileType || object->GetType() == PocketType || object->GetType() == ZigZagType || object->GetType() == AdaptiveType;
}

void COperations::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "Operations" );
	root->LinkEndChild( element );
	WriteBaseXML(element);
}

//static
HeeksObj* COperations::ReadFromXMLElement(TiXmlElement* pElem)
{
	COperations* new_object = new COperations;
	new_object->ReadBaseXML(pElem);
	return new_object;
}

static COperations* object_for_tools = NULL;

class SetAllActive: public Tool{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("Set All Operations Active");}
	void Run()
	{
		for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
		{
			if(COp::IsAnOperation(object->GetType()))
			{
				((COp*)object)->m_active = true;
				heeksCAD->WasModified(object);
			}
		}
	}
	wxString BitmapPath(){ return _T("setactive");}
};

static SetAllActive set_all_active;

class SetAllInactive: public Tool{
	// Tool's virtual functions
	const wxChar* GetTitle(){return _("Set All Operations Inactive");}
	void Run()
	{
		for(HeeksObj* object = object_for_tools->GetFirstChild(); object; object = object_for_tools->GetNextChild())
		{
			if(COp::IsAnOperation(object->GetType()))
			{
				((COp*)object)->m_active = false;
				heeksCAD->WasModified(object);
			}
		}
	}
	wxString BitmapPath(){ return _T("setinactive");}
};

static SetAllInactive set_all_inactive;

void COperations::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
	object_for_tools = this;
	t_list->push_back(&set_all_active);
	t_list->push_back(&set_all_inactive);

	ObjList::GetTools(t_list, p);
}

CProgram::CProgram():m_nc_code(NULL), m_operations(NULL), m_script_edited(false)
{
	CNCConfig config;
	config.Read(_T("ProgramMachine"), &m_machine, _T("nc.iso"));
	config.Read(_T("ProgramOutputFile"), &m_output_file, _T("test.tap"));
}

HeeksObj *CProgram::MakeACopy(void)const
{
	return new CProgram(*this);
}

void CProgram::CopyFrom(const HeeksObj* object)
{
	operator=(*((CProgram*)object));
}

static void on_set_machine(const wxChar* value, HeeksObj* object)
{
	((CProgram*)object)->m_machine = value;
	CNCConfig config;
	config.Write(_T("ProgramMachine"), ((CProgram*)object)->m_machine);
}

static void on_set_output_file(const wxChar* value, HeeksObj* object)
{
	((CProgram*)object)->m_output_file = value;
	CNCConfig config;
	config.Write(_T("ProgramOutputFile"), ((CProgram*)object)->m_output_file);
}

void CProgram::GetProperties(std::list<Property *> *list)
{
	list->push_back(new PropertyString(_("machine"), m_machine, this, on_set_machine));
	list->push_back(new PropertyString(_("output file"), m_output_file, this, on_set_output_file));
	HeeksObj::GetProperties(list);
}

bool CProgram::CanAdd(HeeksObj* object)
{
	return object->GetType() == NCCodeType || object->GetType() == OperationsType;
}

bool CProgram::CanAddTo(HeeksObj* owner)
{
	return owner->GetType() == DocumentType;
}

void CProgram::SetClickMarkPoint(MarkedObject* marked_object, const double* ray_start, const double* ray_direction)
{
	if(marked_object->m_map.size() > 0)
	{
		MarkedObject* sub_marked_object = marked_object->m_map.begin()->second;
		if(sub_marked_object)
		{
			HeeksObj* object = sub_marked_object->m_map.begin()->first;
			if(object && object->GetType() == NCCodeType)
			{
				((CNCCode*)object)->SetClickMarkPoint(sub_marked_object, ray_start, ray_direction);
			}
		}
	}
}

void CProgram::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = new TiXmlElement( "Program" );
	root->LinkEndChild( element );
	element->SetAttribute("machine", Ttc(m_machine.c_str()));
	element->SetAttribute("output_file", Ttc(m_output_file.c_str()));
	element->SetAttribute("program", Ttc(theApp.m_program_canvas->m_textCtrl->GetValue()));

	WriteBaseXML(element);
}

bool CProgram::Add(HeeksObj* object, HeeksObj* prev_object)
{
	if(object->GetType() == NCCodeType)m_nc_code = (CNCCode*)object;
	if(object->GetType() == OperationsType)m_operations = (COperations*)object;
	return ObjList::Add(object, prev_object);
}

void CProgram::Remove(HeeksObj* object)
{
	 // these shouldn't happen, though
	if(object == m_nc_code)m_nc_code = NULL;
	else if(object == m_operations)m_operations = NULL;

	ObjList::Remove(object);
}

// static member function
HeeksObj* CProgram::ReadFromXMLElement(TiXmlElement* pElem)
{
	CProgram* new_object = new CProgram;

	// get the attributes
	for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
	{
		std::string name(a->Name());
		if(name == "machine"){new_object->m_machine.assign(Ctt(a->Value()));}
		else if(name == "output_file"){new_object->m_output_file.assign(Ctt(a->Value()));}
		else if(name == "program"){theApp.m_program_canvas->m_textCtrl->SetValue(Ctt(a->Value()));}
	}

	new_object->ReadBaseXML(pElem);
	theApp.m_program = new_object;

	return new_object;
}

void CProgram::RewritePythonProgram()
{
	theApp.m_program_canvas->m_textCtrl->Clear();
	CZigZag::number_for_stl_file = 1;
	CAdaptive::number_for_stl_file = 1;

	bool profile_op_exists = false;
	bool pocket_op_exists = false;
	bool zigzag_op_exists = false;
	bool adaptive_op_exists = false;
	for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
	{
		if(object->GetType() == ProfileType)
		{
			if(((CProfile*)object)->m_active)profile_op_exists = true;
		}
		else if(object->GetType() == PocketType)
		{
			if(((CPocket*)object)->m_active)pocket_op_exists = true;
		}
		else if(object->GetType() == ZigZagType)
		{
			if(((CZigZag*)object)->m_active)zigzag_op_exists = true;
		}
		else if(object->GetType() == AdaptiveType)
		{
			if(((CAdaptive*)object)->m_active)adaptive_op_exists = true;
		}
	}

	// add standard stuff at the top

	// kurve related things
	if(profile_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import kurve_funcs\n"));
	}

	// area related things
	if(pocket_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import area_funcs\n"));
	}

	// pycam stuff
	if(zigzag_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import sys\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("sys.path.insert(0,'PyCam/trunk')\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Geometry import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.SphericalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.CylindricalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Cutters.ToroidalCutter import *\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.Importers.STLImporter import ImportModel\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from pycam.PathGenerators.DropCutter import DropCutter\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("from PyCamToHeeks import HeeksCNCExporter\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
	}

	// actp
	if(adaptive_op_exists)
	{
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp_funcs\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("import actp\n"));
		theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));
	}

	// machine general stuff
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("from nc.nc import *\n"));

	// specific machine
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("import ") + m_machine + _T("\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));

	// output file
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("output('") + m_output_file + _T("')\n"));

	// begin program
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("program_begin(123, 'Test program')\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("absolute()\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("metric()\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("set_plane(0)\n"));
	theApp.m_program_canvas->m_textCtrl->AppendText(_T("\n"));

	// write the operations
	for(HeeksObj* object = m_operations->GetFirstChild(); object; object = m_operations->GetNextChild())
	{
		switch(object->GetType())
		{
		case ProfileType:
			if(((CProfile*)object)->m_active)((CProfile*)object)->AppendTextToProgram();
			break;
		case PocketType:
			if(((CPocket*)object)->m_active)((CPocket*)object)->AppendTextToProgram();
			break;
		case ZigZagType:
			if(((CZigZag*)object)->m_active)((CZigZag*)object)->AppendTextToProgram();
			break;
		case AdaptiveType:
			if(((CAdaptive*)object)->m_active)((CAdaptive*)object)->AppendTextToProgram();
			break;
		}
	}
}

ProgramUserType CProgram::GetUserType()
{
	if(m_nc_code->m_user_edited)return ProgramUserTypeNC;
	if(m_script_edited)return ProgramUserTypeScript;
	if(m_operations->GetFirstChild())return ProgramUserTypeTree;
	return ProgramUserTypeUnkown;
}

void CProgram::UpdateFromUserType()
{
#if 0
	switch(GetUserType())
	{
	case ProgramUserTypeUnkown:

	case tree:
   Enable "Operations" icon in tree
     editing the tree, recreates the python script
   Read only "Program" window
     pressing "Post-process" creates the NC code ( and backplots it )
   Read only "Output" window
   Disable all buttons on "Output" window

	}
#endif
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/video_coding/h264_sprop_parameter_sets.h"

#include <string>
#include <vector>

#include "webrtc/base/base64.h"
#include "webrtc/base/basictypes.h"
#include "webrtc/base/logging.h"

namespace {

bool DecodeAndConvert(const std::string& base64, std::vector<uint8_t>* binary) {
  // TODO(johan): Directly decode to std::vector<uint8_t> when available.
  std::vector<char> tmp;
  if (!rtc::Base64::DecodeFromArray(base64.data(), base64.size(),
                                    rtc::Base64::DO_STRICT, &tmp, nullptr)) {
    return false;
  }
  const uint8_t* data = reinterpret_cast<uint8_t*>(tmp.data());
  binary->assign(data, data + tmp.size());
  return true;
}
}  // namespace

namespace webrtc {

bool H264SpropParameterSets::DecodeSprop(const std::string& sprop) {
  size_t separator_pos = sprop.find(',');
  if ((separator_pos <= 0) || (separator_pos >= sprop.length() - 1)) {
    LOG(LS_WARNING) << "Invalid seperator position " << separator_pos << " *"
                    << sprop << "*";
    return false;
  }
  std::string sps_str = sprop.substr(0, separator_pos);
  std::string pps_str = sprop.substr(separator_pos + 1, std::string::npos);
  if (!DecodeAndConvert(sps_str, &sps_)) {
    LOG(LS_WARNING) << "Failed to decode sprop/sps *" << sprop << "*";
    return false;
  }
  if (!DecodeAndConvert(pps_str, &pps_)) {
    LOG(LS_WARNING) << "Failed to decode sprop/pps *" << sprop << "*";
    return false;
  }
  return true;
}

}  // namespace webrtc
<commit_msg>Remove static cast from H264SpropParameterSets.<commit_after>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/video_coding/h264_sprop_parameter_sets.h"

#include <string>
#include <vector>

#include "webrtc/base/base64.h"
#include "webrtc/base/basictypes.h"
#include "webrtc/base/logging.h"

namespace {

bool DecodeAndConvert(const std::string& base64, std::vector<uint8_t>* binary) {
  return rtc::Base64::DecodeFromArray(base64.data(), base64.size(),
                                      rtc::Base64::DO_STRICT, binary, nullptr);
}
}  // namespace

namespace webrtc {

bool H264SpropParameterSets::DecodeSprop(const std::string& sprop) {
  size_t separator_pos = sprop.find(',');
  if ((separator_pos <= 0) || (separator_pos >= sprop.length() - 1)) {
    LOG(LS_WARNING) << "Invalid seperator position " << separator_pos << " *"
                    << sprop << "*";
    return false;
  }
  std::string sps_str = sprop.substr(0, separator_pos);
  std::string pps_str = sprop.substr(separator_pos + 1, std::string::npos);
  if (!DecodeAndConvert(sps_str, &sps_)) {
    LOG(LS_WARNING) << "Failed to decode sprop/sps *" << sprop << "*";
    return false;
  }
  if (!DecodeAndConvert(pps_str, &pps_)) {
    LOG(LS_WARNING) << "Failed to decode sprop/pps *" << sprop << "*";
    return false;
  }
  return true;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: nadavs@google.com <Nadav Samet>

#include <iostream>
#include "rpcz/rpcz.hpp"
#include "cpp/search.pb.h"
#include "cpp/search.rpcz.h"

using namespace std;

int main() {
  examples::SearchService_Stub search_stub("tcp://localhost:5555");
  examples::SearchRequest request;
  request.set_query("gold");

  cout << "Sending request." << endl;
  try {
    examples::SearchResponse response;
        = search_stub.Search(request, 1000);
    cout << response.DebugString() << endl;
  } catch (rpcz::rpc_error &e) {
    cout << "Error: " << e.what() << endl;;
  }
}
<commit_msg>fix build<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: nadavs@google.com <Nadav Samet>

#include <iostream>
#include "rpcz/rpcz.hpp"
#include "cpp/search.pb.h"
#include "cpp/search.rpcz.h"

using namespace std;

int main() {
  examples::SearchService_Stub search_stub("tcp://localhost:5555");
  examples::SearchRequest request;
  request.set_query("gold");

  cout << "Sending request." << endl;
  try {
    examples::SearchResponse response
        = search_stub.Search(request, 1000);
    cout << response.DebugString() << endl;
  } catch (rpcz::rpc_error &e) {
    cout << "Error: " << e.what() << endl;;
  }
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <ros/network.h>
#include <string>
#include <std_msgs/String.h>
#include <sstream>
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>
#include "../include/map_marker/qnode.hpp"

namespace map_marker {

QNode::QNode(int argc, char** argv ) :
	init_argc(argc),
	init_argv(argv)
	{}

QNode::~QNode() {
    if(ros::isStarted()) {
      ros::shutdown(); // explicitly needed since we use ros::start();
      ros::waitForShutdown();
    }
	wait();
}

bool QNode::init() {
	ros::init(init_argc,init_argv,"map_marker");
	if ( ! ros::master::check() ) {
		return false;
	}
	ros::start();
	ros::NodeHandle n;
	marker_publisher = n.advertise<geometry_msgs::PoseStamped>("/move_base_simple/goal", 100);
	start();
	return true;
}

bool QNode::init(const std::string &master_url, const std::string &host_url) {
	std::map<std::string,std::string> remappings;
	remappings["__master"] = master_url;
	remappings["__hostname"] = host_url;
	ros::init(remappings,"map_marker");
	if ( ! ros::master::check() ) {
		return false;
	}
	ros::start();
	ros::NodeHandle n;
	marker_publisher = n.advertise<geometry_msgs::PoseStamped>("/move_base_simple/goal", 100);
	start();
	return true;
}

void QNode::run() {
	ros::Rate rate(1);
	int count = 0;

	tf::TransformListener tflistener;

	while (ros::ok()) {
		tf::StampedTransform transform;
		try {
			geometry_msgs::Quaternion q;
			tflistener.lookupTransform("/odom", "/base_link", ros::Time(0), transform);
			pose.position.x = transform.getOrigin().x();
			pose.position.y = transform.getOrigin().y();
			pose.position.z = transform.getOrigin().z();
			tf::quaternionTFToMsg(transform.getRotation(), q);
			pose.orientation = q;

			std::cout << "x: " << transform.getOrigin().x() << ", y:" << transform.getOrigin().y() << ", z: "<< transform.getOrigin().y() << std::endl;
			std::cout << "x: " << q.x << ", y:" << q.y << ", z: " << q.z << ", w: " << q.w << std::endl << std::endl;

		}
		catch (tf::TransformException ex){
		  //ROS_ERROR("%s",ex.what());
		  ros::Duration(1.0).sleep();
		}
		ros::spinOnce();
		rate.sleep();
	}

	std::cout << "Ros shutdown, proceeding to close the gui." << std::endl;
	Q_EMIT rosShutdown(); // used to signal the gui for a shutdown (useful to roslaunch)
}

geometry_msgs::Pose QNode::GetRobotPosition() {
	// TODO: IMPLEMENTATION

	geometry_msgs::Pose p;
	p.position.x = 5;
	p.position.y = 8;
	p.position.z = 0;
	p.orientation.z = 1;
	return p;
}

void QNode::MoveRobotToPose(geometry_msgs::Pose pos) {
	// TODO: IMPLEMENTATION

	ROS_INFO("xpos: %f", pos.position.x);

	geometry_msgs::PoseStamped p;
	p.pose = pos;

	marker_publisher.publish(p);
}

void QNode::log( const LogLevel &level, const std::string &msg) {
	logging_model.insertRows(logging_model.rowCount(),1);
	std::stringstream logging_model_msg;
	switch ( level ) {
		case(Debug) : {
				ROS_DEBUG_STREAM(msg);
				logging_model_msg << "[DEBUG] [" << ros::Time::now() << "]: " << msg;
				break;
		}
		case(Info) : {
				ROS_INFO_STREAM(msg);
				logging_model_msg << "[INFO] [" << ros::Time::now() << "]: " << msg;
				break;
		}
		case(Warn) : {
				ROS_WARN_STREAM(msg);
				logging_model_msg << "[INFO] [" << ros::Time::now() << "]: " << msg;
				break;
		}
		case(Error) : {
				ROS_ERROR_STREAM(msg);
				logging_model_msg << "[ERROR] [" << ros::Time::now() << "]: " << msg;
				break;
		}
		case(Fatal) : {
				ROS_FATAL_STREAM(msg);
				logging_model_msg << "[FATAL] [" << ros::Time::now() << "]: " << msg;
				break;
		}
	}
	QVariant new_row(QString(logging_model_msg.str().c_str()));
	logging_model.setData(logging_model.index(logging_model.rowCount()-1),new_row);
	Q_EMIT loggingUpdated(); // used to readjust the scrollbar
}

}  // namespace map_marker
<commit_msg>Message<commit_after>#include <ros/ros.h>
#include <ros/network.h>
#include <string>
#include <std_msgs/String.h>
#include <sstream>
#include <tf/transform_listener.h>
#include <tf/transform_datatypes.h>
#include "../include/map_marker/qnode.hpp"

namespace map_marker {

QNode::QNode(int argc, char** argv ) :
	init_argc(argc),
	init_argv(argv)
	{}

QNode::~QNode() {
    if(ros::isStarted()) {
      ros::shutdown(); // explicitly needed since we use ros::start();
      ros::waitForShutdown();
    }
	wait();
}

bool QNode::init() {
	ros::init(init_argc,init_argv,"map_marker");
	if ( ! ros::master::check() ) {
		return false;
	}
	ros::start();
	ros::NodeHandle n;
	marker_publisher = n.advertise<geometry_msgs::PoseStamped>("/move_base_simple/goal", 100);
	start();
	return true;
}

bool QNode::init(const std::string &master_url, const std::string &host_url) {
	std::map<std::string,std::string> remappings;
	remappings["__master"] = master_url;
	remappings["__hostname"] = host_url;
	ros::init(remappings,"map_marker");
	if ( ! ros::master::check() ) {
		return false;
	}
	ros::start();
	ros::NodeHandle n;
	marker_publisher = n.advertise<geometry_msgs::PoseStamped>("/move_base_simple/goal", 100);
	start();
	return true;
}

void QNode::run() {
	ros::Rate rate(1);
	int count = 0;

	tf::TransformListener tflistener;

	while (ros::ok()) {
		tf::StampedTransform transform;
		try {
			geometry_msgs::Quaternion q;
			tflistener.lookupTransform("/odom", "/base_link", ros::Time(0), transform);
			pose.position.x = transform.getOrigin().x();
			pose.position.y = transform.getOrigin().y();
			pose.position.z = transform.getOrigin().z();
			tf::quaternionTFToMsg(transform.getRotation(), q);
			pose.orientation = q;

			std::cout << "x: " << transform.getOrigin().x() << ", y:" << transform.getOrigin().y() << ", z: "<< transform.getOrigin().y() << std::endl;
			std::cout << "x: " << q.x << ", y:" << q.y << ", z: " << q.z << ", w: " << q.w << std::endl << std::endl;

		}
		catch (tf::TransformException ex){
		  //ROS_ERROR("%s",ex.what());
		  ros::Duration(1.0).sleep();
		}
		ros::spinOnce();
		rate.sleep();
	}

	std::cout << "Ros shutdown, proceeding to close the gui." << std::endl;
	Q_EMIT rosShutdown(); // used to signal the gui for a shutdown (useful to roslaunch)
}

geometry_msgs::Pose QNode::GetRobotPosition() {
	// TODO: IMPLEMENTATION

	geometry_msgs::Pose p;
	p.position.x = 5;
	p.position.y = 8;
	p.position.z = 0;
	p.orientation.z = 1;
	return pose;
}

void QNode::MoveRobotToPose(geometry_msgs::Pose pos) {
	// TODO: IMPLEMENTATION

	ROS_INFO("xpos: %f", pos.position.x);

	geometry_msgs::PoseStamped p;
	p.header.stamp = ros::Time::now();
	p.header.frame_id = "map";
	p.pose = pos;

	marker_publisher.publish(p);
}

void QNode::log( const LogLevel &level, const std::string &msg) {
	logging_model.insertRows(logging_model.rowCount(),1);
	std::stringstream logging_model_msg;
	switch ( level ) {
		case(Debug) : {
				ROS_DEBUG_STREAM(msg);
				logging_model_msg << "[DEBUG] [" << ros::Time::now() << "]: " << msg;
				break;
		}
		case(Info) : {
				ROS_INFO_STREAM(msg);
				logging_model_msg << "[INFO] [" << ros::Time::now() << "]: " << msg;
				break;
		}
		case(Warn) : {
				ROS_WARN_STREAM(msg);
				logging_model_msg << "[INFO] [" << ros::Time::now() << "]: " << msg;
				break;
		}
		case(Error) : {
				ROS_ERROR_STREAM(msg);
				logging_model_msg << "[ERROR] [" << ros::Time::now() << "]: " << msg;
				break;
		}
		case(Fatal) : {
				ROS_FATAL_STREAM(msg);
				logging_model_msg << "[FATAL] [" << ros::Time::now() << "]: " << msg;
				break;
		}
	}
	QVariant new_row(QString(logging_model_msg.str().c_str()));
	logging_model.setData(logging_model.index(logging_model.rowCount()-1),new_row);
	Q_EMIT loggingUpdated(); // used to readjust the scrollbar
}

}  // namespace map_marker
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Library
  Module:    Renderer.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Renderer.hh"
#include "RenderW.hh"

vlRenderer::vlRenderer()
{
  this->ActiveCamera = NULL;

  this->Ambient[0] = 1;
  this->Ambient[1] = 1;
  this->Ambient[2] = 1;

  this->Background[0] = 0;
  this->Background[1] = 0;
  this->Background[2] = 0;

  this->DisplayPoint[0] = 0;
  this->DisplayPoint[1] = 0;
  this->DisplayPoint[2] = 0;

  this->ViewPoint[0] = 0;
  this->ViewPoint[1] = 0;
  this->ViewPoint[2] = 0;

  this->Viewport[0] = 0;
  this->Viewport[1] = 0;
  this->Viewport[2] = 1;
  this->Viewport[3] = 1;

  this->BackLight = 1;
  this->Erase = 1;
  this->StereoRender = 0;

  this->Aspect[0] = this->Aspect[1] = 1.0;
}

void vlRenderer::SetActiveCamera(vlCamera *cam)
{
  this->ActiveCamera = cam;
}

vlCamera *vlRenderer::GetActiveCamera()
{
  return this->ActiveCamera;
}

void vlRenderer::AddLights(vlLight *light)
{
  this->Lights.AddMember(light);
}

void vlRenderer::AddActors(vlActor *actor)
{
  this->Actors.AddMember(actor);
}

void vlRenderer::DoLights()
{
  vlLight *light1;

  if (!this->UpdateLights())
    {
    cerr << this->GetClassName() << " : No lights are on, creating one.\n";
    light1 = this->RenderWindow->MakeLight();
    this->AddLights(light1);
    light1->SetPosition(this->ActiveCamera->GetPosition());
    light1->SetFocalPoint(this->ActiveCamera->GetFocalPoint());
    this->UpdateLights();
    }
}

void vlRenderer::DoCameras()
{
  vlCamera *cam1;

  if (!this->UpdateCameras())
    {
    cerr << this->GetClassName() << " : No cameras are on, creating one.\n";
    cam1 = this->RenderWindow->MakeCamera();
    this->SetActiveCamera(cam1);
    this->ResetCamera();
    this->UpdateCameras();
    }
}

void vlRenderer::DoActors()
{

  if (!this->UpdateActors())
    {
    cerr << "No actors are on.\n";
    }
}

void vlRenderer::ResetCamera()
{
  vlActor *anActor;
  int num;
  float *bounds;
  float all_bounds[6];
  float center[3];
  float distance;
  float width;

  all_bounds[0] = all_bounds[2] = all_bounds[4] = LARGE_FLOAT;
  all_bounds[1] = all_bounds[3] = all_bounds[5] = -LARGE_FLOAT;

  // loop through actors
  for (num = 1; num <= this->Actors.GetNumberOfMembers(); num++)
    {
    anActor = this->Actors.GetMember(num);

    // if it's invisible, we can skip the rest
    if ( anActor->GetVisibility() )
      {
      bounds = anActor->GetBounds();

      if (bounds[0] < all_bounds[0]) all_bounds[0] = bounds[0];
      if (bounds[1] > all_bounds[1]) all_bounds[1] = bounds[1];
      if (bounds[2] < all_bounds[2]) all_bounds[2] = bounds[2];
      if (bounds[3] > all_bounds[3]) all_bounds[3] = bounds[3];
      if (bounds[4] < all_bounds[4]) all_bounds[4] = bounds[4];
      if (bounds[5] > all_bounds[5]) all_bounds[5] = bounds[5];
      }
    }

  // now we have the bounds for all actors
  center[0] = (all_bounds[0] + all_bounds[1])/2.0;
  center[1] = (all_bounds[2] + all_bounds[3])/2.0;
  center[2] = (all_bounds[4] + all_bounds[5])/2.0;

  width = all_bounds[3] - all_bounds[2];
  if (width < (all_bounds[1] - all_bounds[0]))
    {
    width = all_bounds[1] - all_bounds[0];
    }
  distance = 0.8*width/tan(this->ActiveCamera->GetViewAngle()*M_PI/360.0);
  distance = distance + (all_bounds[5] - all_bounds[4])/2.0;

  // update the camera
  this->ActiveCamera->SetFocalPoint(center);
  this->ActiveCamera->SetPosition(center[0],center[1],center[2]+distance);
  this->ActiveCamera->SetViewUp(0,1,0);
  this->ActiveCamera->SetClippingRange(distance/10.0,distance*5.0);
}

void vlRenderer::SetRenderWindow(vlRenderWindow *renwin)
{
  this->RenderWindow = renwin;
}

void vlRenderer::DisplayToView()
{
  float vx,vy,vz;
  int sizex,sizey;
  int *size;

  /* get physical window dimensions */
  size = this->RenderWindow->GetSize();
  sizex = size[0];
  sizey = size[1];

  vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
    (sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
  vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
    (sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
  vz = this->DisplayPoint[2];

  this->SetViewPoint(vx*this->Aspect[0],vy*this->Aspect[1],vz);
}

void vlRenderer::ViewToDisplay()
{
  int dx,dy;
  int sizex,sizey;
  int *size;

  /* get physical window dimensions */
  size = this->RenderWindow->GetSize();
  sizex = size[0];
  sizey = size[1];

  dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
    (sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 + 0.5 +
      sizex*this->Viewport[0]);
  dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
    (sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 + 0.5 +
      sizey*this->Viewport[1]);

  this->SetDisplayPoint(dx,dy,this->ViewPoint[2]);
}

void vlRenderer::ViewToWorld()
{
  vlMatrix4x4 mat;
  float result[4];

  // get the perspective transformation from the active camera
  mat = this->ActiveCamera->GetPerspectiveTransform();

  // use the inverse matrix
  mat.Invert();

  // Transform point to world coordinates
  result[0] = this->ViewPoint[0];
  result[1] = this->ViewPoint[1];
  result[2] = this->ViewPoint[2];
  result[3] = 1.0;

  mat.VectorMultiply(result,result);

  // Get the transformed vector & set WorldPoint
  this->SetWorldPoint(result);
}

void vlRenderer::WorldToView()
{
  vlMatrix4x4 matrix;
  float     view[4];
  float     *world;

  // get the perspective transformation from the active camera
  matrix = this->ActiveCamera->GetPerspectiveTransform();

  world = this->WorldPoint;
  view[0] = world[0]*matrix[0][0] + world[1]*matrix[1][0] +
    world[2]*matrix[2][0] + world[3]*matrix[3][0];
  view[1] = world[0]*matrix[0][1] + world[1]*matrix[1][1] +
    world[2]*matrix[2][1] + world[3]*matrix[3][1];
  view[2] = world[0]*matrix[0][2] + world[1]*matrix[1][2] +
    world[2]*matrix[2][2] + world[3]*matrix[3][2];
  view[3] = world[0]*matrix[0][3] + world[1]*matrix[1][3] +
    world[2]*matrix[2][3] + world[3]*matrix[3][3];

  if (view[3] != 0.0)
    {
    this->SetViewPoint(view[0]/view[3],
		       view[1]/view[3],
		       view[2]/view[3]);
    }
}

void vlRenderer::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlRenderer::GetClassName()))
    {
    this->vlObject::PrintSelf(os,indent);

    os << indent << "Actors:\n";
    this->Actors.PrintSelf(os,indent.GetNextIndent());
    os << indent << "Ambient: (" << this->Ambient[0] << ", "
      << this->Ambient[1] << ", " << this->Ambient[2] << ")\n";
    os << indent << "Aspect: (" << this->Aspect[0] << ", "
      << this->Aspect[1] << ")\n";
    os << indent << "Background: (" << this->Background[0] << ", "
      << this->Background[1] << ", "  << this->Background[2] << ")\n";

    os << indent << "Back Light: " << (this->BackLight ? "On\n" : "Off\n");
    os << indent << "DisplayPoint: ("  << this->DisplayPoint[0] << ", "
      << this->DisplayPoint[1] << ", " << this->DisplayPoint[2] << ")\n";
    os << indent << "Erase: " << (this->Erase ? "On\n" : "Off\n");
    os << indent << "Lights:\n";
    this->Lights.PrintSelf(os,indent.GetNextIndent());
    os << indent << "Stereo Render: "
      << (this->StereoRender ? "On\n":"Off\n");

    os << indent << "ViewPoint: (" << this->ViewPoint[0] << ", "
      << this->ViewPoint[1] << ", " << this->ViewPoint[2] << ")\n";
    os << indent << "Viewport: (" << this->Viewport[0] << ", "
      << this->Viewport[1] << ", " << this->Viewport[2] << ", "
	<< this->Viewport[3] << ")\n";
    }
}

<commit_msg>ENH: Replace cerr with vlErrorMacro...<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    Renderer.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Renderer.hh"
#include "RenderW.hh"

vlRenderer::vlRenderer()
{
  this->ActiveCamera = NULL;

  this->Ambient[0] = 1;
  this->Ambient[1] = 1;
  this->Ambient[2] = 1;

  this->Background[0] = 0;
  this->Background[1] = 0;
  this->Background[2] = 0;

  this->DisplayPoint[0] = 0;
  this->DisplayPoint[1] = 0;
  this->DisplayPoint[2] = 0;

  this->ViewPoint[0] = 0;
  this->ViewPoint[1] = 0;
  this->ViewPoint[2] = 0;

  this->Viewport[0] = 0;
  this->Viewport[1] = 0;
  this->Viewport[2] = 1;
  this->Viewport[3] = 1;

  this->BackLight = 1;
  this->Erase = 1;
  this->StereoRender = 0;

  this->Aspect[0] = this->Aspect[1] = 1.0;
}

void vlRenderer::SetActiveCamera(vlCamera *cam)
{
  this->ActiveCamera = cam;
}

vlCamera *vlRenderer::GetActiveCamera()
{
  return this->ActiveCamera;
}

void vlRenderer::AddLights(vlLight *light)
{
  this->Lights.AddMember(light);
}

void vlRenderer::AddActors(vlActor *actor)
{
  this->Actors.AddMember(actor);
}

void vlRenderer::DoLights()
{
  vlLight *light1;

  if (!this->UpdateLights())
    {
    vlErrorMacro(<<"No lights are on, creating one.");
    light1 = this->RenderWindow->MakeLight();
    this->AddLights(light1);
    light1->SetPosition(this->ActiveCamera->GetPosition());
    light1->SetFocalPoint(this->ActiveCamera->GetFocalPoint());
    this->UpdateLights();
    }
}

void vlRenderer::DoCameras()
{
  vlCamera *cam1;

  if (!this->UpdateCameras())
    {
    vlErrorMacro(<< "No cameras are on, creating one.");
    cam1 = this->RenderWindow->MakeCamera();
    this->SetActiveCamera(cam1);
    this->ResetCamera();
    this->UpdateCameras();
    }
}

void vlRenderer::DoActors()
{

  if (!this->UpdateActors())
    {
    vlErrorMacro(<< "No actors are on.");
    }
}

void vlRenderer::ResetCamera()
{
  vlActor *anActor;
  int num;
  float *bounds;
  float all_bounds[6];
  float center[3];
  float distance;
  float width;

  all_bounds[0] = all_bounds[2] = all_bounds[4] = LARGE_FLOAT;
  all_bounds[1] = all_bounds[3] = all_bounds[5] = -LARGE_FLOAT;

  // loop through actors
  for (num = 1; num <= this->Actors.GetNumberOfMembers(); num++)
    {
    anActor = this->Actors.GetMember(num);

    // if it's invisible, we can skip the rest
    if ( anActor->GetVisibility() )
      {
      bounds = anActor->GetBounds();

      if (bounds[0] < all_bounds[0]) all_bounds[0] = bounds[0];
      if (bounds[1] > all_bounds[1]) all_bounds[1] = bounds[1];
      if (bounds[2] < all_bounds[2]) all_bounds[2] = bounds[2];
      if (bounds[3] > all_bounds[3]) all_bounds[3] = bounds[3];
      if (bounds[4] < all_bounds[4]) all_bounds[4] = bounds[4];
      if (bounds[5] > all_bounds[5]) all_bounds[5] = bounds[5];
      }
    }

  // now we have the bounds for all actors
  center[0] = (all_bounds[0] + all_bounds[1])/2.0;
  center[1] = (all_bounds[2] + all_bounds[3])/2.0;
  center[2] = (all_bounds[4] + all_bounds[5])/2.0;

  width = all_bounds[3] - all_bounds[2];
  if (width < (all_bounds[1] - all_bounds[0]))
    {
    width = all_bounds[1] - all_bounds[0];
    }
  distance = 0.8*width/tan(this->ActiveCamera->GetViewAngle()*M_PI/360.0);
  distance = distance + (all_bounds[5] - all_bounds[4])/2.0;

  // update the camera
  this->ActiveCamera->SetFocalPoint(center);
  this->ActiveCamera->SetPosition(center[0],center[1],center[2]+distance);
  this->ActiveCamera->SetViewUp(0,1,0);
  this->ActiveCamera->SetClippingRange(distance/10.0,distance*5.0);
}

void vlRenderer::SetRenderWindow(vlRenderWindow *renwin)
{
  this->RenderWindow = renwin;
}

void vlRenderer::DisplayToView()
{
  float vx,vy,vz;
  int sizex,sizey;
  int *size;

  /* get physical window dimensions */
  size = this->RenderWindow->GetSize();
  sizex = size[0];
  sizey = size[1];

  vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
    (sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
  vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
    (sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
  vz = this->DisplayPoint[2];

  this->SetViewPoint(vx*this->Aspect[0],vy*this->Aspect[1],vz);
}

void vlRenderer::ViewToDisplay()
{
  int dx,dy;
  int sizex,sizey;
  int *size;

  /* get physical window dimensions */
  size = this->RenderWindow->GetSize();
  sizex = size[0];
  sizey = size[1];

  dx = (int)((this->ViewPoint[0]/this->Aspect[0] + 1.0) *
    (sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 + 0.5 +
      sizex*this->Viewport[0]);
  dy = (int)((this->ViewPoint[1]/this->Aspect[1] + 1.0) *
    (sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 + 0.5 +
      sizey*this->Viewport[1]);

  this->SetDisplayPoint(dx,dy,this->ViewPoint[2]);
}

void vlRenderer::ViewToWorld()
{
  vlMatrix4x4 mat;
  float result[4];

  // get the perspective transformation from the active camera
  mat = this->ActiveCamera->GetPerspectiveTransform();

  // use the inverse matrix
  mat.Invert();

  // Transform point to world coordinates
  result[0] = this->ViewPoint[0];
  result[1] = this->ViewPoint[1];
  result[2] = this->ViewPoint[2];
  result[3] = 1.0;

  mat.VectorMultiply(result,result);

  // Get the transformed vector & set WorldPoint
  this->SetWorldPoint(result);
}

void vlRenderer::WorldToView()
{
  vlMatrix4x4 matrix;
  float     view[4];
  float     *world;

  // get the perspective transformation from the active camera
  matrix = this->ActiveCamera->GetPerspectiveTransform();

  world = this->WorldPoint;
  view[0] = world[0]*matrix[0][0] + world[1]*matrix[1][0] +
    world[2]*matrix[2][0] + world[3]*matrix[3][0];
  view[1] = world[0]*matrix[0][1] + world[1]*matrix[1][1] +
    world[2]*matrix[2][1] + world[3]*matrix[3][1];
  view[2] = world[0]*matrix[0][2] + world[1]*matrix[1][2] +
    world[2]*matrix[2][2] + world[3]*matrix[3][2];
  view[3] = world[0]*matrix[0][3] + world[1]*matrix[1][3] +
    world[2]*matrix[2][3] + world[3]*matrix[3][3];

  if (view[3] != 0.0)
    {
    this->SetViewPoint(view[0]/view[3],
		       view[1]/view[3],
		       view[2]/view[3]);
    }
}

void vlRenderer::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlRenderer::GetClassName()))
    {
    this->vlObject::PrintSelf(os,indent);

    os << indent << "Actors:\n";
    this->Actors.PrintSelf(os,indent.GetNextIndent());
    os << indent << "Ambient: (" << this->Ambient[0] << ", "
      << this->Ambient[1] << ", " << this->Ambient[2] << ")\n";
    os << indent << "Aspect: (" << this->Aspect[0] << ", "
      << this->Aspect[1] << ")\n";
    os << indent << "Background: (" << this->Background[0] << ", "
      << this->Background[1] << ", "  << this->Background[2] << ")\n";

    os << indent << "Back Light: " << (this->BackLight ? "On\n" : "Off\n");
    os << indent << "DisplayPoint: ("  << this->DisplayPoint[0] << ", "
      << this->DisplayPoint[1] << ", " << this->DisplayPoint[2] << ")\n";
    os << indent << "Erase: " << (this->Erase ? "On\n" : "Off\n");
    os << indent << "Lights:\n";
    this->Lights.PrintSelf(os,indent.GetNextIndent());
    os << indent << "Stereo Render: "
      << (this->StereoRender ? "On\n":"Off\n");

    os << indent << "ViewPoint: (" << this->ViewPoint[0] << ", "
      << this->ViewPoint[1] << ", " << this->ViewPoint[2] << ")\n";
    os << indent << "Viewport: (" << this->Viewport[0] << ", "
      << this->Viewport[1] << ", " << this->Viewport[2] << ", "
	<< this->Viewport[3] << ")\n";
    }
}

<|endoftext|>


<commit_before>#ifndef AST_DECLARATIONS_TYPE_HH
# define AST_DECLARATIONS_TYPE_HH

# include <deque>
# include <iosfwd>

# include <ast/declaration.hh>

namespace ast
{

  /// List of expressions, for List, Nary, Call etc.
  typedef std::deque<rDeclaration> declarations_type;

  /// Separated by commas.
  std::ostream& operator<<(std::ostream& o, const ast::declarations_type& ss);

}

#endif // ! AST_DECLARATIONS_TYPE_HH
<commit_msg>Fix comment about declarations_type.<commit_after>#ifndef AST_DECLARATIONS_TYPE_HH
# define AST_DECLARATIONS_TYPE_HH

# include <deque>
# include <iosfwd>

# include <ast/declaration.hh>

namespace ast
{

  /// List of declarations
  typedef std::deque<rDeclaration> declarations_type;

  /// Separated by commas.
  std::ostream& operator<<(std::ostream& o, const ast::declarations_type& ss);

}

#endif // ! AST_DECLARATIONS_TYPE_HH
<|endoftext|>


<commit_before>/*
Copyright (c) 2019,
Vahan Sosoyan.
All rights reserved. See COPYING.txt for more details.
*/

#include <string>
#include <vector>
#include <cstdlib>

#include <ai.h>
#include <stdio.h>

AI_OPERATOR_NODE_EXPORT_METHODS(AtonOperatorMtd);

const int get_port()
{
    const char* def_port = getenv("ATON_PORT");
    int aton_port;

    if (def_port == NULL)
        aton_port = 9201;
    else
        aton_port = atoi(def_port);

    return aton_port;
}

const std::string get_host()
{
    const char* def_host = getenv("ATON_HOST");

    if (def_host == NULL)
        def_host = "127.0.0.1";

    std::string aton_host = def_host;
    return aton_host;
}

std::vector<std::string> split(std::string str, std::string token)
{
    std::vector<std::string>result;
    while(str.size())
    {
        int index = static_cast<int>(str.find(token));

        if(index != std::string::npos)
        {
            result.push_back(str.substr(0, index));
            str = str.substr(index+token.size());

            if(str.size() == 0)
                result.push_back(str);
        }
        else
        {
            result.push_back(str);
            str = "";
        }
    }
    return result;
}

struct OpData
{
    AtString driver_name;
};

node_parameters
{
    AiParameterStr("host", get_host().c_str());
    AiParameterInt("port", get_port());
    AiParameterStr("output", "");

    AiParameterStr("bucket_scanning", "");

    AiParameterInt("region_min_x", 0);
    AiParameterInt("region_min_y", 0);
    AiParameterInt("region_max_x", 0);
    AiParameterInt("region_max_y", 0);

    AiParameterBool("ignore_motion_blur", false);
    AiParameterBool("ignore_subdivision", false);
    AiParameterBool("ignore_displacement", false);
    AiParameterBool("ignore_bump", false);
    AiParameterBool("ignore_sss", false);
}

operator_init
{
    OpData* data = (OpData*)AiMalloc(sizeof(OpData));

    data->driver_name = AtString("defaultAtonDriver");

    AtNode* driver = AiNode("driver_aton", data->driver_name);
    AiNodeSetStr(driver, "host", AiNodeGetStr(op, "host"));
    AiNodeSetInt(driver, "port", AiNodeGetInt(op, "port"));
    AiNodeSetStr(driver, "output", AiNodeGetStr(op, "output"));

    AiNodeSetLocalData(op, data);
    return true;
}

operator_cook
{
    OpData* data = (OpData*)AiNodeGetLocalData(op);

    AtNode* options = AiUniverseGetOptions();
    AtArray* outputs = AiNodeGetArray(options, "outputs");

    int elements = AiArrayGetNumElements(outputs);

    for (int i=0; i<elements; ++i)
    {
        std::string output_string = AiArrayGetStr(outputs, i).c_str();
        std::string name = split(output_string, std::string(" ")).back();
        output_string.replace(output_string.find(name), name.length(), std::string(data->driver_name));
        AiArraySetStr(outputs, i, AtString(output_string.c_str()));
    }
    return true;
}

operator_cleanup
{
    return true;
}

node_loader
{
    if (i>0) return 0;
    node->methods = (AtNodeMethods*)AtonOperatorMtd;
    node->name = "operator_aton";
    node->node_type = AI_NODE_OPERATOR;
    strcpy(node->version, AI_VERSION);
    return true;
}
<commit_msg>Adds options updates<commit_after>/*
Copyright (c) 2019,
Vahan Sosoyan.
All rights reserved. See COPYING.txt for more details.
*/

#include <string>
#include <vector>
#include <cstdlib>

#include <ai.h>
#include <stdio.h>

AI_OPERATOR_NODE_EXPORT_METHODS(AtonOperatorMtd);

const int get_port()
{
    const char* def_port = getenv("ATON_PORT");

    if (def_port == NULL)
        return 9201;

    return atoi(def_port);
}

const std::string get_host()
{
    const char* def_host = getenv("ATON_HOST");

    if (def_host == NULL)
        return std::string("127.0.0.1");

    return std::string(def_host);
}

std::vector<std::string> split(std::string str, std::string token)
{
    std::vector<std::string>result;
    while(str.size())
    {
        int index = static_cast<int>(str.find(token));

        if(index != std::string::npos)
        {
            result.push_back(str.substr(0, index));
            str = str.substr(index+token.size());

            if(str.size() == 0)
                result.push_back(str);
        }
        else
        {
            result.push_back(str);
            str = "";
        }
    }
    return result;
}

struct OpData
{
    AtString driver_name;
};

node_parameters
{
    AiParameterStr("host", get_host().c_str());
    AiParameterInt("port", get_port());
    AiParameterStr("output", "");
    AiParameterBool("overrides", false);
    AiParameterInt("AA_samples", 0);
    AiParameterInt("xres", 0);
    AiParameterInt("yres", 0);
    AiParameterBool("ignore_motion_blur", false);
    AiParameterBool("ignore_subdivision", false);
    AiParameterBool("ignore_displacement", false);
    AiParameterBool("ignore_bump", false);
    AiParameterBool("ignore_sss", false);
}

operator_init
{
    OpData* data = (OpData*)AiMalloc(sizeof(OpData));

    data->driver_name = AtString("defaultAtonDriver");

    AtNode* driver = AiNode("driver_aton", data->driver_name);

    AiNodeSetStr(driver, "host", AiNodeGetStr(op, "host"));
    AiNodeSetInt(driver, "port", AiNodeGetInt(op, "port"));
    AiNodeSetStr(driver, "output", AiNodeGetStr(op, "output"));
    AiNodeSetLocalData(op, data);

    return true;
}

operator_cook
{
    OpData* data = (OpData*)AiNodeGetLocalData(op);

    AtNode* options = AiUniverseGetOptions();
    AtArray* outputs = AiNodeGetArray(options, "outputs");

    int elements = AiArrayGetNumElements(outputs);

    for (int i=0; i<elements; ++i)
    {
        std::string output_string = AiArrayGetStr(outputs, i).c_str();
        std::string name = split(output_string, std::string(" ")).back();
        output_string.replace(output_string.find(name), name.length(), std::string(data->driver_name));
        AiArraySetStr(outputs, i, AtString(output_string.c_str()));
    }

    // One day this will start to work!
    if (AiNodeGetBool(op, "overrides"))
    {
        AiNodeSetInt(options, "AA_samples", AiNodeGetInt(op, "AA_samples"));
        AiNodeSetInt(options, "xres", AiNodeGetInt(op, "xres"));
        AiNodeSetInt(options, "yres", AiNodeGetInt(op, "yres"));
        AiNodeSetBool(options, "ignore_motion_blur", AiNodeGetBool(op, "ignore_motion_blur"));
        AiNodeSetBool(options, "ignore_subdivision", AiNodeGetBool(op, "ignore_motion_blur"));
        AiNodeSetBool(options, "ignore_displacement", AiNodeGetBool(op, "ignore_motion_blur"));
        AiNodeSetBool(options, "ignore_bump", AiNodeGetBool(op, "ignore_motion_blur"));
        AiNodeSetBool(options, "ignore_sss", AiNodeGetBool(op, "ignore_motion_blur"));
    }

    return true;
}

operator_post_cook
{
    return true;
}

operator_cleanup
{
    return true;
}

node_loader
{
    if (i>0) return 0;
    node->methods = (AtNodeMethods*)AtonOperatorMtd;
    node->name = "operator_aton";
    node->node_type = AI_NODE_OPERATOR;
    strcpy(node->version, AI_VERSION);
    return true;
}
<|endoftext|>