<commit_before>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS)
 *
 * This file is part of metaverse-server.
 *
 * metaverse-server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include "executor.hpp"

#include <algorithm>
#include <csignal>
#include <functional>
#include <future>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <metaverse/server.hpp>
#include <metaverse/bitcoin/utility/backtrace.hpp>
#include <metaverse/bitcoin/utility/path.hpp>

namespace libbitcoin {
namespace server {

using boost::format;
using namespace std::placeholders;
using namespace boost::system;
using namespace bc::config;
using namespace bc::database;
using namespace bc::network;

static constexpr int initialize_stop = 0;
static constexpr int directory_exists = 0;
static constexpr int directory_not_found = 2;
static constexpr auto append = std::ofstream::out | std::ofstream::app;
static const auto application_name = "bs";

std::promise<code> executor::stopping_;

executor::executor(parser& metadata, std::istream& input,
    std::ostream& output, std::ostream& error)
  : metadata_(metadata), output_(output),
    debug_file_((default_data_path() / metadata_.configured.network.debug_file).string(), append),
    error_file_((default_data_path() / metadata_.configured.network.error_file).string(), append)
{
    initialize_logging(debug_file_, error_file_, output, error);
    handle_stop(initialize_stop);
}

// Command line options.
// ----------------------------------------------------------------------------
// Emit directly to standard output (not the log).

void executor::do_help()
{
    const auto options = metadata_.load_options();
    printer help(options, application_name, BS_INFORMATION_MESSAGE);
    help.initialize();
    help.commandline(output_);
}

void executor::do_settings()
{
    const auto settings = metadata_.load_settings();
    printer print(settings, application_name, BS_SETTINGS_MESSAGE);
    print.initialize();
    print.settings(output_);
}

void executor::do_version()
{
    output_ << format(BS_VERSION_MESSAGE) %
        MVS_SERVER_VERSION %
        MVS_SERVER_VERSION %
        MVS_PROTOCOL_VERSION %
        MVS_NODE_VERSION %
        MVS_BLOCKCHAIN_VERSION %
        MVS_VERSION << std::endl;
}

void executor::set_admin()
{
	data_base db(metadata_.configured.database);
	db.start();
	db.set_admin("administerator", "mvsgo");
	db.stop();
}

// Emit to the log.
bool executor::do_initchain()
{
    initialize_output();

    boost::system::error_code ec;

    auto home_path = default_data_path();
    const auto& directory = metadata_.configured.database.directory;
    auto data_path = home_path / directory;

    if (create_directories(data_path, ec))
    {
        log::info(LOG_SERVER) << format(BS_INITIALIZING_CHAIN) % data_path;

        // Unfortunately we are still limited to a choice of hardcoded chains.
        //const auto genesis = metadata_.configured.chain.use_testnet_rules ?
         //   chain::block::genesis_testnet() : chain::block::genesis_mainnet();
        auto genesis = consensus::miner::create_genesis_block(!metadata_.configured.chain.use_testnet_rules);

        const auto result = data_base::initialize(data_path, *genesis);
        if (! result)
        	throw std::runtime_error{"initialize chain failed"};
		// init admin account
		set_admin();
        log::info(LOG_SERVER) << BS_INITCHAIN_COMPLETE;
        return true;
    } else {
    	if(data_base::is_lower_database(data_path)) {
	        auto genesis = consensus::miner::create_genesis_block(!metadata_.configured.chain.use_testnet_rules);
	        const auto result = data_base::upgrade_database(metadata_.configured.database, *genesis);
	        if (! result)
	        	throw std::runtime_error{"reinitialize blockchain db failed"};
			// init admin account
			// set_admin();
	        log::info(LOG_SERVER) << BS_INITCHAIN_COMPLETE;
	        return true;
    	} else if(data_base::is_higher_database(data_path)) {
			throw std::runtime_error{"blockchain db not compatible with mvsd. please download the newest mvsd and try!"};
		} else {
			// version equal nothing to do
		}
	}

    if (ec.value() == directory_exists)
    {
        return false;
    }
    auto error_info = format(BS_INITCHAIN_NEW) % data_path % ec.message();
    throw std::runtime_error{error_info.str()};
//    log::error(LOG_SERVER) << format(BS_INITCHAIN_NEW) % data_path % ec.message();
//    return false;
}

// Menu selection.
// ----------------------------------------------------------------------------

bool executor::menu()
{
    const auto& config = metadata_.configured;

    if (config.help)
    {
        do_help();
        return true;
    }

    if (config.settings)
    {
        do_settings();
        return true;
    }

    if (config.version)
    {
        do_version();
        return true;
    }

	try
	{
		auto result = do_initchain(); // false means no need to initial chain
	    if (config.initchain)
	    {
	    	return result;
	    }
	}
	catch(const std::exception& e){ // initialize failed
		//log::error(LOG_SERVER) << format(BS_INITCHAIN_EXISTS) % data_path;
		log::error(LOG_SERVER) << "initialize chain failed," << e.what();
		return false;
	}

    // There are no command line arguments, just run the server.
    return run();
}

// Run.
// ----------------------------------------------------------------------------

bool executor::run()
{
//    initialize_output();

    log::info(LOG_SERVER) << BS_NODE_STARTING;

    if (!verify_directory())
        return false;

    // Ensure all configured services can function.
    set_minimum_threadpool_size();

    // Now that the directory is verified we can create the node for it.
    node_ = std::make_shared<server_node>(metadata_.configured);

    // The callback may be returned on the same thread.
    node_->start(
        std::bind(&executor::handle_started,
            this, _1));

    // Wait for stop.
    stopping_.get_future().wait();

    log::info(LOG_SERVER) << BS_NODE_STOPPING;

    // Close must be called from main thread.
    if (node_->close())
        log::info(LOG_NODE) << BS_NODE_STOPPED;
    else
        log::info(LOG_NODE) << BS_NODE_STOP_FAIL;

    return true;
}

// Handle the completion of the start sequence and begin the run sequence.
void executor::handle_started(const code& ec)
{
    if (ec)
    {
        log::error(LOG_SERVER) << format(BS_NODE_START_FAIL) % ec.message();
        stop(ec);
        return;
    }

    log::info(LOG_SERVER) << BS_NODE_SEEDED;

    // This is the beginning of the stop sequence.
    node_->subscribe_stop(
        std::bind(&executor::handle_stopped,
            this, _1));

    // This is the beginning of the run sequence.
    node_->run(
        std::bind(&executor::handle_running,
            this, _1));
}

// This is the end of the run sequence.
void executor::handle_running(const code& ec)
{
    if (ec)
    {
        log::info(LOG_SERVER) << format(BS_NODE_START_FAIL) % ec.message();
        stop(ec);
        return;
    }

    log::info(LOG_SERVER) << BS_NODE_STARTED;
}

// This is the end of the stop sequence.
void executor::handle_stopped(const code& ec)
{
    stop(ec);
}

// Stop signal.
// ----------------------------------------------------------------------------

void executor::handle_stop(int code)
{
    // Reinitialize after each capture to prevent hard shutdown.
    std::signal(SIGINT, handle_stop);
    std::signal(SIGTERM, handle_stop);
    std::signal(SIGABRT, handle_stop);

    if (code == initialize_stop)
        return;

    if(SIGINT != code)
    {
    	do_backtrace("signal.out");
    }

    log::info(LOG_SERVER) << format(BS_NODE_SIGNALED) % code;
    stop(error::success);
}

void executor::stop(const code& ec)
{
    static std::once_flag stop_mutex;
    std::call_once(stop_mutex, [&](){ stopping_.set_value(ec); });
}

// Utilities.
// ----------------------------------------------------------------------------

// Set up logging.
void executor::initialize_output()
{
    log::debug(LOG_SERVER) << BS_LOG_HEADER;
    log::info(LOG_SERVER) << BS_LOG_HEADER;
    log::warning(LOG_SERVER) << BS_LOG_HEADER;
    log::error(LOG_SERVER) << BS_LOG_HEADER;
    log::fatal(LOG_SERVER) << BS_LOG_HEADER;

    auto file = default_data_path() / metadata_.configured.file;

    if (file.empty())
        log::info(LOG_SERVER) << BS_USING_DEFAULT_CONFIG;
    else
        log::info(LOG_SERVER) << format(BS_USING_CONFIG_FILE) % file;
}

// Use missing directory as a sentinel indicating lack of initialization.
bool executor::verify_directory()
{
    boost::system::error_code ec;
    auto home_path = default_data_path();
    const auto& directory = metadata_.configured.database.directory;
    auto data_path = home_path / directory;

    if (exists(data_path, ec))
        return true;

    if (ec.value() == directory_not_found)
    {
        log::error(LOG_SERVER) << format(BS_UNINITIALIZED_CHAIN) % data_path;
        return false;
    }

    const auto message = ec.message();
    log::error(LOG_SERVER) << format(BS_INITCHAIN_TRY) % data_path % message;
    return false;
}

// Increase the configured minomum as required to operate the service.
void executor::set_minimum_threadpool_size()
{
    metadata_.configured.network.threads =
        std::max(metadata_.configured.network.threads,
            server_node::threads_required(metadata_.configured));
}

} // namespace server
} // namespace libbitcoin
<commit_msg>Added if initchain failed remove mainnet dir<commit_after>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS)
 *
 * This file is part of metaverse-server.
 *
 * metaverse-server is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include "executor.hpp"

#include <algorithm>
#include <csignal>
#include <functional>
#include <future>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <metaverse/server.hpp>
#include <metaverse/bitcoin/utility/backtrace.hpp>
#include <metaverse/bitcoin/utility/path.hpp>

namespace libbitcoin {
namespace server {

using boost::format;
using namespace std::placeholders;
using namespace boost::system;
using namespace bc::config;
using namespace bc::database;
using namespace bc::network;

static constexpr int initialize_stop = 0;
static constexpr int directory_exists = 0;
static constexpr int directory_not_found = 2;
static constexpr auto append = std::ofstream::out | std::ofstream::app;
static const auto application_name = "bs";

std::promise<code> executor::stopping_;

executor::executor(parser& metadata, std::istream& input,
    std::ostream& output, std::ostream& error)
  : metadata_(metadata), output_(output),
    debug_file_((default_data_path() / metadata_.configured.network.debug_file).string(), append),
    error_file_((default_data_path() / metadata_.configured.network.error_file).string(), append)
{
    initialize_logging(debug_file_, error_file_, output, error);
    handle_stop(initialize_stop);
}

// Command line options.
// ----------------------------------------------------------------------------
// Emit directly to standard output (not the log).

void executor::do_help()
{
    const auto options = metadata_.load_options();
    printer help(options, application_name, BS_INFORMATION_MESSAGE);
    help.initialize();
    help.commandline(output_);
}

void executor::do_settings()
{
    const auto settings = metadata_.load_settings();
    printer print(settings, application_name, BS_SETTINGS_MESSAGE);
    print.initialize();
    print.settings(output_);
}

void executor::do_version()
{
    output_ << format(BS_VERSION_MESSAGE) %
        MVS_SERVER_VERSION %
        MVS_SERVER_VERSION %
        MVS_PROTOCOL_VERSION %
        MVS_NODE_VERSION %
        MVS_BLOCKCHAIN_VERSION %
        MVS_VERSION << std::endl;
}

void executor::set_admin()
{
	data_base db(metadata_.configured.database);
	db.start();
	db.set_admin("administerator", "mvsgo");
	db.stop();
}

// Emit to the log.
bool executor::do_initchain()
{
    initialize_output();

    boost::system::error_code ec;

    auto home_path = default_data_path();
    const auto& directory = metadata_.configured.database.directory;
    auto data_path = home_path / directory;

    if (create_directories(data_path, ec))
    {
        log::info(LOG_SERVER) << format(BS_INITIALIZING_CHAIN) % data_path;

        // Unfortunately we are still limited to a choice of hardcoded chains.
        //const auto genesis = metadata_.configured.chain.use_testnet_rules ?
         //   chain::block::genesis_testnet() : chain::block::genesis_mainnet();
        auto genesis = consensus::miner::create_genesis_block(!metadata_.configured.chain.use_testnet_rules);

        const auto result = data_base::initialize(data_path, *genesis);
        if (!result) {
            //rm directories
            remove_all(data_path);
            throw std::runtime_error{ "initialize chain failed" };
        }
		// init admin account
		set_admin();
        log::info(LOG_SERVER) << BS_INITCHAIN_COMPLETE;
        return true;
    } else {
    	if(data_base::is_lower_database(data_path)) {
	        auto genesis = consensus::miner::create_genesis_block(!metadata_.configured.chain.use_testnet_rules);
	        const auto result = data_base::upgrade_database(metadata_.configured.database, *genesis);
	        if (! result)
	        	throw std::runtime_error{"reinitialize blockchain db failed"};
			// init admin account
			// set_admin();
	        log::info(LOG_SERVER) << BS_INITCHAIN_COMPLETE;
	        return true;
    	} else if(data_base::is_higher_database(data_path)) {
			throw std::runtime_error{"blockchain db not compatible with mvsd. please download the newest mvsd and try!"};
		} else {
			// version equal nothing to do
		}
	}

    if (ec.value() == directory_exists)
    {
        return false;
    }
    auto error_info = format(BS_INITCHAIN_NEW) % data_path % ec.message();
    throw std::runtime_error{error_info.str()};
//    log::error(LOG_SERVER) << format(BS_INITCHAIN_NEW) % data_path % ec.message();
//    return false;
}

// Menu selection.
// ----------------------------------------------------------------------------

bool executor::menu()
{
    const auto& config = metadata_.configured;

    if (config.help)
    {
        do_help();
        return true;
    }

    if (config.settings)
    {
        do_settings();
        return true;
    }

    if (config.version)
    {
        do_version();
        return true;
    }

	try
	{
		auto result = do_initchain(); // false means no need to initial chain
	    if (config.initchain)
	    {
	    	return result;
	    }
	}
	catch(const std::exception& e){ // initialize failed
		//log::error(LOG_SERVER) << format(BS_INITCHAIN_EXISTS) % data_path;
		log::error(LOG_SERVER) << "initialize chain failed," << e.what();
		return false;
	}

    // There are no command line arguments, just run the server.
    return run();
}

// Run.
// ----------------------------------------------------------------------------

bool executor::run()
{
//    initialize_output();

    log::info(LOG_SERVER) << BS_NODE_STARTING;

    if (!verify_directory())
        return false;

    // Ensure all configured services can function.
    set_minimum_threadpool_size();

    // Now that the directory is verified we can create the node for it.
    node_ = std::make_shared<server_node>(metadata_.configured);

    // The callback may be returned on the same thread.
    node_->start(
        std::bind(&executor::handle_started,
            this, _1));

    // Wait for stop.
    stopping_.get_future().wait();

    log::info(LOG_SERVER) << BS_NODE_STOPPING;

    // Close must be called from main thread.
    if (node_->close())
        log::info(LOG_NODE) << BS_NODE_STOPPED;
    else
        log::info(LOG_NODE) << BS_NODE_STOP_FAIL;

    return true;
}

// Handle the completion of the start sequence and begin the run sequence.
void executor::handle_started(const code& ec)
{
    if (ec)
    {
        log::error(LOG_SERVER) << format(BS_NODE_START_FAIL) % ec.message();
        stop(ec);
        return;
    }

    log::info(LOG_SERVER) << BS_NODE_SEEDED;

    // This is the beginning of the stop sequence.
    node_->subscribe_stop(
        std::bind(&executor::handle_stopped,
            this, _1));

    // This is the beginning of the run sequence.
    node_->run(
        std::bind(&executor::handle_running,
            this, _1));
}

// This is the end of the run sequence.
void executor::handle_running(const code& ec)
{
    if (ec)
    {
        log::info(LOG_SERVER) << format(BS_NODE_START_FAIL) % ec.message();
        stop(ec);
        return;
    }

    log::info(LOG_SERVER) << BS_NODE_STARTED;
}

// This is the end of the stop sequence.
void executor::handle_stopped(const code& ec)
{
    stop(ec);
}

// Stop signal.
// ----------------------------------------------------------------------------

void executor::handle_stop(int code)
{
    // Reinitialize after each capture to prevent hard shutdown.
    std::signal(SIGINT, handle_stop);
    std::signal(SIGTERM, handle_stop);
    std::signal(SIGABRT, handle_stop);

    if (code == initialize_stop)
        return;

    if(SIGINT != code)
    {
    	do_backtrace("signal.out");
    }

    log::info(LOG_SERVER) << format(BS_NODE_SIGNALED) % code;
    stop(error::success);
}

void executor::stop(const code& ec)
{
    static std::once_flag stop_mutex;
    std::call_once(stop_mutex, [&](){ stopping_.set_value(ec); });
}

// Utilities.
// ----------------------------------------------------------------------------

// Set up logging.
void executor::initialize_output()
{
    log::debug(LOG_SERVER) << BS_LOG_HEADER;
    log::info(LOG_SERVER) << BS_LOG_HEADER;
    log::warning(LOG_SERVER) << BS_LOG_HEADER;
    log::error(LOG_SERVER) << BS_LOG_HEADER;
    log::fatal(LOG_SERVER) << BS_LOG_HEADER;

    auto file = default_data_path() / metadata_.configured.file;

    if (file.empty())
        log::info(LOG_SERVER) << BS_USING_DEFAULT_CONFIG;
    else
        log::info(LOG_SERVER) << format(BS_USING_CONFIG_FILE) % file;
}

// Use missing directory as a sentinel indicating lack of initialization.
bool executor::verify_directory()
{
    boost::system::error_code ec;
    auto home_path = default_data_path();
    const auto& directory = metadata_.configured.database.directory;
    auto data_path = home_path / directory;

    if (exists(data_path, ec))
        return true;

    if (ec.value() == directory_not_found)
    {
        log::error(LOG_SERVER) << format(BS_UNINITIALIZED_CHAIN) % data_path;
        return false;
    }

    const auto message = ec.message();
    log::error(LOG_SERVER) << format(BS_INITCHAIN_TRY) % data_path % message;
    return false;
}

// Increase the configured minomum as required to operate the service.
void executor::set_minimum_threadpool_size()
{
    metadata_.configured.network.threads =
        std::max(metadata_.configured.network.threads,
            server_node::threads_required(metadata_.configured));
}

} // namespace server
} // namespace libbitcoin
<|endoftext|>


<commit_before>/*
Copyright 2015 Adam Grandquist

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 Adam Grandquist
 * @copyright Apache
 */

#ifndef REQL_CPP_ERROR_HPP_
#define REQL_CPP_ERROR_HPP_

#include <exception>

namespace _ReQL {

enum Error_e {
  CompileError,
  DriverError,
  RuntimeError,
};

struct Error_t : public std::exception {
  Error_t(const Error_e code, const char *errstr) noexcept :
    _code(code),
    _what(errstr) {}

  Error_t(const Error_e code, const wchar_t *errstr) noexcept :
    _code(code),
    _what(reinterpret_cast<const char *>(errstr)) {}

  virtual const char* what() const noexcept override { return _what; }

  const Error_e _code;
  const char *_what;
};

}  // namespace _ReQL

#endif  // REQL_CPP_ERROR_HPP_
<commit_msg>Make wide error strings easier to handle.<commit_after>/*
Copyright 2015 Adam Grandquist

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 Adam Grandquist
 * @copyright Apache
 */

#ifndef REQL_CPP_ERROR_HPP_
#define REQL_CPP_ERROR_HPP_

#include <exception>

namespace _ReQL {

enum Error_e {
  CompileError,
  DriverError,
  RuntimeError
};

struct Error_t : public std::exception {
  Error_t(const char *errstr) noexcept;

  Error_t(const Error_e code, const char *errstr) noexcept;

  Error_t(const wchar_t *errstr) noexcept;

  Error_t(const Error_e code, const wchar_t *errstr) noexcept;

  virtual const char* what() const noexcept override;

  const wchar_t* wwhat() const noexcept;

  Error_e code() const noexcept;

  bool wide() const noexcept;

  const Error_e _code = DriverError;
  const char *_what;
  const bool _wide = false;
};

Error_t::Error_t(const char *errstr) noexcept :
  _what(errstr) {}

Error_t::Error_t(const Error_e code, const char *errstr) noexcept :
  _code(code),
  _what(errstr) {}

Error_t::Error_t(const wchar_t *errstr) noexcept :
  _what(reinterpret_cast<const char *>(errstr)),
  _wide(true) {}

Error_t::Error_t(const Error_e code, const wchar_t *errstr) noexcept :
  _code(code),
  _what(reinterpret_cast<const char *>(errstr)),
  _wide(true) {}

const char *
Error_t::what() const noexcept {
  return _wide ? "unhandled wide error" : _what;
}

const wchar_t *
Error_t::wwhat() const noexcept {
  return _wide ? reinterpret_cast<const wchar_t *>(_what) : L"bad wide error";
}

Error_e
Error_t::code() const noexcept {
  return _code;
}

bool
Error_t::wide() const noexcept {
  return _wide;
}

}  // namespace _ReQL

#endif  // REQL_CPP_ERROR_HPP_
<|endoftext|>


<commit_before>// Copyright 2004-present Facebook. All Rights Reserved.

#include <stdio.h>
#include <string.h>

#include "osquery/database.h"

namespace osquery {
namespace tables {

QueryData genArp() {
  Row r;
  QueryData results;
  FILE *arp_cmd_output;
  char *line;
  size_t length;

  char ip[32];
  char arp[64];
  char iface[32];

  // We are already calling 'popen', let's give it some more work with sed to clean.
  arp_cmd_output = popen("arp -an | sed 's,^[^(]*(\\([^)]*\\)) at \\([^ ]*\\).*on \\([^ ]*\\).*$,\\1 \\2 \\3,'", "r");
  if (arp_cmd_output == NULL) {
    return results;
  }

  line = fgetln(arp_cmd_output, &length);
  while (line) {
    sscanf(line, "%s %s %s", ip, arp, iface);

    r["ip"] = ip;
    r["arp"] = arp;
    r["iface"] = iface;

    results.push_back(r);

    line = fgetln(arp_cmd_output, &length);
  }

  return results;
}
}
}
<commit_msg>Change fgetln (osx specific) in favour of getline (both osx and linux)<commit_after>// Copyright 2004-present Facebook. All Rights Reserved.

#include <stdio.h>
#include <string.h>

#include "osquery/database.h"

namespace osquery {
namespace tables {

QueryData genArp() {
  Row r;
  QueryData results;
  FILE *arp_cmd_output;
  char *line = NULL;
  size_t length;
  int ret;

  char ip[32];
  char arp[64];
  char iface[32];

  // We are already calling 'popen', let's give it some more work with sed to clean.
  arp_cmd_output = popen("arp -an | sed 's,^[^(]*(\\([^)]*\\)) at \\([^ ]*\\).*on \\([^ ]*\\).*$,\\1 \\2 \\3,'", "r");
  if (arp_cmd_output == NULL) {
    return results;
  }

  ret = getline(&line, &length, arp_cmd_output);
  while (ret > 0) {
    sscanf(line, "%s %s %s", ip, arp, iface);

    r["ip"] = ip;
    r["arp"] = arp;
    r["iface"] = iface;

    results.push_back(r);

    line = NULL;
    ret = getline(&line, &length, arp_cmd_output);
  }

  return results;
}
}
}
<|endoftext|>


<commit_before>// This code is in the public domain -- castanyo@yahoo.es

#include <nvimage/Image.h>
#include <nvimage/ImageIO.h>

#include <nvmath/Color.h>

#include <nvcore/Debug.h>
#include <nvcore/Ptr.h>
#include <nvcore/Containers.h> // swap

using namespace nv;

Image::Image() : m_width(0), m_height(0), m_format(Format_RGB), m_data(NULL)
{
}

Image::Image(const Image & img) : m_data(NULL)
{
	allocate(img.m_width, img.m_height);
	m_format = img.m_format;
	memcpy(m_data, img.m_data, sizeof(Color32) * m_width * m_height);
}

Image::~Image()
{
	free();
}

const Image & Image::operator=(const Image & img)
{
	allocate(img.m_width, img.m_height);
	m_format = img.m_format;
	memcpy(m_data, img.m_data, sizeof(Color32) * m_width * m_height);
	return *this;
}

void Image::allocate(uint w, uint h)
{
	free();
	m_width = w;
	m_height = h;
	m_data = (Color32 *)nv::mem::malloc(w * h * sizeof(Color32));
}

bool Image::load(const char * name)
{
	free();

	AutoPtr<Image> img(ImageIO::load(name));
	if (img == NULL) {
		return false;
	}

	swap(m_width, img->m_width);
	swap(m_height, img->m_height);
	swap(m_format, img->m_format);
	swap(m_data, img->m_data);

	return true;
}

void Image::wrap(void * data, uint w, uint h)
{
	free();
	m_data = (Color32 *)data;
	m_width = w;
	m_height = h;
}

void Image::unwrap()
{
	m_data = NULL;
	m_width = 0;
	m_height = 0;
}

void Image::free()
{
	::free(m_data);
	m_data = NULL;
}

uint Image::width() const
{
	return m_width;
}

uint Image::height() const
{
	return m_height;
}

const Color32 * Image::scanline(uint h) const
{
	nvDebugCheck(h < m_height);
	return m_data + h * m_width;
}

Color32 * Image::scanline(uint h)
{
	nvDebugCheck(h < m_height);
	return m_data + h * m_width;
}

const Color32 * Image::pixels() const
{
	return m_data;
}

Color32 * Image::pixels()
{
	return m_data;
}

const Color32 & Image::pixel(uint idx) const
{
	nvDebugCheck(idx < m_width * m_height);
	return m_data[idx];
}

Color32 & Image::pixel(uint idx)
{
	nvDebugCheck(idx < m_width * m_height);
	return m_data[idx];
}

Image::Format Image::format() const
{
	return m_format;
}

void Image::setFormat(Image::Format f)
{
	m_format = f;
}

void Image::fill(Color32 c)
{
	const uint size = m_width * m_height;
	for (uint i = 0; i < size; ++i)
	{
		m_data[i] = c;
	}
}

<commit_msg>Use memory allocator correctly.<commit_after>// This code is in the public domain -- castanyo@yahoo.es

#include <nvimage/Image.h>
#include <nvimage/ImageIO.h>

#include <nvmath/Color.h>

#include <nvcore/Debug.h>
#include <nvcore/Ptr.h>
#include <nvcore/Containers.h> // swap

using namespace nv;

Image::Image() : m_width(0), m_height(0), m_format(Format_RGB), m_data(NULL)
{
}

Image::Image(const Image & img) : m_data(NULL)
{
	allocate(img.m_width, img.m_height);
	m_format = img.m_format;
	memcpy(m_data, img.m_data, sizeof(Color32) * m_width * m_height);
}

Image::~Image()
{
	free();
}

const Image & Image::operator=(const Image & img)
{
	allocate(img.m_width, img.m_height);
	m_format = img.m_format;
	memcpy(m_data, img.m_data, sizeof(Color32) * m_width * m_height);
	return *this;
}

void Image::allocate(uint w, uint h)
{
	m_width = w;
	m_height = h;
	m_data = (Color32 *)nv::mem::realloc(m_data, w * h * sizeof(Color32));
}

bool Image::load(const char * name)
{
	free();

	AutoPtr<Image> img(ImageIO::load(name));
	if (img == NULL) {
		return false;
	}

	swap(m_width, img->m_width);
	swap(m_height, img->m_height);
	swap(m_format, img->m_format);
	swap(m_data, img->m_data);

	return true;
}

void Image::wrap(void * data, uint w, uint h)
{
	free();
	m_data = (Color32 *)data;
	m_width = w;
	m_height = h;
}

void Image::unwrap()
{
	m_data = NULL;
	m_width = 0;
	m_height = 0;
}

void Image::free()
{
	nv::mem::free(m_data);
	m_data = NULL;
}

uint Image::width() const
{
	return m_width;
}

uint Image::height() const
{
	return m_height;
}

const Color32 * Image::scanline(uint h) const
{
	nvDebugCheck(h < m_height);
	return m_data + h * m_width;
}

Color32 * Image::scanline(uint h)
{
	nvDebugCheck(h < m_height);
	return m_data + h * m_width;
}

const Color32 * Image::pixels() const
{
	return m_data;
}

Color32 * Image::pixels()
{
	return m_data;
}

const Color32 & Image::pixel(uint idx) const
{
	nvDebugCheck(idx < m_width * m_height);
	return m_data[idx];
}

Color32 & Image::pixel(uint idx)
{
	nvDebugCheck(idx < m_width * m_height);
	return m_data[idx];
}

Image::Format Image::format() const
{
	return m_format;
}

void Image::setFormat(Image::Format f)
{
	m_format = f;
}

void Image::fill(Color32 c)
{
	const uint size = m_width * m_height;
	for (uint i = 0; i < size; ++i)
	{
		m_data[i] = c;
	}
}

<|endoftext|>


<commit_before>#include <iostream>
#include "ofxGridSystem.h"

ofxGridSystem::ofxGridSystem(float iPageWidth, float iPageHeight, int iNumColumns, float iBaselineLeading, float iBack, float iGutter, float iHead, float iTail)
{
  buildGrid(iPageWidth, iPageHeight, iNumColumns, iBaselineLeading, iBack, iGutter, iHead, iTail);
}

//NOTE If you use this constructor, you need to call buildGrid()
ofxGridSystem::ofxGridSystem()
{
  width = 0;
  height = 0;
  numCol = 0;
  left = 0;
  right = 0;
  tail = 0;
  head = 0;
  leading = 0;
  leftX = 0;
  rightX = 0;
  topY = 0;
  bottomY = 0;
  colW = 0;
  baselines = NULL;
  numBaselines = 0;
  isGridShown = false;
  isBaselineGridShown = false;
}

ofxGridSystem::~ofxGridSystem(){}

//Returns the X position of a column.
float ofxGridSystem::colX(int iNumber)
{
  if(iNumber < 0)
    return 0;
  else
    return (leftX + iNumber*(colW + leading));
}

//Returns the width of a number of columns.
float ofxGridSystem::col(int iNumber)
{
  return (colW * iNumber + leading * (iNumber - 1));
}

void ofxGridSystem::buildGrid(float iPageWidth, float iPageHeight, int iNumColumns, float iBaselineLeading, float iLeft, float iRight, float iHead, float iTail)
{
  width = iPageWidth;
  height = iPageHeight;

  numCol = iNumColumns;

  //Left, right, bottom, top in grid terms.
  left = iLeft;
  right = iRight;
  tail = iTail;
  head = iHead;

  leading = iBaselineLeading;

  //Back size determines position of left margin line.
  leftX = iLeft;
  //Gutter size determines position of left margin line.
  rightX = width - iRight;
  //Head determines top margin location.
  topY = height - head;
  //Tail determines bottom margin location.
  bottomY = tail;

  //Determine column width, Swiss grid style.
  //There is a baselineLeading space between each column.
  colW = (width - left - right - (numCol-1)*leading)/(float)numCol;

  //Calculate baseline grid positions.
  //NOTE Baseline grid starts at top of page. So you are responsible for aligning grid with head and tail.
  numBaselines = (int)(height/(float)leading);
  baselines = new float[numBaselines];
  for(int i=0; i < numBaselines; i++)
    baselines[i] = topY - (float)i*leading;

  isGridShown = false;
  isBaselineGridShown = false;

  buildLines();
  //By default, start with lines hidden.
  showLines(false);
}

void ofxGridSystem::buildLines()
{
  float curX = leftX;

  for(int i=0; i < (numCol+1); i++){

    if(i>0){
      ofxLineStripObject *line = new ofxLineStripObject(2);
      line->setVertexPos(0, 0, 0, 0);
      line->setVertexPos(1, 0, height - tail - head, 0);
      line->setTrans(curX, tail, 0);
      lines.push_back(line);
      addChild(line);

      curX += leading;
    }

    if(i < numCol){  //For last line on right.
      ofxLineStripObject *line = new ofxLineStripObject(2);
      line->setVertexPos(0, 0, 0, 0);
      line->setVertexPos(1, 0, height - tail - head, 0);
      line->setTrans(curX, tail, 0);
      lines.push_back(line);
      addChild(line);
    }

    curX += colW;
  }

  //Head line
  ofxLineStripObject *headLine = new ofxLineStripObject(2);
  headLine->setVertexPos(0, 0, 0, 0);
  headLine->setVertexPos(1, width-left-right, 0, 0);
  headLine->setTrans(leftX, topY, 0);
  headLine->hide();
  lines.push_back(headLine);
  addChild(headLine);

  //Tail line
  ofxLineStripObject *tailLine = new ofxLineStripObject(2);
  tailLine->setVertexPos(0, 0, 0, 0);
  tailLine->setVertexPos(1, width-left-right, 0, 0);
  tailLine->setTrans(leftX, bottomY, 0);
  tailLine->hide();
  lines.push_back(tailLine);
  addChild(tailLine);

  //Set line color and width.
  for(int i=0; i < lines.size(); i++){
    lines[i]->setColor(100, 100, 255, 255);
    lines[i]->setLineWidth(1.0);
    lines[i]->setRenderOnTop(true);
    lines[i]->hide();
  }

  //Create baseline lines.
  for(int i=0; i < numBaselines; i++){
    ofxLineStripObject *line = new ofxLineStripObject(2);
    line->setVertexPos(0, 0, 0, 0);
    line->setVertexPos(1, width, 0, 0);
    line->setTrans(0, height - (float)i*leading, 0);
    line->setColor(100, 100, 255, 100);
    line->setLineWidth(1.0);
    line->hide();
    line->setRenderOnTop(true);
    baselineLines.push_back(line);
    addChild(line);
  }
}

//Method for accessing grid positions.
//Basically, this returns an ofxGridSystemArray, which also has an overloaded [] operator.
//Usage: grid[2][2] where this will return an ofVec3f for the column 2 and 2 baselines down from top of page.
ofxGridSystemArray ofxGridSystem::operator[](int iColumn)
{
  ofxGridSystemArray array;
  array.x = colX(iColumn);
  array.leading = leading;
  array.height = height;

  return array;
}

void ofxGridSystem::setLineColor(ofVec4f iColor)
{
  for(int i=0; i < lines.size(); i++)
    lines[i]->setColor(iColor);

  for(int i=0; i < baselineLines.size(); i++)
    baselineLines[i]->setColor(iColor.x, iColor.y, iColor.z, 100);
}

void ofxGridSystem::setLineWidth(float iWidth)
{
  for(int i=0; i < lines.size(); i++)
    lines[i]->setLineWidth(iWidth);

  for(int i=0; i < baselineLines.size(); i++)
    baselineLines[i]->setLineWidth(iWidth);
}

bool ofxGridSystem::isGridVisible()
{
  return isGridShown;
}

bool ofxGridSystem::isBaselineGridVisible()
{
  return isBaselineGridShown;
}

//By default this shows all lines in grid. To hide baseline grid, use showBaselines()
void ofxGridSystem::showLines(bool iShowHide)
{
  for(int i=0; i < lines.size(); i++){
    if(iShowHide) lines[i]->show();
    else lines[i]->hide();
  }

  for(int i=0; i < baselineLines.size(); i++){
    if(iShowHide){
      if(isBaselineGridShown) baselineLines[i]->show();
    }else{
      baselineLines[i]->hide();
    }
  }

  isGridShown = iShowHide;

}

void ofxGridSystem::showBaselines(bool iShowHide)
{
  for(int i=0; i < baselineLines.size(); i++){
    if(iShowHide) baselineLines[i]->show();
    else baselineLines[i]->hide();
  }

  isBaselineGridShown = iShowHide;
}
<commit_msg>changed constructor arg names<commit_after>#include <iostream>
#include "ofxGridSystem.h"

ofxGridSystem::ofxGridSystem(float iPageWidth, float iPageHeight, int iNumColumns, float iBaselineLeading, float iLeft, float iRight, float iHead, float iTail)
{
  buildGrid(iPageWidth, iPageHeight, iNumColumns, iBaselineLeading, iLeft, iRight, iHead, iTail);
}

//NOTE If you use this constructor, you need to call buildGrid()
ofxGridSystem::ofxGridSystem()
{
  width = 0;
  height = 0;
  numCol = 0;
  left = 0;
  right = 0;
  tail = 0;
  head = 0;
  leading = 0;
  leftX = 0;
  rightX = 0;
  topY = 0;
  bottomY = 0;
  colW = 0;
  baselines = NULL;
  numBaselines = 0;
  isGridShown = false;
  isBaselineGridShown = false;
}

ofxGridSystem::~ofxGridSystem(){}

//Returns the X position of a column.
float ofxGridSystem::colX(int iNumber)
{
  if(iNumber < 0)
    return 0;
  else
    return (leftX + iNumber*(colW + leading));
}

//Returns the width of a number of columns.
float ofxGridSystem::col(int iNumber)
{
  return (colW * iNumber + leading * (iNumber - 1));
}

void ofxGridSystem::buildGrid(float iPageWidth, float iPageHeight, int iNumColumns, float iBaselineLeading, float iLeft, float iRight, float iHead, float iTail)
{
  width = iPageWidth;
  height = iPageHeight;

  numCol = iNumColumns;

  //Left, right, bottom, top in grid terms.
  left = iLeft;
  right = iRight;
  tail = iTail;
  head = iHead;

  leading = iBaselineLeading;

  //Back size determines position of left margin line.
  leftX = iLeft;
  //Gutter size determines position of left margin line.
  rightX = width - iRight;
  //Head determines top margin location.
  topY = height - head;
  //Tail determines bottom margin location.
  bottomY = tail;

  //Determine column width, Swiss grid style.
  //There is a baselineLeading space between each column.
  colW = (width - left - right - (numCol-1)*leading)/(float)numCol;

  //Calculate baseline grid positions.
  //NOTE Baseline grid starts at top of page. So you are responsible for aligning grid with head and tail.
  numBaselines = (int)(height/(float)leading);
  baselines = new float[numBaselines];
  for(int i=0; i < numBaselines; i++)
    baselines[i] = topY - (float)i*leading;

  isGridShown = false;
  isBaselineGridShown = false;

  buildLines();
  //By default, start with lines hidden.
  showLines(false);
}

void ofxGridSystem::buildLines()
{
  float curX = leftX;

  for(int i=0; i < (numCol+1); i++){

    if(i>0){
      ofxLineStripObject *line = new ofxLineStripObject(2);
      line->setVertexPos(0, 0, 0, 0);
      line->setVertexPos(1, 0, height - tail - head, 0);
      line->setTrans(curX, tail, 0);
      lines.push_back(line);
      addChild(line);

      curX += leading;
    }

    if(i < numCol){  //For last line on right.
      ofxLineStripObject *line = new ofxLineStripObject(2);
      line->setVertexPos(0, 0, 0, 0);
      line->setVertexPos(1, 0, height - tail - head, 0);
      line->setTrans(curX, tail, 0);
      lines.push_back(line);
      addChild(line);
    }

    curX += colW;
  }

  //Head line
  ofxLineStripObject *headLine = new ofxLineStripObject(2);
  headLine->setVertexPos(0, 0, 0, 0);
  headLine->setVertexPos(1, width-left-right, 0, 0);
  headLine->setTrans(leftX, topY, 0);
  headLine->hide();
  lines.push_back(headLine);
  addChild(headLine);

  //Tail line
  ofxLineStripObject *tailLine = new ofxLineStripObject(2);
  tailLine->setVertexPos(0, 0, 0, 0);
  tailLine->setVertexPos(1, width-left-right, 0, 0);
  tailLine->setTrans(leftX, bottomY, 0);
  tailLine->hide();
  lines.push_back(tailLine);
  addChild(tailLine);

  //Set line color and width.
  for(int i=0; i < lines.size(); i++){
    lines[i]->setColor(100, 100, 255, 255);
    lines[i]->setLineWidth(1.0);
    lines[i]->setRenderOnTop(true);
    lines[i]->hide();
  }

  //Create baseline lines.
  for(int i=0; i < numBaselines; i++){
    ofxLineStripObject *line = new ofxLineStripObject(2);
    line->setVertexPos(0, 0, 0, 0);
    line->setVertexPos(1, width, 0, 0);
    line->setTrans(0, height - (float)i*leading, 0);
    line->setColor(100, 100, 255, 100);
    line->setLineWidth(1.0);
    line->hide();
    line->setRenderOnTop(true);
    baselineLines.push_back(line);
    addChild(line);
  }
}

//Method for accessing grid positions.
//Basically, this returns an ofxGridSystemArray, which also has an overloaded [] operator.
//Usage: grid[2][2] where this will return an ofVec3f for the column 2 and 2 baselines down from top of page.
ofxGridSystemArray ofxGridSystem::operator[](int iColumn)
{
  ofxGridSystemArray array;
  array.x = colX(iColumn);
  array.leading = leading;
  array.height = height;

  return array;
}

void ofxGridSystem::setLineColor(ofVec4f iColor)
{
  for(int i=0; i < lines.size(); i++)
    lines[i]->setColor(iColor);

  for(int i=0; i < baselineLines.size(); i++)
    baselineLines[i]->setColor(iColor.x, iColor.y, iColor.z, 100);
}

void ofxGridSystem::setLineWidth(float iWidth)
{
  for(int i=0; i < lines.size(); i++)
    lines[i]->setLineWidth(iWidth);

  for(int i=0; i < baselineLines.size(); i++)
    baselineLines[i]->setLineWidth(iWidth);
}

bool ofxGridSystem::isGridVisible()
{
  return isGridShown;
}

bool ofxGridSystem::isBaselineGridVisible()
{
  return isBaselineGridShown;
}

//By default this shows all lines in grid. To hide baseline grid, use showBaselines()
void ofxGridSystem::showLines(bool iShowHide)
{
  for(int i=0; i < lines.size(); i++){
    if(iShowHide) lines[i]->show();
    else lines[i]->hide();
  }

  for(int i=0; i < baselineLines.size(); i++){
    if(iShowHide){
      if(isBaselineGridShown) baselineLines[i]->show();
    }else{
      baselineLines[i]->hide();
    }
  }

  isGridShown = iShowHide;

}

void ofxGridSystem::showBaselines(bool iShowHide)
{
  for(int i=0; i < baselineLines.size(); i++){
    if(iShowHide) baselineLines[i]->show();
    else baselineLines[i]->hide();
  }

  isBaselineGridShown = iShowHide;
}
<|endoftext|>


<commit_before>#include "Gui.h"

namespace ofxPreset
{
	//--------------------------------------------------------------
	void Gui::SetNextWindow(GuiSettings & settings)
	{
		settings.windowSize.x = 0;
		settings.windowPos.y += settings.windowSize.y + kGuiMargin;
	}

	//--------------------------------------------------------------
	bool Gui::BeginWindow(Parameter<bool> & parameter, const GuiSettings & settings, bool collapse)
	{
		return Gui::BeginWindow(parameter.getName(), settings, collapse, parameter.getRef());
	}

	//--------------------------------------------------------------
	bool Gui::BeginWindow(const string & name, const GuiSettings & settings, bool collapse, bool * opened)
	{
		ImGui::SetNextWindowPos(settings.windowPos, ImGuiSetCond_Appearing);
		ImGui::SetNextWindowSize(settings.windowSize, ImGuiSetCond_Appearing);
		ImGui::SetNextWindowCollapsed(collapse, ImGuiSetCond_Appearing);
		return ImGui::Begin(name.c_str(), opened, ImGuiWindowFlags_AlwaysAutoResize | (collapse ?  0 : ImGuiWindowFlags_NoCollapse));
	}

	//--------------------------------------------------------------
	void Gui::EndWindow(GuiSettings & settings)
	{
		settings.windowPos = ImGui::GetWindowPos();
		settings.windowSize = ImGui::GetWindowSize();
		ImGui::End();

		const auto bounds = ofRectangle(settings.windowPos, settings.windowSize.x, settings.windowSize.y);
		settings.mouseOverGui = bounds.inside(ofGetMouseX(), ofGetMouseY());
	}

    //--------------------------------------------------------------
    bool Gui::AddParameter(Parameter<ofVec2f> & parameter)
    {
        return ImGui::SliderFloat2(parameter.getName().c_str(), parameter.getRef()->getPtr(), parameter.getMin().x, parameter.getMax().x);
    }

    //--------------------------------------------------------------
    bool Gui::AddParameter(Parameter<ofVec3f> & parameter)
    {
        return ImGui::SliderFloat3(parameter.getName().c_str(), parameter.getRef()->getPtr(), parameter.getMin().x, parameter.getMax().x);
    }

    //--------------------------------------------------------------
    bool Gui::AddParameter(Parameter<ofVec4f> & parameter)
    {
        return ImGui::SliderFloat4(parameter.getName().c_str(), parameter.getRef()->getPtr(), parameter.getMin().x, parameter.getMax().x);
    }

    //--------------------------------------------------------------
    bool Gui::AddParameter(Parameter<ofFloatColor> & parameter)
    {
        return ImGui::ColorEdit4(parameter.getName().c_str(), &(parameter.getRef()->r));
    }

	//--------------------------------------------------------------
	template<typename ParameterType>
	bool Gui::AddParameter(Parameter<ParameterType> & parameter)
	{
		const auto & info = typeid(ParameterType);
		if (info == typeid(float))
		{
			return ImGui::SliderFloat(parameter.getName().c_str(), (float *)parameter.getRef(), parameter.getMin(), parameter.getMax());
		}
		if (info == typeid(int))
		{
			return ImGui::SliderInt(parameter.getName().c_str(), (int *)parameter.getRef(), parameter.getMin(), parameter.getMax());
		}
		if (info == typeid(bool))
		{
			return ImGui::Checkbox(parameter.getName().c_str(), (bool *)parameter.getRef());
		}
		ofLogWarning("Gui::addParameter") << "Could not create GUI element for type " << info.name();
		return false;
	}

	//--------------------------------------------------------------
	bool Gui::AddRange(const string & name, Parameter<float> & parameterMin, Parameter<float> & parameterMax, float speed)
	{
		return ImGui::DragFloatRange2(name.c_str(), parameterMin.getRef(), parameterMax.getRef(), speed, parameterMin.getMin(), parameterMax.getMax());
	}

	//--------------------------------------------------------------
	void Gui::AddImage(ofBaseHasTexture & hasTexture, const ofVec2f & size)
	{
		Gui::AddImage(hasTexture.getTexture(), size);
	}

	//--------------------------------------------------------------
	void Gui::AddImage(ofTexture & texture, const ofVec2f & size)
	{
		ImTextureID textureID = (ImTextureID)(uintptr_t)texture.texData.textureID;
		ImGui::Image(textureID, size);
	}
}
<commit_msg>Fixed bug where settings.mouseOverGui would erase previous value.<commit_after>#include "Gui.h"

namespace ofxPreset
{
	//--------------------------------------------------------------
	void Gui::SetNextWindow(GuiSettings & settings)
	{
		settings.windowSize.x = 0;
		settings.windowPos.y += settings.windowSize.y + kGuiMargin;
	}

	//--------------------------------------------------------------
	bool Gui::BeginWindow(Parameter<bool> & parameter, const GuiSettings & settings, bool collapse)
	{
		return Gui::BeginWindow(parameter.getName(), settings, collapse, parameter.getRef());
	}

	//--------------------------------------------------------------
	bool Gui::BeginWindow(const string & name, const GuiSettings & settings, bool collapse, bool * opened)
	{
		ImGui::SetNextWindowPos(settings.windowPos, ImGuiSetCond_Appearing);
		ImGui::SetNextWindowSize(settings.windowSize, ImGuiSetCond_Appearing);
		ImGui::SetNextWindowCollapsed(collapse, ImGuiSetCond_Appearing);
		return ImGui::Begin(name.c_str(), opened, ImGuiWindowFlags_AlwaysAutoResize | (collapse ?  0 : ImGuiWindowFlags_NoCollapse));
	}

	//--------------------------------------------------------------
	void Gui::EndWindow(GuiSettings & settings)
	{
		settings.windowPos = ImGui::GetWindowPos();
		settings.windowSize = ImGui::GetWindowSize();
		ImGui::End();

		const auto bounds = ofRectangle(settings.windowPos, settings.windowSize.x, settings.windowSize.y);
		settings.mouseOverGui |= bounds.inside(ofGetMouseX(), ofGetMouseY());
	}

    //--------------------------------------------------------------
    bool Gui::AddParameter(Parameter<ofVec2f> & parameter)
    {
        return ImGui::SliderFloat2(parameter.getName().c_str(), parameter.getRef()->getPtr(), parameter.getMin().x, parameter.getMax().x);
    }

    //--------------------------------------------------------------
    bool Gui::AddParameter(Parameter<ofVec3f> & parameter)
    {
        return ImGui::SliderFloat3(parameter.getName().c_str(), parameter.getRef()->getPtr(), parameter.getMin().x, parameter.getMax().x);
    }

    //--------------------------------------------------------------
    bool Gui::AddParameter(Parameter<ofVec4f> & parameter)
    {
        return ImGui::SliderFloat4(parameter.getName().c_str(), parameter.getRef()->getPtr(), parameter.getMin().x, parameter.getMax().x);
    }

    //--------------------------------------------------------------
    bool Gui::AddParameter(Parameter<ofFloatColor> & parameter)
    {
        return ImGui::ColorEdit4(parameter.getName().c_str(), &(parameter.getRef()->r));
    }

	//--------------------------------------------------------------
	template<typename ParameterType>
	bool Gui::AddParameter(Parameter<ParameterType> & parameter)
	{
		const auto & info = typeid(ParameterType);
		if (info == typeid(float))
		{
			return ImGui::SliderFloat(parameter.getName().c_str(), (float *)parameter.getRef(), parameter.getMin(), parameter.getMax());
		}
		if (info == typeid(int))
		{
			return ImGui::SliderInt(parameter.getName().c_str(), (int *)parameter.getRef(), parameter.getMin(), parameter.getMax());
		}
		if (info == typeid(bool))
		{
			return ImGui::Checkbox(parameter.getName().c_str(), (bool *)parameter.getRef());
		}
		ofLogWarning("Gui::addParameter") << "Could not create GUI element for type " << info.name();
		return false;
	}

	//--------------------------------------------------------------
	bool Gui::AddRange(const string & name, Parameter<float> & parameterMin, Parameter<float> & parameterMax, float speed)
	{
		return ImGui::DragFloatRange2(name.c_str(), parameterMin.getRef(), parameterMax.getRef(), speed, parameterMin.getMin(), parameterMax.getMax());
	}

	//--------------------------------------------------------------
	void Gui::AddImage(ofBaseHasTexture & hasTexture, const ofVec2f & size)
	{
		Gui::AddImage(hasTexture.getTexture(), size);
	}

	//--------------------------------------------------------------
	void Gui::AddImage(ofTexture & texture, const ofVec2f & size)
	{
		ImTextureID textureID = (ImTextureID)(uintptr_t)texture.texData.textureID;
		ImGui::Image(textureID, size);
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xfactory.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2003-09-11 10:15:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif

#include "xfactory.hxx"
#include "xstorage.hxx"

using namespace ::com::sun::star;

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OStorageFactory::impl_staticGetSupportedServiceNames()
{
    uno::Sequence< ::rtl::OUString > aRet(2);
    aRet[0] = ::rtl::OUString::createFromAscii("com.sun.star.embed.StorageFactory");
    aRet[1] = ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.StorageFactory");
    return aRet;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OStorageFactory::impl_staticGetImplementationName()
{
    return ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.StorageFactory");
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OStorageFactory::impl_staticCreateSelfInstance(
            const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )
{
    return uno::Reference< uno::XInterface >( *new OStorageFactory( xServiceManager ) );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OStorageFactory::createInstance()
    throw ( uno::Exception,
            uno::RuntimeException )
{
    // TODO: reimplement TempStream service to support XStream interface
    uno::Reference < io::XStream > xTempStream(
                        m_xFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.io.TempFile" ) ),
                        uno::UNO_QUERY );

    if ( !xTempStream.is() )
        throw uno::RuntimeException(); // TODO:

    return uno::Reference< uno::XInterface >(
                static_cast< OWeakObject* >( new OStorage(  xTempStream,
                                                            embed::ElementModes::ELEMENT_READWRITE,
                                                            uno::Sequence< beans::PropertyValue >(),
                                                            m_xFactory ) ),
                uno::UNO_QUERY );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OStorageFactory::createInstanceWithArguments(
            const uno::Sequence< uno::Any >& aArguments )
    throw ( uno::Exception,
            uno::RuntimeException )
{
    // The request for storage can be done with up to three arguments

    // The first argument specifies a source for the storage
    // it can be URL, XStream, XInputStream.
    // The second value is a mode the storage should be open in.
    // And the third value is a media descriptor.

    sal_Int32 nArgNum = aArguments.getLength();
    OSL_ENSURE( nArgNum < 4, "Wrong parameter number" );

    if ( !nArgNum )
        return createInstance();

    // first try to retrieve storage open mode if any
    // by default the storage will be open in readonly mode
    sal_Int32 nStorageMode = embed::ElementModes::ELEMENT_READ;
    if ( nArgNum >= 2 )
    {
        if( !( aArguments[1] >>= nStorageMode ) )
        {
            OSL_ENSURE( sal_False, "Wrong second argument!\n" );
            throw uno::Exception(); // TODO: Illegal argument
        }
        // it's allways possible to read written storage in this implementation
        nStorageMode |= embed::ElementModes::ELEMENT_READ;
    }

    // retrieve storage source stream
    ::rtl::OUString aURL;
    uno::Reference< io::XStream > xStream;
    uno::Reference< io::XInputStream > xInputStream;

    if ( aArguments[0] >>= aURL )
    {
        if ( !aURL.getLength() )
        {
            OSL_ENSURE( sal_False, "Empty URL is provided!\n" );
            throw uno::Exception(); // TODO: illegal argument
        }

        if ( aURL.equalsIgnoreAsciiCaseAsciiL( "vnd.sun.star.pkg", 16 ) )
        {
            OSL_ENSURE( sal_False, "Packages URL's are not valid for storages!\n" ); // ???
            throw uno::Exception(); // TODO: illegal argument
        }

        uno::Reference < ::com::sun::star::ucb::XSimpleFileAccess > xTempAccess(
                m_xFactory->createInstance (
                        ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ),
                uno::UNO_QUERY );

        if ( !xTempAccess.is() )
            throw uno::RuntimeException(); // TODO:

        if ( nStorageMode & embed::ElementModes::ELEMENT_WRITE )
            xStream = xTempAccess->openFileReadWrite( aURL );
        else
            xInputStream = xTempAccess->openFileRead( aURL );
    }
    else if ( !( aArguments[0] >>= xStream ) && !( aArguments[0] >>= xInputStream ) )
    {
        OSL_ENSURE( sal_False, "Wrong first argument!\n" );
        throw uno::Exception(); // TODO: Illegal argument
    }

    // retrieve mediadescriptor and set storage properties
    uno::Sequence< beans::PropertyValue > aDescr;
    uno::Sequence< beans::PropertyValue > aPropsToSet;

    if ( nArgNum >= 3 )
    {
        if( aArguments[2] >>= aDescr )
        {
            if ( aURL.getLength() )
            {
                aPropsToSet.realloc(1);
                aPropsToSet[0].Name = ::rtl::OUString::createFromAscii( "URL" );
                aPropsToSet[0].Value <<= aURL;
            }
            // TODO: fill in aPropsToSet

            for ( sal_Int32 nInd = 0, nNumArgs = 1; nInd < aDescr.getLength(); nInd++ )
            {
                if ( aDescr[nInd].Name.equalsAscii( "InteractionHandler" )
                  || aDescr[nInd].Name.equalsAscii( "Password" )
                  || aDescr[nInd].Name.equalsAscii( "RepairPackage" ) )
                  // || aDescr[nInd].Name.equalsAscii( "StatusIndicator" ) ) // TODO: may be should be changed to ProgressHandler
                  // || aDescr[nInd].Name.equalsAscii( "Unpacked" ) // TODO:
                {
                    aPropsToSet.realloc( ++nNumArgs );
                    aPropsToSet[nNumArgs-1].Name = aDescr[nInd].Name;
                    aPropsToSet[nNumArgs-1].Value = aDescr[nInd].Value;
                }
                else
                    OSL_ENSURE( sal_False, "Unacceptable property, will be ignored!\n" );
            }
        }
        else
        {
            OSL_ENSURE( sal_False, "Wrong third argument!\n" );
            throw uno::Exception(); // TODO: Illegal argument
        }

    }

    // create storage based on source
    if ( xInputStream.is() )
    {
        // if xInputStream is set the storage should be open from it
        if ( ( nStorageMode & embed::ElementModes::ELEMENT_WRITE ) )
              throw uno::Exception(); // TODO: access denied

        return uno::Reference< uno::XInterface >(
                    static_cast< OWeakObject* >( new OStorage( xInputStream, nStorageMode, aPropsToSet, m_xFactory ) ),
                    uno::UNO_QUERY );
    }
    else if ( xStream.is() )
    {
        if ( ( nStorageMode & embed::ElementModes::ELEMENT_WRITE ) && !xStream->getOutputStream().is()
          || !xStream->getInputStream().is() )
              throw uno::Exception(); // TODO: access denied

        uno::Reference< io::XSeekable > xSeekable( xStream, uno::UNO_QUERY );
        if ( !xSeekable.is() )
        {
            // TODO: wrap stream to let it be seekable
            OSL_ENSURE( sal_False, "Nonseekable streams are not supported for now!\n" );
        }

        return uno::Reference< uno::XInterface >(
                    static_cast< OWeakObject* >( new OStorage( xStream, nStorageMode, aPropsToSet, m_xFactory ) ),
                    uno::UNO_QUERY );
    }

    throw uno::Exception(); // general error during creation
    // not reachable
    return uno::Reference< uno::XInterface >();
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OStorageFactory::getImplementationName()
    throw ( uno::RuntimeException )
{
    return impl_staticGetImplementationName();
}

//-------------------------------------------------------------------------
sal_Bool SAL_CALL OStorageFactory::supportsService( const ::rtl::OUString& ServiceName )
    throw ( uno::RuntimeException )
{
    uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();

    for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )
        if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )
            return sal_True;

    return sal_False;
}

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OStorageFactory::getSupportedServiceNames()
    throw ( uno::RuntimeException )
{
    return impl_staticGetSupportedServiceNames();
}

<commit_msg>INTEGRATION: CWS fwkbugfix02 (1.2.36); FILE MERGED 2004/04/01 14:33:49 mav 1.2.36.1: #116056# adopt implementation to the design change<commit_after>/*************************************************************************
 *
 *  $RCSfile: xfactory.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2004-05-10 17:28:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_
#include <com/sun/star/io/XSeekable.hpp>
#endif

#include "xfactory.hxx"
#include "xstorage.hxx"

using namespace ::com::sun::star;

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OStorageFactory::impl_staticGetSupportedServiceNames()
{
    uno::Sequence< ::rtl::OUString > aRet(2);
    aRet[0] = ::rtl::OUString::createFromAscii("com.sun.star.embed.StorageFactory");
    aRet[1] = ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.StorageFactory");
    return aRet;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OStorageFactory::impl_staticGetImplementationName()
{
    return ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.StorageFactory");
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OStorageFactory::impl_staticCreateSelfInstance(
            const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )
{
    return uno::Reference< uno::XInterface >( *new OStorageFactory( xServiceManager ) );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OStorageFactory::createInstance()
    throw ( uno::Exception,
            uno::RuntimeException )
{
    // TODO: reimplement TempStream service to support XStream interface
    uno::Reference < io::XStream > xTempStream(
                        m_xFactory->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.io.TempFile" ) ),
                        uno::UNO_QUERY );

    if ( !xTempStream.is() )
        throw uno::RuntimeException(); // TODO:

    return uno::Reference< uno::XInterface >(
                static_cast< OWeakObject* >( new OStorage(  xTempStream,
                                                            embed::ElementModes::READWRITE,
                                                            uno::Sequence< beans::PropertyValue >(),
                                                            m_xFactory ) ),
                uno::UNO_QUERY );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OStorageFactory::createInstanceWithArguments(
            const uno::Sequence< uno::Any >& aArguments )
    throw ( uno::Exception,
            uno::RuntimeException )
{
    // The request for storage can be done with up to three arguments

    // The first argument specifies a source for the storage
    // it can be URL, XStream, XInputStream.
    // The second value is a mode the storage should be open in.
    // And the third value is a media descriptor.

    sal_Int32 nArgNum = aArguments.getLength();
    OSL_ENSURE( nArgNum < 4, "Wrong parameter number" );

    if ( !nArgNum )
        return createInstance();

    // first try to retrieve storage open mode if any
    // by default the storage will be open in readonly mode
    sal_Int32 nStorageMode = embed::ElementModes::READ;
    if ( nArgNum >= 2 )
    {
        if( !( aArguments[1] >>= nStorageMode ) )
        {
            OSL_ENSURE( sal_False, "Wrong second argument!\n" );
            throw uno::Exception(); // TODO: Illegal argument
        }
        // it's allways possible to read written storage in this implementation
        nStorageMode |= embed::ElementModes::READ;
    }

    // retrieve storage source stream
    ::rtl::OUString aURL;
    uno::Reference< io::XStream > xStream;
    uno::Reference< io::XInputStream > xInputStream;

    if ( aArguments[0] >>= aURL )
    {
        if ( !aURL.getLength() )
        {
            OSL_ENSURE( sal_False, "Empty URL is provided!\n" );
            throw uno::Exception(); // TODO: illegal argument
        }

        if ( aURL.equalsIgnoreAsciiCaseAsciiL( "vnd.sun.star.pkg", 16 ) )
        {
            OSL_ENSURE( sal_False, "Packages URL's are not valid for storages!\n" ); // ???
            throw uno::Exception(); // TODO: illegal argument
        }

        uno::Reference < ::com::sun::star::ucb::XSimpleFileAccess > xTempAccess(
                m_xFactory->createInstance (
                        ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ),
                uno::UNO_QUERY );

        if ( !xTempAccess.is() )
            throw uno::RuntimeException(); // TODO:

        if ( nStorageMode & embed::ElementModes::WRITE )
            xStream = xTempAccess->openFileReadWrite( aURL );
        else
            xInputStream = xTempAccess->openFileRead( aURL );
    }
    else if ( !( aArguments[0] >>= xStream ) && !( aArguments[0] >>= xInputStream ) )
    {
        OSL_ENSURE( sal_False, "Wrong first argument!\n" );
        throw uno::Exception(); // TODO: Illegal argument
    }

    // retrieve mediadescriptor and set storage properties
    uno::Sequence< beans::PropertyValue > aDescr;
    uno::Sequence< beans::PropertyValue > aPropsToSet;

    if ( nArgNum >= 3 )
    {
        if( aArguments[2] >>= aDescr )
        {
            if ( aURL.getLength() )
            {
                aPropsToSet.realloc(1);
                aPropsToSet[0].Name = ::rtl::OUString::createFromAscii( "URL" );
                aPropsToSet[0].Value <<= aURL;
            }
            // TODO: fill in aPropsToSet

            for ( sal_Int32 nInd = 0, nNumArgs = 1; nInd < aDescr.getLength(); nInd++ )
            {
                if ( aDescr[nInd].Name.equalsAscii( "InteractionHandler" )
                  || aDescr[nInd].Name.equalsAscii( "Password" )
                  || aDescr[nInd].Name.equalsAscii( "RepairPackage" ) )
                  // || aDescr[nInd].Name.equalsAscii( "StatusIndicator" ) ) // TODO: may be should be changed to ProgressHandler
                  // || aDescr[nInd].Name.equalsAscii( "Unpacked" ) // TODO:
                {
                    aPropsToSet.realloc( ++nNumArgs );
                    aPropsToSet[nNumArgs-1].Name = aDescr[nInd].Name;
                    aPropsToSet[nNumArgs-1].Value = aDescr[nInd].Value;
                }
                else
                    OSL_ENSURE( sal_False, "Unacceptable property, will be ignored!\n" );
            }
        }
        else
        {
            OSL_ENSURE( sal_False, "Wrong third argument!\n" );
            throw uno::Exception(); // TODO: Illegal argument
        }

    }

    // create storage based on source
    if ( xInputStream.is() )
    {
        // if xInputStream is set the storage should be open from it
        if ( ( nStorageMode & embed::ElementModes::WRITE ) )
              throw uno::Exception(); // TODO: access denied

        return uno::Reference< uno::XInterface >(
                    static_cast< OWeakObject* >( new OStorage( xInputStream, nStorageMode, aPropsToSet, m_xFactory ) ),
                    uno::UNO_QUERY );
    }
    else if ( xStream.is() )
    {
        if ( ( nStorageMode & embed::ElementModes::WRITE ) && !xStream->getOutputStream().is()
          || !xStream->getInputStream().is() )
              throw uno::Exception(); // TODO: access denied

        uno::Reference< io::XSeekable > xSeekable( xStream, uno::UNO_QUERY );
        if ( !xSeekable.is() )
        {
            // TODO: wrap stream to let it be seekable
            OSL_ENSURE( sal_False, "Nonseekable streams are not supported for now!\n" );
        }

        return uno::Reference< uno::XInterface >(
                    static_cast< OWeakObject* >( new OStorage( xStream, nStorageMode, aPropsToSet, m_xFactory ) ),
                    uno::UNO_QUERY );
    }

    throw uno::Exception(); // general error during creation
    // not reachable
    return uno::Reference< uno::XInterface >();
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OStorageFactory::getImplementationName()
    throw ( uno::RuntimeException )
{
    return impl_staticGetImplementationName();
}

//-------------------------------------------------------------------------
sal_Bool SAL_CALL OStorageFactory::supportsService( const ::rtl::OUString& ServiceName )
    throw ( uno::RuntimeException )
{
    uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();

    for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )
        if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )
            return sal_True;

    return sal_False;
}

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OStorageFactory::getSupportedServiceNames()
    throw ( uno::RuntimeException )
{
    return impl_staticGetSupportedServiceNames();
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <cstring>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/thread.h>

#include <OSL/oslcomp.h>
#include <OSL/oslexec.h>
using namespace OSL;

static void
usage ()
{
    std::cout <<
        "oslc -- Open Shading Language compiler " OSL_LIBRARY_VERSION_STRING "\n"
        OSL_COPYRIGHT_STRING "\n"
        "Usage:  oslc [options] file\n"
        "  Options:\n"
        "\t--help         Print this usage message\n"
        "\t-o filename    Specify output filename\n"
        "\t-v             Verbose mode\n"
        "\t-q             Quiet mode\n"
        "\t-Ipath         Add path to the #include search path\n"
        "\t-Dsym[=val]    Define preprocessor symbol\n"
        "\t-Usym          Undefine preprocessor symbol\n"
        "\t-O0, -O1, -O2  Set optimization level (default=1)\n"
        "\t-d             Debug mode\n"
        "\t-E             Only preprocess the input and output to stdout\n"
        ;
}

namespace { // anonymous

// Subclass ErrorHandler because we want our messages to appear somewhat
// differant than the default ErrorHandler base class, in order to match
// typical compiler command line messages.
class OSLC_ErrorHandler : public ErrorHandler {
public:
    virtual void operator () (int errcode, const std::string &msg) {
        static OIIO::mutex err_mutex;
        OIIO::lock_guard guard (err_mutex);
        switch (errcode & 0xffff0000) {
        case EH_INFO :
            if (verbosity() >= VERBOSE)
                std::cout << msg << std::endl;
            break;
        case EH_WARNING :
            if (verbosity() >= NORMAL)
                std::cerr << msg << std::endl;
            break;
        case EH_ERROR :
            std::cerr << msg << std::endl;
            break;
        case EH_SEVERE :
            std::cerr << msg << std::endl;
            break;
        case EH_DEBUG :
#ifdef NDEBUG
            break;
#endif
        default :
            if (verbosity() > QUIET)
                std::cout << msg;
            break;
        }
    }
};

static OSLC_ErrorHandler default_oslc_error_handler;
} // anonymous namespace

int
main (int argc, const char *argv[])
{
    // Globally force classic "C" locale, and turn off all formatting
    // internationalization, for the entire oslc application.
    std::locale::global (std::locale::classic());

    OIIO::Filesystem::convert_native_arguments (argc, (const char **)argv);

    if (argc <= 1) {
        usage ();
        return EXIT_SUCCESS;
    }

    std::vector<std::string> args;
    bool quiet = false;
    std::string shader_path;

    // Parse arguments from command line
    for (int a = 1;  a < argc;  ++a) {
        if (! strcmp (argv[a], "--help") | ! strcmp (argv[a], "-h")) {
            usage ();
            return EXIT_SUCCESS;
        }
        else if (! strcmp (argv[a], "-v") ||
                 ! strcmp (argv[a], "-q") ||
                 ! strcmp (argv[a], "-d") ||
                 ! strcmp (argv[a], "-E") ||
                 ! strcmp (argv[a], "-O") || ! strcmp (argv[a], "-O0") ||
                 ! strcmp (argv[a], "-O1") || ! strcmp (argv[a], "-O2") ||
                 ! strcmp (argv[a], "-Werror")
                 ) {
            // Valid command-line argument
            args.emplace_back(argv[a]);
            quiet |= (strcmp (argv[a], "-q") == 0);
        }
        else if (! strcmp (argv[a], "-o") && a < argc-1) {
            // Output filepath
            args.emplace_back(argv[a]);
            ++a;
            args.emplace_back(argv[a]);
        }
        else if (argv[a][0] == '-' &&
                 (argv[a][1] == 'D' || argv[a][1] == 'U' || argv[a][1] == 'I')) {
            args.emplace_back(argv[a]);
        }
        else {
            // Shader to compile
            shader_path = argv[a];
        }
    }

    if (shader_path.empty ()) {
        std::cout << "ERROR: Missing shader path" << "\n\n";
        usage ();
        return EXIT_FAILURE;
    }

    OSLCompiler compiler (&default_oslc_error_handler);
    bool ok = compiler.compile (shader_path, args);
    if (ok) {
        if (!quiet)
            std::cout << "Compiled " << shader_path << " -> " << compiler.output_filename() << "\n";
    }
    else {
        std::cout << "FAILED " << shader_path << "\n";
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
<commit_msg>Add forgotten -Werror to oslc help message (#879)<commit_after>/*
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <cstring>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/sysutil.h>
#include <OpenImageIO/thread.h>

#include <OSL/oslcomp.h>
#include <OSL/oslexec.h>
using namespace OSL;

static void
usage ()
{
    std::cout <<
        "oslc -- Open Shading Language compiler " OSL_LIBRARY_VERSION_STRING "\n"
        OSL_COPYRIGHT_STRING "\n"
        "Usage:  oslc [options] file\n"
        "  Options:\n"
        "\t--help         Print this usage message\n"
        "\t-o filename    Specify output filename\n"
        "\t-v             Verbose mode\n"
        "\t-q             Quiet mode\n"
        "\t-Ipath         Add path to the #include search path\n"
        "\t-Dsym[=val]    Define preprocessor symbol\n"
        "\t-Usym          Undefine preprocessor symbol\n"
        "\t-O0, -O1, -O2  Set optimization level (default=1)\n"
        "\t-d             Debug mode\n"
        "\t-E             Only preprocess the input and output to stdout\n"
        "\t-Werror        Treat all warnings as errors\n"
        ;
}

namespace { // anonymous

// Subclass ErrorHandler because we want our messages to appear somewhat
// differant than the default ErrorHandler base class, in order to match
// typical compiler command line messages.
class OSLC_ErrorHandler : public ErrorHandler {
public:
    virtual void operator () (int errcode, const std::string &msg) {
        static OIIO::mutex err_mutex;
        OIIO::lock_guard guard (err_mutex);
        switch (errcode & 0xffff0000) {
        case EH_INFO :
            if (verbosity() >= VERBOSE)
                std::cout << msg << std::endl;
            break;
        case EH_WARNING :
            if (verbosity() >= NORMAL)
                std::cerr << msg << std::endl;
            break;
        case EH_ERROR :
            std::cerr << msg << std::endl;
            break;
        case EH_SEVERE :
            std::cerr << msg << std::endl;
            break;
        case EH_DEBUG :
#ifdef NDEBUG
            break;
#endif
        default :
            if (verbosity() > QUIET)
                std::cout << msg;
            break;
        }
    }
};

static OSLC_ErrorHandler default_oslc_error_handler;
} // anonymous namespace

int
main (int argc, const char *argv[])
{
    // Globally force classic "C" locale, and turn off all formatting
    // internationalization, for the entire oslc application.
    std::locale::global (std::locale::classic());

    OIIO::Filesystem::convert_native_arguments (argc, (const char **)argv);

    if (argc <= 1) {
        usage ();
        return EXIT_SUCCESS;
    }

    std::vector<std::string> args;
    bool quiet = false;
    std::string shader_path;

    // Parse arguments from command line
    for (int a = 1;  a < argc;  ++a) {
        if (! strcmp (argv[a], "--help") | ! strcmp (argv[a], "-h")) {
            usage ();
            return EXIT_SUCCESS;
        }
        else if (! strcmp (argv[a], "-v") ||
                 ! strcmp (argv[a], "-q") ||
                 ! strcmp (argv[a], "-d") ||
                 ! strcmp (argv[a], "-E") ||
                 ! strcmp (argv[a], "-O") || ! strcmp (argv[a], "-O0") ||
                 ! strcmp (argv[a], "-O1") || ! strcmp (argv[a], "-O2") ||
                 ! strcmp (argv[a], "-Werror")
                 ) {
            // Valid command-line argument
            args.emplace_back(argv[a]);
            quiet |= (strcmp (argv[a], "-q") == 0);
        }
        else if (! strcmp (argv[a], "-o") && a < argc-1) {
            // Output filepath
            args.emplace_back(argv[a]);
            ++a;
            args.emplace_back(argv[a]);
        }
        else if (argv[a][0] == '-' &&
                 (argv[a][1] == 'D' || argv[a][1] == 'U' || argv[a][1] == 'I')) {
            args.emplace_back(argv[a]);
        }
        else {
            // Shader to compile
            shader_path = argv[a];
        }
    }

    if (shader_path.empty ()) {
        std::cout << "ERROR: Missing shader path" << "\n\n";
        usage ();
        return EXIT_FAILURE;
    }

    OSLCompiler compiler (&default_oslc_error_handler);
    bool ok = compiler.compile (shader_path, args);
    if (ok) {
        if (!quiet)
            std::cout << "Compiled " << shader_path << " -> " << compiler.output_filename() << "\n";
    }
    else {
        std::cout << "FAILED " << shader_path << "\n";
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>