<commit_before>#include <silicium/source/received_from_socket_source.hpp>
#include <silicium/observable/flatten.hpp>
#include <silicium/asio/writing_observable.hpp>
#include <silicium/source/observable_source.hpp>
#include <silicium/asio/tcp_acceptor.hpp>
#include <silicium/observable/coroutine.hpp>
#include <silicium/observable/constant.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <silicium/http/http.hpp>
#include <silicium/observable/virtualized.hpp>
#include <silicium/source/virtualized_source.hpp>
#include <silicium/observable/total_consumer.hpp>
#include <silicium/observable/coroutine_generator.hpp>
#include <silicium/observable/erase_shared.hpp>
#include <silicium/observable/erase_unique.hpp>
#include <silicium/asio/reading_observable.hpp>
#include <silicium/terminate_on_exception.hpp>
#include <boost/format.hpp>
#include <boost/thread/future.hpp>
#include <cassert>

#define SILICIUM_EXAMPLE_AVAILABLE (SILICIUM_HAS_EXCEPTIONS && SILICIUM_HAS_YIELD_CONTEXT)

#if SILICIUM_EXAMPLE_AVAILABLE
#include <thread>

namespace
{
	template <class Socket>
	void serve_client(
		Socket &client,
		boost::uintmax_t visitor_number)
	{
		Si::received_from_socket_source bytes_receiver(client.receiving());
		Si::optional<Si::http::request> request = Si::http::parse_request(bytes_receiver);
		if (!request)
		{
			return;
		}
		std::vector<char> send_buffer;
		{
			auto response_sink = Si::make_container_sink(send_buffer);
			Si::http::response response;
			response.arguments = Si::make_unique<std::map<Si::noexcept_string, Si::noexcept_string>>();
			response.http_version = "HTTP/1.0";
			response.status = 200;
			response.status_text = "OK";
			std::string const body = boost::str(boost::format("Hello, visitor %1%") % visitor_number);
			(*response.arguments)["Content-Length"] = boost::lexical_cast<Si::noexcept_string>(body.size());
			(*response.arguments)["Connection"] = "close";
			Si::http::generate_response(response_sink, response);
			Si::append(response_sink, body);
		}
		client.send(Si::make_iterator_range(send_buffer.data(), send_buffer.data() + send_buffer.size()));
		client.shutdown();

		while (Si::get(bytes_receiver))
		{
		}
	}

	typedef Si::asio::reading_observable<boost::asio::ip::tcp::socket> socket_observable;

	struct coroutine_socket
	{
		explicit coroutine_socket(boost::asio::ip::tcp::socket &socket, Si::push_context<Si::nothing> &yield)
			: socket(&socket)
			, yield(&yield)
			, received(4096)
			, receiving_(Si::observable_source<socket_observable, Si::push_context<Si::nothing>>(socket_observable(socket, Si::make_iterator_range(received.data(), received.data() + received.size())), yield))
		{
		}

		Si::Source<Si::error_or<Si::memory_range>>::interface &receiving()
		{
			return receiving_;
		}

		void send(Si::iterator_range<char const *> data)
		{
			assert(socket);
			assert(yield);

			auto sending = Si::asio::make_writing_observable(*socket);
			sending.set_buffer(data);
			auto virtualized = Si::virtualize_observable<Si::ptr_observer<Si::observer<boost::system::error_code>>>(sending);

			//ignore error
			yield->get_one(virtualized);
		}

		void shutdown()
		{
			boost::system::error_code error;
			socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
		}

	private:

		boost::asio::ip::tcp::socket *socket;
		Si::push_context<Si::nothing> *yield;
		std::vector<char> received;
		Si::virtualized_source<Si::observable_source<socket_observable, Si::push_context<Si::nothing>>> receiving_;
	};

	struct thread_socket_source : Si::Source<Si::error_or<Si::memory_range>>::interface
	{
		typedef Si::error_or<Si::memory_range> element_type;

		explicit thread_socket_source(boost::asio::ip::tcp::socket &socket)
			: socket(&socket)
			, received(4096)
		{
		}

		boost::asio::ip::tcp::socket *get_socket() const
		{
			return socket;
		}

		virtual Si::iterator_range<element_type const *> map_next(std::size_t size) SILICIUM_OVERRIDE
		{
			(void)size;
			return Si::iterator_range<element_type const *>();
		}

		virtual element_type *copy_next(Si::iterator_range<element_type *> destination) SILICIUM_OVERRIDE
		{
			assert(socket);
			auto *i = destination.begin();
			if (i != destination.end())
			{
				boost::system::error_code ec;
				auto const bytes_received = socket->receive(boost::asio::buffer(received), 0, ec);
				if (ec)
				{
					*i = ec;
				}
				else
				{
					*i = Si::make_memory_range<char const>(received.data(), received.data() + bytes_received);
				}
				++i;
			}
			return i;
		}

	private:

		boost::asio::ip::tcp::socket *socket;
		std::vector<char> received;
	};

	struct thread_socket
	{
		explicit thread_socket(boost::asio::ip::tcp::socket &socket)
			: receiving_(socket)
		{
		}

		Si::Source<Si::error_or<Si::memory_range>>::interface &receiving()
		{
			return receiving_;
		}

		void send(Si::iterator_range<char const *> data)
		{
			assert(receiving_.get_socket());
			boost::asio::write(*receiving_.get_socket(), boost::asio::buffer(data.begin(), data.size()));
		}

		void shutdown()
		{
			assert(receiving_.get_socket());
			boost::system::error_code error;
			receiving_.get_socket()->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
		}

	private:

		thread_socket_source receiving_;
	};

	typedef Si::shared_observable<Si::nothing> events;

#if SILICIUM_EXAMPLE_AVAILABLE
	struct coroutine_web_server
	{
		explicit coroutine_web_server(boost::asio::io_service &io, boost::uint16_t port)
			: acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), port))
			, clients(&acceptor)
			, all_work(Si::make_total_consumer(Si::erase_unique(Si::flatten<boost::mutex>(Si::make_coroutine_generator<events>([this](Si::push_context<events> &yield) -> void
			{
				boost::uintmax_t visitor_count = 0;
				for (;;)
				{
					auto result = yield.get_one(clients);
					if (!result)
					{
						break;
					}
					++visitor_count;
					std::shared_ptr<boost::asio::ip::tcp::socket> client = result->get();
					auto context =
						[visitor_count, client]() -> events
					{
						auto visitor_number_ = visitor_count;
						auto client_handler = Si::erase_shared(Si::make_coroutine_generator<Si::nothing>([client, visitor_number_](Si::push_context<Si::nothing> &yield) -> void
						{
							coroutine_socket coro_socket(*client, yield);
							return serve_client(coro_socket, visitor_number_);
						}));
						return client_handler;
					}();
					if (!context.empty())
					{
						yield(std::move(context));
					}
				}
			})))))
		{
		}

		void start()
		{
			all_work.start();
		}

	private:

		boost::asio::ip::tcp::acceptor acceptor;
		Si::asio::tcp_acceptor<boost::asio::ip::tcp::acceptor *> clients;
		Si::total_consumer<Si::unique_observable<Si::nothing>> all_work;
	};

	struct thread_web_server
	{
		explicit thread_web_server(boost::asio::io_service &io, boost::uint16_t port)
			: acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), port))
			, clients(&acceptor)
			, all_work(Si::make_total_consumer(Si::erase_unique(Si::flatten<boost::mutex>(Si::make_coroutine_generator<events>([this](Si::push_context<events> &yield) -> void
			{
				boost::uintmax_t visitor_count = 0;
				for (;;)
				{
					auto result = yield.get_one(clients);
					if (!result)
					{
						break;
					}
					++visitor_count;
					std::shared_ptr<boost::asio::ip::tcp::socket> client = result->get();
					std::thread([client, visitor_count]
					{
						thread_socket threaded_socket(*client);
						serve_client(threaded_socket, visitor_count);
					}).detach();
				}
			})))))
		{
		}

		void start()
		{
			all_work.start();
		}

	private:

		boost::asio::ip::tcp::acceptor acceptor;
		Si::asio::tcp_acceptor<boost::asio::ip::tcp::acceptor *> clients;
		Si::total_consumer<Si::unique_observable<Si::nothing>> all_work;
	};
#endif
}
#endif

int main()
{
	boost::asio::io_service io;

#if SILICIUM_EXAMPLE_AVAILABLE
	coroutine_web_server coroutined(io, 8080);
	coroutined.start();

	thread_web_server threaded(io, 8081);
	threaded.start();

	auto const thread_count = boost::thread::hardware_concurrency();

	std::vector<boost::unique_future<void>> workers;
	std::generate_n(std::back_inserter(workers), thread_count - 1, [&io]
	{
		return boost::async(boost::launch::async, [&io]
		{
			io.run();
		});
	});
	std::for_each(workers.begin(), workers.end(), [](boost::unique_future<void> &worker)
	{
		worker.get();
	});
#else
	std::cerr << "This example requires coroutine support\n";
#endif
	io.run();
}
<commit_msg>example depends on Boost.Coroutine<commit_after>#include <silicium/source/received_from_socket_source.hpp>
#include <silicium/observable/flatten.hpp>
#include <silicium/asio/writing_observable.hpp>
#include <silicium/source/observable_source.hpp>
#include <silicium/asio/tcp_acceptor.hpp>
#include <silicium/observable/coroutine.hpp>
#include <silicium/observable/constant.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <silicium/http/http.hpp>
#include <silicium/observable/virtualized.hpp>
#include <silicium/source/virtualized_source.hpp>
#include <silicium/observable/total_consumer.hpp>
#include <silicium/observable/coroutine_generator.hpp>
#include <silicium/observable/erase_shared.hpp>
#include <silicium/observable/erase_unique.hpp>
#include <silicium/asio/reading_observable.hpp>
#include <silicium/terminate_on_exception.hpp>
#include <boost/format.hpp>
#include <boost/thread/future.hpp>
#include <cassert>

#define SILICIUM_EXAMPLE_AVAILABLE (SILICIUM_HAS_EXCEPTIONS && SILICIUM_HAS_YIELD_CONTEXT && SILICIUM_HAS_COROUTINE_GENERATOR)

#if SILICIUM_EXAMPLE_AVAILABLE
#include <thread>

namespace
{
	template <class Socket>
	void serve_client(
		Socket &client,
		boost::uintmax_t visitor_number)
	{
		Si::received_from_socket_source bytes_receiver(client.receiving());
		Si::optional<Si::http::request> request = Si::http::parse_request(bytes_receiver);
		if (!request)
		{
			return;
		}
		std::vector<char> send_buffer;
		{
			auto response_sink = Si::make_container_sink(send_buffer);
			Si::http::response response;
			response.arguments = Si::make_unique<std::map<Si::noexcept_string, Si::noexcept_string>>();
			response.http_version = "HTTP/1.0";
			response.status = 200;
			response.status_text = "OK";
			std::string const body = boost::str(boost::format("Hello, visitor %1%") % visitor_number);
			(*response.arguments)["Content-Length"] = boost::lexical_cast<Si::noexcept_string>(body.size());
			(*response.arguments)["Connection"] = "close";
			Si::http::generate_response(response_sink, response);
			Si::append(response_sink, body);
		}
		client.send(Si::make_iterator_range(send_buffer.data(), send_buffer.data() + send_buffer.size()));
		client.shutdown();

		while (Si::get(bytes_receiver))
		{
		}
	}

	typedef Si::asio::reading_observable<boost::asio::ip::tcp::socket> socket_observable;

	struct coroutine_socket
	{
		explicit coroutine_socket(boost::asio::ip::tcp::socket &socket, Si::push_context<Si::nothing> &yield)
			: socket(&socket)
			, yield(&yield)
			, received(4096)
			, receiving_(Si::observable_source<socket_observable, Si::push_context<Si::nothing>>(socket_observable(socket, Si::make_iterator_range(received.data(), received.data() + received.size())), yield))
		{
		}

		Si::Source<Si::error_or<Si::memory_range>>::interface &receiving()
		{
			return receiving_;
		}

		void send(Si::iterator_range<char const *> data)
		{
			assert(socket);
			assert(yield);

			auto sending = Si::asio::make_writing_observable(*socket);
			sending.set_buffer(data);
			auto virtualized = Si::virtualize_observable<Si::ptr_observer<Si::observer<boost::system::error_code>>>(sending);

			//ignore error
			yield->get_one(virtualized);
		}

		void shutdown()
		{
			boost::system::error_code error;
			socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
		}

	private:

		boost::asio::ip::tcp::socket *socket;
		Si::push_context<Si::nothing> *yield;
		std::vector<char> received;
		Si::virtualized_source<Si::observable_source<socket_observable, Si::push_context<Si::nothing>>> receiving_;
	};

	struct thread_socket_source : Si::Source<Si::error_or<Si::memory_range>>::interface
	{
		typedef Si::error_or<Si::memory_range> element_type;

		explicit thread_socket_source(boost::asio::ip::tcp::socket &socket)
			: socket(&socket)
			, received(4096)
		{
		}

		boost::asio::ip::tcp::socket *get_socket() const
		{
			return socket;
		}

		virtual Si::iterator_range<element_type const *> map_next(std::size_t size) SILICIUM_OVERRIDE
		{
			(void)size;
			return Si::iterator_range<element_type const *>();
		}

		virtual element_type *copy_next(Si::iterator_range<element_type *> destination) SILICIUM_OVERRIDE
		{
			assert(socket);
			auto *i = destination.begin();
			if (i != destination.end())
			{
				boost::system::error_code ec;
				auto const bytes_received = socket->receive(boost::asio::buffer(received), 0, ec);
				if (ec)
				{
					*i = ec;
				}
				else
				{
					*i = Si::make_memory_range<char const>(received.data(), received.data() + bytes_received);
				}
				++i;
			}
			return i;
		}

	private:

		boost::asio::ip::tcp::socket *socket;
		std::vector<char> received;
	};

	struct thread_socket
	{
		explicit thread_socket(boost::asio::ip::tcp::socket &socket)
			: receiving_(socket)
		{
		}

		Si::Source<Si::error_or<Si::memory_range>>::interface &receiving()
		{
			return receiving_;
		}

		void send(Si::iterator_range<char const *> data)
		{
			assert(receiving_.get_socket());
			boost::asio::write(*receiving_.get_socket(), boost::asio::buffer(data.begin(), data.size()));
		}

		void shutdown()
		{
			assert(receiving_.get_socket());
			boost::system::error_code error;
			receiving_.get_socket()->shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
		}

	private:

		thread_socket_source receiving_;
	};

	typedef Si::shared_observable<Si::nothing> events;

#if SILICIUM_EXAMPLE_AVAILABLE
	struct coroutine_web_server
	{
		explicit coroutine_web_server(boost::asio::io_service &io, boost::uint16_t port)
			: acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), port))
			, clients(&acceptor)
			, all_work(Si::make_total_consumer(Si::erase_unique(Si::flatten<boost::mutex>(Si::make_coroutine_generator<events>([this](Si::push_context<events> &yield) -> void
			{
				boost::uintmax_t visitor_count = 0;
				for (;;)
				{
					auto result = yield.get_one(clients);
					if (!result)
					{
						break;
					}
					++visitor_count;
					std::shared_ptr<boost::asio::ip::tcp::socket> client = result->get();
					auto context =
						[visitor_count, client]() -> events
					{
						auto visitor_number_ = visitor_count;
						auto client_handler = Si::erase_shared(Si::make_coroutine_generator<Si::nothing>([client, visitor_number_](Si::push_context<Si::nothing> &yield) -> void
						{
							coroutine_socket coro_socket(*client, yield);
							return serve_client(coro_socket, visitor_number_);
						}));
						return client_handler;
					}();
					if (!context.empty())
					{
						yield(std::move(context));
					}
				}
			})))))
		{
		}

		void start()
		{
			all_work.start();
		}

	private:

		boost::asio::ip::tcp::acceptor acceptor;
		Si::asio::tcp_acceptor<boost::asio::ip::tcp::acceptor *> clients;
		Si::total_consumer<Si::unique_observable<Si::nothing>> all_work;
	};

	struct thread_web_server
	{
		explicit thread_web_server(boost::asio::io_service &io, boost::uint16_t port)
			: acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), port))
			, clients(&acceptor)
			, all_work(Si::make_total_consumer(Si::erase_unique(Si::flatten<boost::mutex>(Si::make_coroutine_generator<events>([this](Si::push_context<events> &yield) -> void
			{
				boost::uintmax_t visitor_count = 0;
				for (;;)
				{
					auto result = yield.get_one(clients);
					if (!result)
					{
						break;
					}
					++visitor_count;
					std::shared_ptr<boost::asio::ip::tcp::socket> client = result->get();
					std::thread([client, visitor_count]
					{
						thread_socket threaded_socket(*client);
						serve_client(threaded_socket, visitor_count);
					}).detach();
				}
			})))))
		{
		}

		void start()
		{
			all_work.start();
		}

	private:

		boost::asio::ip::tcp::acceptor acceptor;
		Si::asio::tcp_acceptor<boost::asio::ip::tcp::acceptor *> clients;
		Si::total_consumer<Si::unique_observable<Si::nothing>> all_work;
	};
#endif
}
#endif

int main()
{
	boost::asio::io_service io;

#if SILICIUM_EXAMPLE_AVAILABLE
	coroutine_web_server coroutined(io, 8080);
	coroutined.start();

	thread_web_server threaded(io, 8081);
	threaded.start();

	auto const thread_count = boost::thread::hardware_concurrency();

	std::vector<boost::unique_future<void>> workers;
	std::generate_n(std::back_inserter(workers), thread_count - 1, [&io]
	{
		return boost::async(boost::launch::async, [&io]
		{
			io.run();
		});
	});
	std::for_each(workers.begin(), workers.end(), [](boost::unique_future<void> &worker)
	{
		worker.get();
	});
#else
	std::cerr << "This example requires coroutine support\n";
#endif
	io.run();
}
<|endoftext|>


<commit_before>#include "arithmetics.hpp"

namespace arithmetics {

int add(int a, int b) { return a + b; }

int add_buggy(int a, int b) { return a + b; }
}
<commit_msg>reintroduce bug to test circleci caching<commit_after>#include "arithmetics.hpp"

namespace arithmetics {

int add(int a, int b) { return a + b; }

int add_buggy(int a, int b) { return a + b + 1; }
}
<|endoftext|>


<commit_before>#include "caffe2/core/types.h"
#include "caffe2/core/typeid.h"

#include <atomic>
#include <memory>
#include <string>
#include <vector>

namespace caffe2 {

CAFFE_KNOWN_TYPE(float);
CAFFE_KNOWN_TYPE(int);
CAFFE_KNOWN_TYPE(std::string);
CAFFE_KNOWN_TYPE(bool);
CAFFE_KNOWN_TYPE(uint8_t);
CAFFE_KNOWN_TYPE(int8_t);
CAFFE_KNOWN_TYPE(uint16_t);
CAFFE_KNOWN_TYPE(int16_t);
CAFFE_KNOWN_TYPE(int64_t);
CAFFE_KNOWN_TYPE(long);
CAFFE_KNOWN_TYPE(float16);
CAFFE_KNOWN_TYPE(double);
CAFFE_KNOWN_TYPE(char);
CAFFE_KNOWN_TYPE(std::unique_ptr<std::mutex>);
CAFFE_KNOWN_TYPE(std::unique_ptr<std::atomic<bool>>);
CAFFE_KNOWN_TYPE(std::vector<int64_t>);
CAFFE_KNOWN_TYPE(std::vector<long>);
CAFFE_KNOWN_TYPE(std::vector<unsigned long>);

TensorProto::DataType TypeMetaToDataType(const TypeMeta& meta) {
  static_assert(sizeof(int) == 4,
                "int in this compiler does not equal to 4 bytes.");
  static std::map<CaffeTypeId, TensorProto::DataType> data_type_map {
    {TypeMeta::Id<float>(), TensorProto_DataType_FLOAT},
    {TypeMeta::Id<int>(), TensorProto_DataType_INT32},
    // BYTE does not have a type meta to proto mapping: we should
    // always use uint8_t when serializing. BYTE is kept for backward
    // compatibility.
    // {TypeMeta::Id<>(), TensorProto_DataType_BYTE},
    {TypeMeta::Id<string>(), TensorProto_DataType_STRING},
    {TypeMeta::Id<bool>(), TensorProto_DataType_BOOL},
    {TypeMeta::Id<uint8_t>(), TensorProto_DataType_UINT8},
    {TypeMeta::Id<int8_t>(), TensorProto_DataType_INT8},
    {TypeMeta::Id<uint16_t>(), TensorProto_DataType_UINT16},
    {TypeMeta::Id<int16_t>(), TensorProto_DataType_INT16},
    {TypeMeta::Id<int64_t>(), TensorProto_DataType_INT64},
    {TypeMeta::Id<float16>(), TensorProto_DataType_FLOAT16},
    {TypeMeta::Id<double>(), TensorProto_DataType_DOUBLE},
  };
  const auto it = data_type_map.find(meta.id());
  return (it == data_type_map.end()
          ? TensorProto_DataType_UNDEFINED : it->second);
}

const TypeMeta& DataTypeToTypeMeta(const TensorProto::DataType& dt) {
  static std::map<TensorProto::DataType, TypeMeta> type_meta_map{
      {TensorProto_DataType_FLOAT, TypeMeta::Make<float>()},
      {TensorProto_DataType_INT32, TypeMeta::Make<int>()},
      {TensorProto_DataType_STRING, TypeMeta::Make<std::string>()},
      {TensorProto_DataType_BOOL, TypeMeta::Make<bool>()},
      {TensorProto_DataType_UINT8, TypeMeta::Make<uint8_t>()},
      {TensorProto_DataType_INT8, TypeMeta::Make<int8_t>()},
      {TensorProto_DataType_UINT16, TypeMeta::Make<uint16_t>()},
      {TensorProto_DataType_INT16, TypeMeta::Make<int16_t>()},
      {TensorProto_DataType_INT64, TypeMeta::Make<int64_t>()},
      {TensorProto_DataType_FLOAT16, TypeMeta::Make<float16>()},
      {TensorProto_DataType_DOUBLE, TypeMeta::Make<double>()},
  };
  const auto it = type_meta_map.find(dt);
  if (it == type_meta_map.end()) {
    throw std::runtime_error("Unknown data type.");
  }
  return it->second;
}

}  // namespace caffe2
<commit_msg>Fix duplicate definition bug (only present in GCC)<commit_after>#include "caffe2/core/types.h"
#include "caffe2/core/typeid.h"

#include <atomic>
#include <memory>
#include <string>
#include <vector>

namespace caffe2 {

CAFFE_KNOWN_TYPE(float);
CAFFE_KNOWN_TYPE(int);
CAFFE_KNOWN_TYPE(std::string);
CAFFE_KNOWN_TYPE(bool);
CAFFE_KNOWN_TYPE(uint8_t);
CAFFE_KNOWN_TYPE(int8_t);
CAFFE_KNOWN_TYPE(uint16_t);
CAFFE_KNOWN_TYPE(int16_t);
CAFFE_KNOWN_TYPE(int64_t);
#if __clang__
CAFFE_KNOWN_TYPE(long);
#endif
CAFFE_KNOWN_TYPE(float16);
CAFFE_KNOWN_TYPE(double);
CAFFE_KNOWN_TYPE(char);
CAFFE_KNOWN_TYPE(std::unique_ptr<std::mutex>);
CAFFE_KNOWN_TYPE(std::unique_ptr<std::atomic<bool>>);
CAFFE_KNOWN_TYPE(std::vector<int64_t>);
#if __clang__
CAFFE_KNOWN_TYPE(std::vector<long>);
#endif
CAFFE_KNOWN_TYPE(std::vector<unsigned long>);

TensorProto::DataType TypeMetaToDataType(const TypeMeta& meta) {
  static_assert(sizeof(int) == 4,
                "int in this compiler does not equal to 4 bytes.");
  static std::map<CaffeTypeId, TensorProto::DataType> data_type_map {
    {TypeMeta::Id<float>(), TensorProto_DataType_FLOAT},
    {TypeMeta::Id<int>(), TensorProto_DataType_INT32},
    // BYTE does not have a type meta to proto mapping: we should
    // always use uint8_t when serializing. BYTE is kept for backward
    // compatibility.
    // {TypeMeta::Id<>(), TensorProto_DataType_BYTE},
    {TypeMeta::Id<string>(), TensorProto_DataType_STRING},
    {TypeMeta::Id<bool>(), TensorProto_DataType_BOOL},
    {TypeMeta::Id<uint8_t>(), TensorProto_DataType_UINT8},
    {TypeMeta::Id<int8_t>(), TensorProto_DataType_INT8},
    {TypeMeta::Id<uint16_t>(), TensorProto_DataType_UINT16},
    {TypeMeta::Id<int16_t>(), TensorProto_DataType_INT16},
    {TypeMeta::Id<int64_t>(), TensorProto_DataType_INT64},
    {TypeMeta::Id<float16>(), TensorProto_DataType_FLOAT16},
    {TypeMeta::Id<double>(), TensorProto_DataType_DOUBLE},
  };
  const auto it = data_type_map.find(meta.id());
  return (it == data_type_map.end()
          ? TensorProto_DataType_UNDEFINED : it->second);
}

const TypeMeta& DataTypeToTypeMeta(const TensorProto::DataType& dt) {
  static std::map<TensorProto::DataType, TypeMeta> type_meta_map{
      {TensorProto_DataType_FLOAT, TypeMeta::Make<float>()},
      {TensorProto_DataType_INT32, TypeMeta::Make<int>()},
      {TensorProto_DataType_STRING, TypeMeta::Make<std::string>()},
      {TensorProto_DataType_BOOL, TypeMeta::Make<bool>()},
      {TensorProto_DataType_UINT8, TypeMeta::Make<uint8_t>()},
      {TensorProto_DataType_INT8, TypeMeta::Make<int8_t>()},
      {TensorProto_DataType_UINT16, TypeMeta::Make<uint16_t>()},
      {TensorProto_DataType_INT16, TypeMeta::Make<int16_t>()},
      {TensorProto_DataType_INT64, TypeMeta::Make<int64_t>()},
      {TensorProto_DataType_FLOAT16, TypeMeta::Make<float16>()},
      {TensorProto_DataType_DOUBLE, TypeMeta::Make<double>()},
  };
  const auto it = type_meta_map.find(dt);
  if (it == type_meta_map.end()) {
    throw std::runtime_error("Unknown data type.");
  }
  return it->second;
}

}  // namespace caffe2
<|endoftext|>


<commit_before>//===--- PPC.cpp - PPC Helpers for Tools ------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "PPC.h"
#include "ToolChains/CommonArgs.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/ArgList.h"

using namespace clang::driver;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm::opt;

/// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
std::string ppc::getPPCTargetCPU(const ArgList &Args) {
  if (Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ)) {
    StringRef CPUName = A->getValue();

    if (CPUName == "native") {
      std::string CPU = llvm::sys::getHostCPUName();
      if (!CPU.empty() && CPU != "generic")
        return CPU;
      else
        return "";
    }

    return llvm::StringSwitch<const char *>(CPUName)
        .Case("common", "generic")
        .Case("440", "440")
        .Case("440fp", "440")
        .Case("450", "450")
        .Case("601", "601")
        .Case("602", "602")
        .Case("603", "603")
        .Case("603e", "603e")
        .Case("603ev", "603ev")
        .Case("604", "604")
        .Case("604e", "604e")
        .Case("620", "620")
        .Case("630", "pwr3")
        .Case("G3", "g3")
        .Case("7400", "7400")
        .Case("G4", "g4")
        .Case("7450", "7450")
        .Case("G4+", "g4+")
        .Case("750", "750")
        .Case("970", "970")
        .Case("G5", "g5")
        .Case("a2", "a2")
        .Case("a2q", "a2q")
        .Case("e500mc", "e500mc")
        .Case("e5500", "e5500")
        .Case("power3", "pwr3")
        .Case("power4", "pwr4")
        .Case("power5", "pwr5")
        .Case("power5x", "pwr5x")
        .Case("power6", "pwr6")
        .Case("power6x", "pwr6x")
        .Case("power7", "pwr7")
        .Case("power8", "pwr8")
        .Case("power9", "pwr9")
        .Case("pwr3", "pwr3")
        .Case("pwr4", "pwr4")
        .Case("pwr5", "pwr5")
        .Case("pwr5x", "pwr5x")
        .Case("pwr6", "pwr6")
        .Case("pwr6x", "pwr6x")
        .Case("pwr7", "pwr7")
        .Case("pwr8", "pwr8")
        .Case("pwr9", "pwr9")
        .Case("powerpc", "ppc")
        .Case("powerpc64", "ppc64")
        .Case("powerpc64le", "ppc64le")
        .Default("");
  }

  return "";
}

const char *ppc::getPPCAsmModeForCPU(StringRef Name) {
  return llvm::StringSwitch<const char *>(Name)
        .Case("pwr7", "-mpower7")
        .Case("power7", "-mpower7")
        .Case("pwr8", "-mpower8")
        .Case("power8", "-mpower8")
        .Case("ppc64le", "-mpower8")
        .Case("pwr9", "-mpower9")
        .Case("power9", "-mpower9")
        .Default("-many");
}

void ppc::getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
                               const ArgList &Args,
                               std::vector<StringRef> &Features) {
  handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);

  ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
  if (FloatABI == ppc::FloatABI::Soft)
    Features.push_back("-hard-float");

  ppc::ReadGOTPtrMode ReadGOT = ppc::getPPCReadGOTPtrMode(D, Triple, Args);
  if (ReadGOT == ppc::ReadGOTPtrMode::SecurePlt)
    Features.push_back("+secure-plt");
}

ppc::ReadGOTPtrMode ppc::getPPCReadGOTPtrMode(const Driver &D, const llvm::Triple &Triple,
                                              const ArgList &Args) {
  if (Args.getLastArg(options::OPT_msecure_plt))
    return ppc::ReadGOTPtrMode::SecurePlt;
  if (Triple.isOSNetBSD() || Triple.isOSOpenBSD())
    return ppc::ReadGOTPtrMode::SecurePlt;
  else
    return ppc::ReadGOTPtrMode::Bss;
}

ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
  ppc::FloatABI ABI = ppc::FloatABI::Invalid;
  if (Arg *A =
          Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
                          options::OPT_mfloat_abi_EQ)) {
    if (A->getOption().matches(options::OPT_msoft_float))
      ABI = ppc::FloatABI::Soft;
    else if (A->getOption().matches(options::OPT_mhard_float))
      ABI = ppc::FloatABI::Hard;
    else {
      ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
                .Case("soft", ppc::FloatABI::Soft)
                .Case("hard", ppc::FloatABI::Hard)
                .Default(ppc::FloatABI::Invalid);
      if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
        D.Diag(clang::diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
        ABI = ppc::FloatABI::Hard;
      }
    }
  }

  // If unspecified, choose the default based on the platform.
  if (ABI == ppc::FloatABI::Invalid) {
    ABI = ppc::FloatABI::Hard;
  }

  return ABI;
}

bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  return A && (A->getValue() == StringRef(Value));
}
<commit_msg>[PowerPC] Set the default PLT mode on musl to Secure PLT<commit_after>//===--- PPC.cpp - PPC Helpers for Tools ------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "PPC.h"
#include "ToolChains/CommonArgs.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/ArgList.h"

using namespace clang::driver;
using namespace clang::driver::tools;
using namespace clang;
using namespace llvm::opt;

/// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
std::string ppc::getPPCTargetCPU(const ArgList &Args) {
  if (Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ)) {
    StringRef CPUName = A->getValue();

    if (CPUName == "native") {
      std::string CPU = llvm::sys::getHostCPUName();
      if (!CPU.empty() && CPU != "generic")
        return CPU;
      else
        return "";
    }

    return llvm::StringSwitch<const char *>(CPUName)
        .Case("common", "generic")
        .Case("440", "440")
        .Case("440fp", "440")
        .Case("450", "450")
        .Case("601", "601")
        .Case("602", "602")
        .Case("603", "603")
        .Case("603e", "603e")
        .Case("603ev", "603ev")
        .Case("604", "604")
        .Case("604e", "604e")
        .Case("620", "620")
        .Case("630", "pwr3")
        .Case("G3", "g3")
        .Case("7400", "7400")
        .Case("G4", "g4")
        .Case("7450", "7450")
        .Case("G4+", "g4+")
        .Case("750", "750")
        .Case("970", "970")
        .Case("G5", "g5")
        .Case("a2", "a2")
        .Case("a2q", "a2q")
        .Case("e500mc", "e500mc")
        .Case("e5500", "e5500")
        .Case("power3", "pwr3")
        .Case("power4", "pwr4")
        .Case("power5", "pwr5")
        .Case("power5x", "pwr5x")
        .Case("power6", "pwr6")
        .Case("power6x", "pwr6x")
        .Case("power7", "pwr7")
        .Case("power8", "pwr8")
        .Case("power9", "pwr9")
        .Case("pwr3", "pwr3")
        .Case("pwr4", "pwr4")
        .Case("pwr5", "pwr5")
        .Case("pwr5x", "pwr5x")
        .Case("pwr6", "pwr6")
        .Case("pwr6x", "pwr6x")
        .Case("pwr7", "pwr7")
        .Case("pwr8", "pwr8")
        .Case("pwr9", "pwr9")
        .Case("powerpc", "ppc")
        .Case("powerpc64", "ppc64")
        .Case("powerpc64le", "ppc64le")
        .Default("");
  }

  return "";
}

const char *ppc::getPPCAsmModeForCPU(StringRef Name) {
  return llvm::StringSwitch<const char *>(Name)
        .Case("pwr7", "-mpower7")
        .Case("power7", "-mpower7")
        .Case("pwr8", "-mpower8")
        .Case("power8", "-mpower8")
        .Case("ppc64le", "-mpower8")
        .Case("pwr9", "-mpower9")
        .Case("power9", "-mpower9")
        .Default("-many");
}

void ppc::getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
                               const ArgList &Args,
                               std::vector<StringRef> &Features) {
  handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);

  ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
  if (FloatABI == ppc::FloatABI::Soft)
    Features.push_back("-hard-float");

  ppc::ReadGOTPtrMode ReadGOT = ppc::getPPCReadGOTPtrMode(D, Triple, Args);
  if (ReadGOT == ppc::ReadGOTPtrMode::SecurePlt)
    Features.push_back("+secure-plt");
}

ppc::ReadGOTPtrMode ppc::getPPCReadGOTPtrMode(const Driver &D, const llvm::Triple &Triple,
                                              const ArgList &Args) {
  if (Args.getLastArg(options::OPT_msecure_plt))
    return ppc::ReadGOTPtrMode::SecurePlt;
  if (Triple.isOSNetBSD() || Triple.isOSOpenBSD() || Triple.isMusl())
    return ppc::ReadGOTPtrMode::SecurePlt;
  else
    return ppc::ReadGOTPtrMode::Bss;
}

ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
  ppc::FloatABI ABI = ppc::FloatABI::Invalid;
  if (Arg *A =
          Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
                          options::OPT_mfloat_abi_EQ)) {
    if (A->getOption().matches(options::OPT_msoft_float))
      ABI = ppc::FloatABI::Soft;
    else if (A->getOption().matches(options::OPT_mhard_float))
      ABI = ppc::FloatABI::Hard;
    else {
      ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
                .Case("soft", ppc::FloatABI::Soft)
                .Case("hard", ppc::FloatABI::Hard)
                .Default(ppc::FloatABI::Invalid);
      if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
        D.Diag(clang::diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
        ABI = ppc::FloatABI::Hard;
      }
    }
  }

  // If unspecified, choose the default based on the platform.
  if (ABI == ppc::FloatABI::Invalid) {
    ABI = ppc::FloatABI::Hard;
  }

  return ABI;
}

bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
  Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
  return A && (A->getValue() == StringRef(Value));
}
<|endoftext|>


<commit_before>//
//  AsteroidSystem.cpp
//  COMP371_Framework
//
//  Created by Mark Massoud on 2015-08-02.
//  Copyright (c) 2015 Concordia. All rights reserved.
//

#include "AsteroidSystem.h"
#include "ParticleDescriptor.h"
#include "ParticleEmitter.h"
#include "EventManager.h"
#include "World.h"

#include <glm/gtc/matrix_transform.hpp>
#include <glm/common.hpp>

using namespace glm;

AsteroidSystem::AsteroidSystem(ParticleEmitter* emitter, ParticleDescriptor* descriptor)
: mpDescriptor(descriptor), mpEmitter(emitter)
{
    assert(mpDescriptor != nullptr);
    assert(mpEmitter != nullptr);

	#if defined(PLATFORM_OSX)
		int textureID = TextureLoader::LoadTexture("Textures/asteroidTexture.jpg");
	#else
		int textureID = TextureLoader::LoadTexture("../Assets/Textures/asteroidTexture.jpg");
	#endif

    // Update Event Manager - Frame time / input / events processing

    // Pre-allocate the maximum number of particles at a give time, according to
    // lifetime and emission rate
    int maxAsteroids = static_cast<int>(mpDescriptor->emissionRate * (mpDescriptor->totalLifetime + mpDescriptor->totalLifetimeDelta)) + 1;

    mInactiveAsteroids.resize(maxAsteroids);
    for (std::vector<Asteroid*>::iterator it = mInactiveAsteroids.begin(); it != mInactiveAsteroids.end(); ++it)
    {
		*it = new Asteroid(mpEmitter->GetAsteroidRandomPosition(), textureID);
    }

}

AsteroidSystem::~AsteroidSystem()
{
    // TODO: DESTROY MODEL STUFF INSTEAD
    for (std::vector<Asteroid*>::iterator it = mInactiveAsteroids.begin(); it != mInactiveAsteroids.end(); ++it)
    {
        delete *it;
    }

    for (std::vector<Asteroid*>::iterator it = mAsteroidList.begin(); it != mAsteroidList.end(); ++it)
    {
        delete *it;
    }

    mInactiveAsteroids.resize(0);
    mAsteroidList.resize(0);
}

void AsteroidSystem::Update(float dt)
{
    // Emit particle according to the emission rate
    float averageTimeBetweenEmission = 10.0f / mpDescriptor->emissionRate;
    float randomValue = EventManager::GetRandomFloat(0.0f, 1.0f) * averageTimeBetweenEmission;

    while (mInactiveAsteroids.size() > 0 && randomValue < dt)
    {
        randomValue += averageTimeBetweenEmission;

        Asteroid* newAsteroid = mInactiveAsteroids.back();
        mAsteroidList.push_back(newAsteroid);
        mInactiveAsteroids.pop_back();

        newAsteroid->SetPosition(mpEmitter->GetAsteroidRandomPosition());

        // giving random size to asteroids
		float randomSize = mpEmitter->GetRandomFloat(1, 3);
		newAsteroid->SetScaling(vec3(randomSize));

        mpEmitter = new ParticleEmitter(vec3(0.0f, 0.0f, 0.0f), newAsteroid);
        mpDescriptor = new ParticleDescriptor();

		mpDescriptor->setInitialSize(vec2(randomSize));

        mpDescriptor->SetAsteroidDescriptor();

        ParticleSystem* ps = new ParticleSystem(mpEmitter, mpDescriptor);

        newAsteroid->setParticleSystem(ps);
    }

    for (std::vector<Asteroid*>::iterator it = mAsteroidList.begin(); it != mAsteroidList.end(); )
    {
        Asteroid* a = (*it);
        a->Update(dt);
        a->getParticleSystem()->Update(dt);

        // TODO: modify so that asteroid dies if:
        // 1: asteroid has been shot x times and has no more lives
        // 2: asteroid has reached World origin vec3(0.0f, 0.0f, 0.0f)
        if (a->GetPosition().x >= -2.0f && a->GetPosition().x <= 2.0f)
        {
            std::cout << a->GetPosition().x << " has been destroyed." << std::endl;

            mInactiveAsteroids.push_back(a);

            delete a->getParticleSystem();

            it = mAsteroidList.erase(it);
        }
        else
        {
            ++it;
        }

    }

}

void AsteroidSystem::Draw() {

    for(Asteroid* asteroid : mAsteroidList) {
        asteroid->Draw();
    }

}<commit_msg>Decreased rate of asteroids generation<commit_after>//
//  AsteroidSystem.cpp
//  COMP371_Framework
//
//  Created by Mark Massoud on 2015-08-02.
//  Copyright (c) 2015 Concordia. All rights reserved.
//

#include "AsteroidSystem.h"
#include "ParticleDescriptor.h"
#include "ParticleEmitter.h"
#include "EventManager.h"
#include "World.h"

#include <glm/gtc/matrix_transform.hpp>
#include <glm/common.hpp>

using namespace glm;

AsteroidSystem::AsteroidSystem(ParticleEmitter* emitter, ParticleDescriptor* descriptor)
: mpDescriptor(descriptor), mpEmitter(emitter)
{
    assert(mpDescriptor != nullptr);
    assert(mpEmitter != nullptr);

	#if defined(PLATFORM_OSX)
		int textureID = TextureLoader::LoadTexture("Textures/asteroidTexture.jpg");
	#else
		int textureID = TextureLoader::LoadTexture("../Assets/Textures/asteroidTexture.jpg");
	#endif

    // Update Event Manager - Frame time / input / events processing

    // Pre-allocate the maximum number of particles at a give time, according to
    // lifetime and emission rate
    int maxAsteroids = static_cast<int>(mpDescriptor->emissionRate * (mpDescriptor->totalLifetime + mpDescriptor->totalLifetimeDelta)) + 1;

    mInactiveAsteroids.resize(maxAsteroids);
    for (std::vector<Asteroid*>::iterator it = mInactiveAsteroids.begin(); it != mInactiveAsteroids.end(); ++it)
    {
		*it = new Asteroid(mpEmitter->GetAsteroidRandomPosition(), textureID);
    }

}

AsteroidSystem::~AsteroidSystem()
{
    // TODO: DESTROY MODEL STUFF INSTEAD
    for (std::vector<Asteroid*>::iterator it = mInactiveAsteroids.begin(); it != mInactiveAsteroids.end(); ++it)
    {
        delete *it;
    }

    for (std::vector<Asteroid*>::iterator it = mAsteroidList.begin(); it != mAsteroidList.end(); ++it)
    {
        delete *it;
    }

    mInactiveAsteroids.resize(0);
    mAsteroidList.resize(0);
}

void AsteroidSystem::Update(float dt)
{
    // Emit particle according to the emission rate
    float averageTimeBetweenEmission = 30.0f / mpDescriptor->emissionRate;
    float randomValue = EventManager::GetRandomFloat(0.0f, 1.0f) * averageTimeBetweenEmission;

    while (mInactiveAsteroids.size() > 0 && randomValue < dt)
    {
        randomValue += averageTimeBetweenEmission;

        Asteroid* newAsteroid = mInactiveAsteroids.back();
        mAsteroidList.push_back(newAsteroid);
        mInactiveAsteroids.pop_back();

        newAsteroid->SetPosition(mpEmitter->GetAsteroidRandomPosition());

        // giving random size to asteroids
		float randomSize = mpEmitter->GetRandomFloat(1, 3);
		newAsteroid->SetScaling(vec3(randomSize));

        mpEmitter = new ParticleEmitter(vec3(0.0f, 0.0f, 0.0f), newAsteroid);
        mpDescriptor = new ParticleDescriptor();

		mpDescriptor->setInitialSize(vec2(randomSize));

        mpDescriptor->SetAsteroidDescriptor();

        ParticleSystem* ps = new ParticleSystem(mpEmitter, mpDescriptor);

        newAsteroid->setParticleSystem(ps);
    }

    for (std::vector<Asteroid*>::iterator it = mAsteroidList.begin(); it != mAsteroidList.end(); )
    {
        Asteroid* a = (*it);
        a->Update(dt);
        a->getParticleSystem()->Update(dt);

        // TODO: modify so that asteroid dies if:
        // 1: asteroid has been shot x times and has no more lives
        // 2: asteroid has reached World origin vec3(0.0f, 0.0f, 0.0f)
        if (a->GetPosition().x >= -2.0f && a->GetPosition().x <= 2.0f)
        {
            std::cout << a->GetPosition().x << " has been destroyed." << std::endl;

            mInactiveAsteroids.push_back(a);

            delete a->getParticleSystem();

            it = mAsteroidList.erase(it);
        }
        else
        {
            ++it;
        }

    }

}

void AsteroidSystem::Draw() {

    for(Asteroid* asteroid : mAsteroidList) {
        asteroid->Draw();
    }

}<|endoftext|>


<commit_before>
/*
 *  AudioStream.cpp
 *  sfeMovie project
 *
 *  Copyright (C) 2010-2014 Lucas Soltic
 *  lucas.soltic@orange.fr
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */

extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/samplefmt.h>
#include <libavutil/opt.h>
#include <libavutil/channel_layout.h>
#include <libswresample/swresample.h>
}

#include <cstring>
#include <iostream>
#include "AudioStream.hpp"
#include "Log.hpp"
#include <sfeMovie/Movie.hpp>

namespace sfe
{
    AudioStream::AudioStream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource,
                             std::shared_ptr<Timer> timer) :
    Stream(formatCtx, stream, dataSource, timer),

    // Public properties
    m_sampleRate(0),

    // Private data
    m_samplesBuffer(nullptr),
    m_audioFrame(nullptr),

    // Resampling
    m_swrCtx(nullptr),
    m_dstNbSamples(0),
    m_maxDstNbSamples(0),
    m_dstNbChannels(0),
    m_dstLinesize(0),
    m_dstData(nullptr)
    {
        m_audioFrame = av_frame_alloc();
        CHECK(m_audioFrame, "AudioStream::AudioStream() - out of memory");

        // Get some audio informations
        m_sampleRate = m_stream->codec->sample_rate;

        // Alloc a two seconds buffer
        m_samplesBuffer = (sf::Int16*)av_malloc(sizeof(sf::Int16) * av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO) * m_sampleRate * 2);
        CHECK(m_samplesBuffer, "AudioStream::AudioStream() - out of memory");

        // Initialize the sf::SoundStream
        // Whatever the channel count is, it'll we resampled to stereo
        sf::SoundStream::initialize(av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO), m_sampleRate);

        // Initialize resampler to be able to give signed 16 bits samples to SFML
        initResampler();
    }

    /** Default destructor
     */
    AudioStream::~AudioStream()
    {
        if (m_audioFrame)
        {
            av_frame_free(&m_audioFrame);
        }

        if (m_samplesBuffer)
        {
            av_free(m_samplesBuffer);
        }

        if (m_dstData)
        {
            av_freep(&m_dstData[0]);
        }
        av_freep(&m_dstData);

        swr_free(&m_swrCtx);
    }

    void AudioStream::flushBuffers()
    {
        sf::SoundStream::Status sfStatus = sf::SoundStream::getStatus();
        CHECK (sfStatus != sf::SoundStream::Playing, "Trying to flush while audio is playing, this will introduce an audio glitch!");

        // Flush audio driver/OpenAL/SFML buffer
        if (sfStatus != sf::SoundStream::Stopped)
            sf::SoundStream::stop();

        Stream::flushBuffers();
    }

    MediaType AudioStream::getStreamKind() const
    {
        return Audio;
    }

    void AudioStream::update()
    {
        sf::SoundStream::Status sfStatus = sf::SoundStream::getStatus();

        switch (sfStatus)
        {
            case sf::SoundStream::Playing:
                setStatus(sfe::Playing);
                break;

            case sf::SoundStream::Paused:
                setStatus(sfe::Paused);
                break;

            case sf::SoundStream::Stopped:
                setStatus(sfe::Stopped);
                break;

            default:
                break;
        }
    }

    bool AudioStream::onGetData(sf::SoundStream::Chunk& data)
    {
        AVPacket* packet = nullptr;
        data.samples = m_samplesBuffer;

        while (data.sampleCount < av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO) * m_sampleRate &&
               (nullptr != (packet = popEncodedData())))
        {
            bool needsMoreDecoding = false;
            bool gotFrame = false;

            do
            {
                needsMoreDecoding = decodePacket(packet, m_audioFrame, gotFrame);

                if (gotFrame)
                {
                    uint8_t* samples = nullptr;
                    int nbSamples = 0;
                    int samplesLength = 0;

                    resampleFrame(m_audioFrame, samples, nbSamples, samplesLength);
                    CHECK(samples, "AudioStream::onGetData() - resampleFrame() error");
                    CHECK(nbSamples > 0, "AudioStream::onGetData() - resampleFrame() error");
                    CHECK(nbSamples == samplesLength / 2, "AudioStream::onGetData() resampleFrame() inconsistency");

                    CHECK(data.sampleCount + nbSamples < m_sampleRate * 2 * av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO), "AudioStream::onGetData() - Going to overflow!!");

                    std::memcpy((void *)(data.samples + data.sampleCount),
                                samples, samplesLength);
                    data.sampleCount += nbSamples;
                }
            } while (needsMoreDecoding);

            av_free_packet(packet);
            av_free(packet);
        }

        if (!packet)
        {
            sfeLogDebug("No more audio packets, do not go further");
        }
        return (packet != nullptr);
    }

    void AudioStream::onSeek(sf::Time timeOffset)
    {
        //        CHECK(0, "AudioStream::onSeek() - not implemented");
    }

    bool AudioStream::decodePacket(AVPacket* packet, AVFrame* outputFrame, bool& gotFrame)
    {
        bool needsMoreDecoding = false;
        int igotFrame = 0;

        int decodedLength = avcodec_decode_audio4(m_stream->codec, outputFrame, &igotFrame, packet);
        gotFrame = (igotFrame != 0);
        CHECK(decodedLength >= 0, "AudioStream::decodePacket() - error: decodedLength=" + s(decodedLength));

        if (decodedLength < packet->size)
        {
            needsMoreDecoding = true;
            packet->data += decodedLength;
            packet->size -= decodedLength;
        }

        return needsMoreDecoding;
    }

    void AudioStream::initResampler()
    {
        CHECK0(m_swrCtx, "AudioStream::initResampler() - resampler already initialized");
        int err = 0;

        /* create resampler context */
        m_swrCtx = swr_alloc();
        CHECK(m_swrCtx, "AudioStream::initResampler() - out of memory");

        // Some media files don't define the channel layout, in this case take a default one
        // according to the channels' count
        if (m_stream->codec->channel_layout == 0)
        {
            m_stream->codec->channel_layout = av_get_default_channel_layout(m_stream->codec->channels);
        }

        /* set options */
        av_opt_set_int        (m_swrCtx, "in_channel_layout",  m_stream->codec->channel_layout, 0);
        av_opt_set_int        (m_swrCtx, "in_sample_rate",     m_stream->codec->sample_rate,    0);
        av_opt_set_sample_fmt (m_swrCtx, "in_sample_fmt",      m_stream->codec->sample_fmt,     0);
        av_opt_set_int        (m_swrCtx, "out_channel_layout", AV_CH_LAYOUT_STEREO,             0);
        av_opt_set_int        (m_swrCtx, "out_sample_rate",    m_stream->codec->sample_rate,    0);
        av_opt_set_sample_fmt (m_swrCtx, "out_sample_fmt",     AV_SAMPLE_FMT_S16,               0);

        /* initialize the resampling context */
        err = swr_init(m_swrCtx);
        CHECK(err >= 0, "AudioStream::initResampler() - resampling context initialization error");

        /* compute the number of converted samples: buffering is avoided
         * ensuring that the output buffer will contain at least all the
         * converted input samples */
        m_maxDstNbSamples = m_dstNbSamples = 1024;

        /* Create the resampling output buffer */
        m_dstNbChannels = av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO);
        err = av_samples_alloc_array_and_samples(&m_dstData, &m_dstLinesize, m_dstNbChannels,
                                                 m_dstNbSamples, AV_SAMPLE_FMT_S16, 0);
        CHECK(err >= 0, "AudioStream::initResampler() - av_samples_alloc_array_and_samples error");
    }

    void AudioStream::resampleFrame(const AVFrame* frame, uint8_t*& outSamples, int& outNbSamples, int& outSamplesLength)
    {
        CHECK(m_swrCtx, "AudioStream::resampleFrame() - resampler is not initialized, call AudioStream::initResamplerFirst() !");
        CHECK(frame, "AudioStream::resampleFrame() - invalid argument");

        int src_rate, dst_rate, err, dst_bufsize;
        src_rate = dst_rate = frame->sample_rate;

        /* compute destination number of samples */
        m_dstNbSamples = av_rescale_rnd(swr_get_delay(m_swrCtx, src_rate) +
                                        frame->nb_samples, dst_rate, src_rate, AV_ROUND_UP);
        if (m_dstNbSamples > m_maxDstNbSamples)
        {
            av_free(m_dstData[0]);
            err = av_samples_alloc(m_dstData, &m_dstLinesize, m_dstNbChannels,
                                   m_dstNbSamples, AV_SAMPLE_FMT_S16, 1);
            CHECK(err >= 0, "AudioStream::resampleFrame() - out of memory");
            m_maxDstNbSamples = m_dstNbSamples;
        }

        /* convert to destination format */
        err = swr_convert(m_swrCtx, m_dstData, m_dstNbSamples, (const uint8_t **)frame->extended_data, frame->nb_samples);
        CHECK(err >= 0, "AudioStream::resampleFrame() - swr_convert() error");

        dst_bufsize = av_samples_get_buffer_size(&m_dstLinesize, m_dstNbChannels,
                                                 err, AV_SAMPLE_FMT_S16, 1);
        CHECK(dst_bufsize >= 0, "AudioStream::resampleFrame() - av_samples_get_buffer_size() error");

        outNbSamples = dst_bufsize / av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
        outSamplesLength = dst_bufsize;
        outSamples = m_dstData[0];
    }

    void AudioStream::willPlay(const Timer &timer)
    {
        Stream::willPlay(timer);

        if (Stream::getStatus() == sfe::Stopped)
        {
            sf::Time initialTime = sf::SoundStream::getPlayingOffset();
            sf::Clock timeout;
            sf::SoundStream::play();

            // Some audio drivers take time before the sound is actually played
            // To avoid desynchronization with the timer, we don't return
            // until the audio stream is actually started
            while (sf::SoundStream::getPlayingOffset() == initialTime && timeout.getElapsedTime() < sf::seconds(5))
                sf::sleep(sf::milliseconds(10));

            CHECK(sf::SoundStream::getPlayingOffset() != initialTime, "is your audio device broken? Audio did not start within 5 seconds");
        }
        else
        {
            sf::SoundStream::play();
        }
    }

    void AudioStream::didPlay(const Timer& timer, sfe::Status previousStatus)
    {
        CHECK(SoundStream::getStatus() == SoundStream::Playing, "AudioStream::didPlay() - willPlay() not executed!");
        Stream::didPlay(timer, previousStatus);
    }

    void AudioStream::didPause(const Timer& timer, sfe::Status previousStatus)
    {
        sf::SoundStream::pause();
        Stream::didPause(timer, previousStatus);
    }

    void AudioStream::didStop(const Timer& timer, sfe::Status previousStatus)
    {
        sf::SoundStream::stop();
        Stream::didStop(timer, previousStatus);
    }
}
<commit_msg>#6 Temporary workaround for inaccurage status gathered from sf::SoundStream<commit_after>
/*
 *  AudioStream.cpp
 *  sfeMovie project
 *
 *  Copyright (C) 2010-2014 Lucas Soltic
 *  lucas.soltic@orange.fr
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 *
 */

extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/samplefmt.h>
#include <libavutil/opt.h>
#include <libavutil/channel_layout.h>
#include <libswresample/swresample.h>
}

#include <cstring>
#include <iostream>
#include "AudioStream.hpp"
#include "Log.hpp"
#include <sfeMovie/Movie.hpp>

namespace sfe
{
    AudioStream::AudioStream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource,
                             std::shared_ptr<Timer> timer) :
    Stream(formatCtx, stream, dataSource, timer),

    // Public properties
    m_sampleRate(0),

    // Private data
    m_samplesBuffer(nullptr),
    m_audioFrame(nullptr),

    // Resampling
    m_swrCtx(nullptr),
    m_dstNbSamples(0),
    m_maxDstNbSamples(0),
    m_dstNbChannels(0),
    m_dstLinesize(0),
    m_dstData(nullptr)
    {
        m_audioFrame = av_frame_alloc();
        CHECK(m_audioFrame, "AudioStream::AudioStream() - out of memory");

        // Get some audio informations
        m_sampleRate = m_stream->codec->sample_rate;

        // Alloc a two seconds buffer
        m_samplesBuffer = (sf::Int16*)av_malloc(sizeof(sf::Int16) * av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO) * m_sampleRate * 2);
        CHECK(m_samplesBuffer, "AudioStream::AudioStream() - out of memory");

        // Initialize the sf::SoundStream
        // Whatever the channel count is, it'll we resampled to stereo
        sf::SoundStream::initialize(av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO), m_sampleRate);

        // Initialize resampler to be able to give signed 16 bits samples to SFML
        initResampler();
    }

    /** Default destructor
     */
    AudioStream::~AudioStream()
    {
        if (m_audioFrame)
        {
            av_frame_free(&m_audioFrame);
        }

        if (m_samplesBuffer)
        {
            av_free(m_samplesBuffer);
        }

        if (m_dstData)
        {
            av_freep(&m_dstData[0]);
        }
        av_freep(&m_dstData);

        swr_free(&m_swrCtx);
    }

    void AudioStream::flushBuffers()
    {
        // To be removed once issue with sf::SoundStream::getStatus() is fixed:
        // http://en.sfml-dev.org/forums/index.php?topic=17095.msg122898#msg122898
        // This should never happen as this stream has already been notified to pause and
        // sf::SoundStream::pause() has been called
        while (sf::SoundStream::getStatus() == sf::SoundStream::Playing)
            sf::sleep(sf::microseconds(1));

        sf::SoundStream::Status sfStatus = sf::SoundStream::getStatus();
        CHECK (sfStatus != sf::SoundStream::Playing, "Trying to flush while audio is playing, this will introduce an audio glitch!");

        // Flush audio driver/OpenAL/SFML buffer
        if (sfStatus != sf::SoundStream::Stopped)
            sf::SoundStream::stop();

        Stream::flushBuffers();
    }

    MediaType AudioStream::getStreamKind() const
    {
        return Audio;
    }

    void AudioStream::update()
    {
        sf::SoundStream::Status sfStatus = sf::SoundStream::getStatus();

        switch (sfStatus)
        {
            case sf::SoundStream::Playing:
                setStatus(sfe::Playing);
                break;

            case sf::SoundStream::Paused:
                setStatus(sfe::Paused);
                break;

            case sf::SoundStream::Stopped:
                setStatus(sfe::Stopped);
                break;

            default:
                break;
        }
    }

    bool AudioStream::onGetData(sf::SoundStream::Chunk& data)
    {
        AVPacket* packet = nullptr;
        data.samples = m_samplesBuffer;

        while (data.sampleCount < av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO) * m_sampleRate &&
               (nullptr != (packet = popEncodedData())))
        {
            bool needsMoreDecoding = false;
            bool gotFrame = false;

            do
            {
                needsMoreDecoding = decodePacket(packet, m_audioFrame, gotFrame);

                if (gotFrame)
                {
                    uint8_t* samples = nullptr;
                    int nbSamples = 0;
                    int samplesLength = 0;

                    resampleFrame(m_audioFrame, samples, nbSamples, samplesLength);
                    CHECK(samples, "AudioStream::onGetData() - resampleFrame() error");
                    CHECK(nbSamples > 0, "AudioStream::onGetData() - resampleFrame() error");
                    CHECK(nbSamples == samplesLength / 2, "AudioStream::onGetData() resampleFrame() inconsistency");

                    CHECK(data.sampleCount + nbSamples < m_sampleRate * 2 * av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO), "AudioStream::onGetData() - Going to overflow!!");

                    std::memcpy((void *)(data.samples + data.sampleCount),
                                samples, samplesLength);
                    data.sampleCount += nbSamples;
                }
            } while (needsMoreDecoding);

            av_free_packet(packet);
            av_free(packet);
        }

        if (!packet)
        {
            sfeLogDebug("No more audio packets, do not go further");
        }
        return (packet != nullptr);
    }

    void AudioStream::onSeek(sf::Time timeOffset)
    {
        //        CHECK(0, "AudioStream::onSeek() - not implemented");
    }

    bool AudioStream::decodePacket(AVPacket* packet, AVFrame* outputFrame, bool& gotFrame)
    {
        bool needsMoreDecoding = false;
        int igotFrame = 0;

        int decodedLength = avcodec_decode_audio4(m_stream->codec, outputFrame, &igotFrame, packet);
        gotFrame = (igotFrame != 0);
        CHECK(decodedLength >= 0, "AudioStream::decodePacket() - error: decodedLength=" + s(decodedLength));

        if (decodedLength < packet->size)
        {
            needsMoreDecoding = true;
            packet->data += decodedLength;
            packet->size -= decodedLength;
        }

        return needsMoreDecoding;
    }

    void AudioStream::initResampler()
    {
        CHECK0(m_swrCtx, "AudioStream::initResampler() - resampler already initialized");
        int err = 0;

        /* create resampler context */
        m_swrCtx = swr_alloc();
        CHECK(m_swrCtx, "AudioStream::initResampler() - out of memory");

        // Some media files don't define the channel layout, in this case take a default one
        // according to the channels' count
        if (m_stream->codec->channel_layout == 0)
        {
            m_stream->codec->channel_layout = av_get_default_channel_layout(m_stream->codec->channels);
        }

        /* set options */
        av_opt_set_int        (m_swrCtx, "in_channel_layout",  m_stream->codec->channel_layout, 0);
        av_opt_set_int        (m_swrCtx, "in_sample_rate",     m_stream->codec->sample_rate,    0);
        av_opt_set_sample_fmt (m_swrCtx, "in_sample_fmt",      m_stream->codec->sample_fmt,     0);
        av_opt_set_int        (m_swrCtx, "out_channel_layout", AV_CH_LAYOUT_STEREO,             0);
        av_opt_set_int        (m_swrCtx, "out_sample_rate",    m_stream->codec->sample_rate,    0);
        av_opt_set_sample_fmt (m_swrCtx, "out_sample_fmt",     AV_SAMPLE_FMT_S16,               0);

        /* initialize the resampling context */
        err = swr_init(m_swrCtx);
        CHECK(err >= 0, "AudioStream::initResampler() - resampling context initialization error");

        /* compute the number of converted samples: buffering is avoided
         * ensuring that the output buffer will contain at least all the
         * converted input samples */
        m_maxDstNbSamples = m_dstNbSamples = 1024;

        /* Create the resampling output buffer */
        m_dstNbChannels = av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO);
        err = av_samples_alloc_array_and_samples(&m_dstData, &m_dstLinesize, m_dstNbChannels,
                                                 m_dstNbSamples, AV_SAMPLE_FMT_S16, 0);
        CHECK(err >= 0, "AudioStream::initResampler() - av_samples_alloc_array_and_samples error");
    }

    void AudioStream::resampleFrame(const AVFrame* frame, uint8_t*& outSamples, int& outNbSamples, int& outSamplesLength)
    {
        CHECK(m_swrCtx, "AudioStream::resampleFrame() - resampler is not initialized, call AudioStream::initResamplerFirst() !");
        CHECK(frame, "AudioStream::resampleFrame() - invalid argument");

        int src_rate, dst_rate, err, dst_bufsize;
        src_rate = dst_rate = frame->sample_rate;

        /* compute destination number of samples */
        m_dstNbSamples = av_rescale_rnd(swr_get_delay(m_swrCtx, src_rate) +
                                        frame->nb_samples, dst_rate, src_rate, AV_ROUND_UP);
        if (m_dstNbSamples > m_maxDstNbSamples)
        {
            av_free(m_dstData[0]);
            err = av_samples_alloc(m_dstData, &m_dstLinesize, m_dstNbChannels,
                                   m_dstNbSamples, AV_SAMPLE_FMT_S16, 1);
            CHECK(err >= 0, "AudioStream::resampleFrame() - out of memory");
            m_maxDstNbSamples = m_dstNbSamples;
        }

        /* convert to destination format */
        err = swr_convert(m_swrCtx, m_dstData, m_dstNbSamples, (const uint8_t **)frame->extended_data, frame->nb_samples);
        CHECK(err >= 0, "AudioStream::resampleFrame() - swr_convert() error");

        dst_bufsize = av_samples_get_buffer_size(&m_dstLinesize, m_dstNbChannels,
                                                 err, AV_SAMPLE_FMT_S16, 1);
        CHECK(dst_bufsize >= 0, "AudioStream::resampleFrame() - av_samples_get_buffer_size() error");

        outNbSamples = dst_bufsize / av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
        outSamplesLength = dst_bufsize;
        outSamples = m_dstData[0];
    }

    void AudioStream::willPlay(const Timer &timer)
    {
        Stream::willPlay(timer);

        if (Stream::getStatus() == sfe::Stopped)
        {
            sf::Time initialTime = sf::SoundStream::getPlayingOffset();
            sf::Clock timeout;
            sf::SoundStream::play();

            // Some audio drivers take time before the sound is actually played
            // To avoid desynchronization with the timer, we don't return
            // until the audio stream is actually started
            while (sf::SoundStream::getPlayingOffset() == initialTime && timeout.getElapsedTime() < sf::seconds(5))
                sf::sleep(sf::milliseconds(10));

            CHECK(sf::SoundStream::getPlayingOffset() != initialTime, "is your audio device broken? Audio did not start within 5 seconds");
        }
        else
        {
            sf::SoundStream::play();
        }
    }

    void AudioStream::didPlay(const Timer& timer, sfe::Status previousStatus)
    {
        CHECK(SoundStream::getStatus() == SoundStream::Playing, "AudioStream::didPlay() - willPlay() not executed!");
        Stream::didPlay(timer, previousStatus);
    }

    void AudioStream::didPause(const Timer& timer, sfe::Status previousStatus)
    {
        sf::SoundStream::pause();
        Stream::didPause(timer, previousStatus);
    }

    void AudioStream::didStop(const Timer& timer, sfe::Status previousStatus)
    {
        sf::SoundStream::stop();
        Stream::didStop(timer, previousStatus);
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ConnectionHelper.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:21:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef DBAUI_CONNECTIONHELPER_HXX
#define DBAUI_CONNECTIONHELPER_HXX

#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#ifndef _DBAUI_CURLEDIT_HXX_
#include "curledit.hxx"
#endif
#ifndef _SFX_FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#define FILL_STRING_ITEM(editcontrol, itemset, itemid, modifiedflag)    \
    if (editcontrol.GetText() != editcontrol.GetSavedValue())           \
    {                                                                   \
        itemset.Put(SfxStringItem(itemid, editcontrol.GetText()));      \
        modifiedflag = sal_True;                                        \
    }

//.........................................................................
namespace dbaui
{
//.........................................................................

    // #106016# --------------
    enum IS_PATH_EXIST
    {
        PATH_NOT_EXIST = 0,
        PATH_EXIST,
        PATH_NOT_KNOWN
    };

    class IDatabaseSettingsDialog;

    class OConnectionHelper : public OGenericAdministrationPage
    {
        sal_Bool            m_bUserGrabFocus : 1;

    public:
        OConnectionHelper( Window* pParent, const ResId& _rId, const SfxItemSet& _rCoreAttrs);
        virtual ~OConnectionHelper();
        FixedText           m_aFT_Connection;
        OConnectionURLEdit  m_aET_Connection;
        PushButton          m_aPB_Connection;
        DATASOURCE_TYPE     m_eType;          // the type can't be changed in this class, so we hold it as member.

    public:

        // setting/retrieving the current connection URL
        // necessary because for some types, the URL must be decoded for display purposes
        ODsnTypeCollection* m_pCollection;  /// the DSN type collection instance
        virtual long    PreNotify( NotifyEvent& _rNEvt );

        // <method>OGenericAdministrationPage::fillControls</method>
        virtual void    fillControls(::std::vector< ISaveValueWrapper* >& _rControlList);
        // <method>OGenericAdministrationPage::fillWindows</method>
        virtual void    fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList);
        virtual void    implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);

        // setting/retrieving the current connection URL
        // necessary because for some types, the URL must be decoded for display purposes
        String      getURL( OConnectionURLEdit* _m_pConnection ) const;
        void        setURL( const String& _rURL, OConnectionURLEdit* _m_pConnection );

        String      getURLNoPrefix( ) const;
        void        setURLNoPrefix( const String& _rURL );

        /** checks if the path is existence
            @param  _rURL
                The URL to check.
        */
        sal_Int32   checkPathExistence(const String& _rURL);

        IS_PATH_EXIST   pathExists(const ::rtl::OUString& _rURL, sal_Bool bIsFile) const;
        sal_Bool        createDirectoryDeep(const String& _rPathNormalized);
        sal_Bool        commitURL();

        /** opens the FileOpen dialog and asks for a FileName
            @param  _aFileOpen
                Executes the file open dialog, which must be filled from caller.
        */
        void askForFileName(::sfx2::FileDialogHelper& _aFileOpen);

           virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB)
        {
            OGenericAdministrationPage::SetServiceFactory(_rxORB);
            m_aET_Connection.initializeTypeCollection(m_xORB);
        }

    protected:
        DECL_LINK(OnBrowseConnections, PushButton*);
        void        setURL( const String& _rURL );
        String      implGetURL( sal_Bool _bPrefix ) const;
        void        implSetURL( const String& _rURL, sal_Bool _bPrefix );
        StringBag getInstalledAdabasDBDirs(const String &_rPath,const ::ucb::ResultSetInclude& _reResultSetInclude);
        StringBag getInstalledAdabasDBs(const String &_rConfigDir,const String &_rWorkDir);
        virtual bool checkTestConnection();

        void    implUpdateURLDependentStates() const;
    };

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // DBAUI_CONNECTIONHELPER_HXX
<commit_msg>INTEGRATION: CWS bgdlremove (1.4.278); FILE MERGED 2007/05/21 10:35:25 kso 1.4.278.2: RESYNC: (1.4-1.5); FILE MERGED 2007/05/18 09:03:13 kso 1.4.278.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ConnectionHelper.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 14:41:35 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef DBAUI_CONNECTIONHELPER_HXX
#define DBAUI_CONNECTIONHELPER_HXX

#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#ifndef _DBAUI_CURLEDIT_HXX_
#include "curledit.hxx"
#endif
#ifndef _SFX_FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#define FILL_STRING_ITEM(editcontrol, itemset, itemid, modifiedflag)    \
    if (editcontrol.GetText() != editcontrol.GetSavedValue())           \
    {                                                                   \
        itemset.Put(SfxStringItem(itemid, editcontrol.GetText()));      \
        modifiedflag = sal_True;                                        \
    }

//.........................................................................
namespace dbaui
{
//.........................................................................

    // #106016# --------------
    enum IS_PATH_EXIST
    {
        PATH_NOT_EXIST = 0,
        PATH_EXIST,
        PATH_NOT_KNOWN
    };

    class IDatabaseSettingsDialog;

    class OConnectionHelper : public OGenericAdministrationPage
    {
        sal_Bool            m_bUserGrabFocus : 1;

    public:
        OConnectionHelper( Window* pParent, const ResId& _rId, const SfxItemSet& _rCoreAttrs);
        virtual ~OConnectionHelper();
        FixedText           m_aFT_Connection;
        OConnectionURLEdit  m_aET_Connection;
        PushButton          m_aPB_Connection;
        DATASOURCE_TYPE     m_eType;          // the type can't be changed in this class, so we hold it as member.

    public:

        // setting/retrieving the current connection URL
        // necessary because for some types, the URL must be decoded for display purposes
        ODsnTypeCollection* m_pCollection;  /// the DSN type collection instance
        virtual long    PreNotify( NotifyEvent& _rNEvt );

        // <method>OGenericAdministrationPage::fillControls</method>
        virtual void    fillControls(::std::vector< ISaveValueWrapper* >& _rControlList);
        // <method>OGenericAdministrationPage::fillWindows</method>
        virtual void    fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList);
        virtual void    implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);

        // setting/retrieving the current connection URL
        // necessary because for some types, the URL must be decoded for display purposes
        String      getURL( OConnectionURLEdit* _m_pConnection ) const;
        void        setURL( const String& _rURL, OConnectionURLEdit* _m_pConnection );

        String      getURLNoPrefix( ) const;
        void        setURLNoPrefix( const String& _rURL );

        /** checks if the path is existence
            @param  _rURL
                The URL to check.
        */
        sal_Int32   checkPathExistence(const String& _rURL);

        IS_PATH_EXIST   pathExists(const ::rtl::OUString& _rURL, sal_Bool bIsFile) const;
        sal_Bool        createDirectoryDeep(const String& _rPathNormalized);
        sal_Bool        commitURL();

        /** opens the FileOpen dialog and asks for a FileName
            @param  _aFileOpen
                Executes the file open dialog, which must be filled from caller.
        */
        void askForFileName(::sfx2::FileDialogHelper& _aFileOpen);

           virtual void SetServiceFactory(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > _rxORB)
        {
            OGenericAdministrationPage::SetServiceFactory(_rxORB);
            m_aET_Connection.initializeTypeCollection(m_xORB);
        }

    protected:
        DECL_LINK(OnBrowseConnections, PushButton*);
        void        setURL( const String& _rURL );
        String      implGetURL( sal_Bool _bPrefix ) const;
        void        implSetURL( const String& _rURL, sal_Bool _bPrefix );
        StringBag getInstalledAdabasDBDirs(const String &_rPath,const ::ucbhelper::ResultSetInclude& _reResultSetInclude);
        StringBag getInstalledAdabasDBs(const String &_rConfigDir,const String &_rWorkDir);
        virtual bool checkTestConnection();

        void    implUpdateURLDependentStates() const;
    };

//.........................................................................
}   // namespace dbaui
//.........................................................................

#endif // DBAUI_CONNECTIONHELPER_HXX
<|endoftext|>