text
stringlengths
54
60.6k
<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 <application/berryStarter.h> #include <Poco/Util/MapConfiguration.h> #include <QApplication> #include <QMessageBox> #include <QtSingleApplication> #include <QtGlobal> #include <QTime> #include <mitkCommon.h> #include <mitkException.h> class QtSafeApplication : public QtSingleApplication { public: QtSafeApplication(int& argc, char** argv) : QtSingleApplication(argc, argv) {} /** * Reimplement notify to catch unhandled exceptions and open an error message. * * @param receiver * @param event * @return */ bool notify(QObject* receiver, QEvent* event) { QString msg; try { return QApplication::notify(receiver, event); } catch (mitk::Exception& e) { msg = QString("MITK Exception:\n\n") + QString("Desciption: ") + QString(e.GetDescription()) + QString("\n\n") + QString("Filename: ") + QString(e.GetFile()) + QString("\n\n") + QString("Line: ") + QString::number(e.GetLine()); } catch (Poco::Exception& e) { msg = QString::fromStdString(e.displayText()); } catch (std::exception& e) { msg = e.what(); } catch (...) { msg = "Unknown exception"; } MITK_ERROR << "An error occurred: " << msg.toStdString(); QMessageBox msgBox; msgBox.setText("An error occurred. You should save all data and quit the program to prevent possible data loss."); msgBox.setDetailedText(msg); msgBox.setIcon(QMessageBox::Critical); msgBox.addButton(trUtf8("Exit immediately"), QMessageBox::YesRole); msgBox.addButton(trUtf8("Ignore"), QMessageBox::NoRole); int ret = msgBox.exec(); switch(ret) { case 0: MITK_ERROR << "The program was closed."; this->closeAllWindows(); break; case 1: MITK_ERROR << "The error was ignored by the user. The program may be in a corrupt state and don't behave like expected!"; break; } return false; } }; int main(int argc, char** argv) { // Create a QApplication instance first QtSafeApplication qSafeApp(argc, argv); qSafeApp.setApplicationName("MITK Workbench"); qSafeApp.setOrganizationName("DKFZ"); // This function checks if an instance is already running // and either sends a message to it (containing the command // line arguments) or checks if a new instance was forced by // providing the BlueBerry.newInstance command line argument. // In the latter case, a path to a temporary directory for // the new application's storage directory is returned. QString storageDir = handleNewAppInstance(&qSafeApp, argc, argv, "BlueBerry.newInstance"); // These paths replace the .ini file and are tailored for installation // packages created with CPack. If a .ini file is presented, it will // overwrite the settings in MapConfiguration Poco::Path basePath(argv[0]); basePath.setFileName(""); Poco::Path provFile(basePath); provFile.setFileName("mitkWorkbench.provisioning"); Poco::Path extPath(basePath); extPath.pushDirectory("ExtBundles"); std::string pluginDirs = extPath.toString(); Poco::Util::MapConfiguration* extConfig(new Poco::Util::MapConfiguration()); if (!storageDir.isEmpty()) { extConfig->setString(berry::Platform::ARG_STORAGE_DIR, storageDir.toStdString()); } extConfig->setString(berry::Platform::ARG_PLUGIN_DIRS, pluginDirs); extConfig->setString(berry::Platform::ARG_PROVISIONING, provFile.toString()); extConfig->setString(berry::Platform::ARG_APPLICATION, "org.mitk.qt.extapplication"); #ifdef Q_OS_WIN #define CTK_LIB_PREFIX #else #define CTK_LIB_PREFIX "lib" #endif // Preload the org.mitk.gui.qt.ext plug-in (and hence also QmitkExt) to speed // up a clean-cache start. This also works around bugs in older gcc and glibc implementations, // which have difficulties with multiple dynamic opening and closing of shared libraries with // many global static initializers. It also helps if dependent libraries have weird static // initialization methods and/or missing de-initialization code. extConfig->setString(berry::Platform::ARG_PRELOAD_LIBRARY, "liborg_mitk_gui_qt_ext," CTK_LIB_PREFIX "CTKDICOMCore:0.1"); // Seed the random number generator, once at startup. QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // Run the workbench. return berry::Starter::Run(argc, argv, extConfig); } <commit_msg>Set the CppMicroServices persistent data location.<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 <application/berryStarter.h> #include <Poco/Util/MapConfiguration.h> #include <QApplication> #include <QMessageBox> #include <QtSingleApplication> #include <QtGlobal> #include <QTime> #include <QDesktopServices> #include <usModuleSettings.h> #include <mitkCommon.h> #include <mitkException.h> class QtSafeApplication : public QtSingleApplication { public: QtSafeApplication(int& argc, char** argv) : QtSingleApplication(argc, argv) {} /** * Reimplement notify to catch unhandled exceptions and open an error message. * * @param receiver * @param event * @return */ bool notify(QObject* receiver, QEvent* event) { QString msg; try { return QApplication::notify(receiver, event); } catch (mitk::Exception& e) { msg = QString("MITK Exception:\n\n") + QString("Desciption: ") + QString(e.GetDescription()) + QString("\n\n") + QString("Filename: ") + QString(e.GetFile()) + QString("\n\n") + QString("Line: ") + QString::number(e.GetLine()); } catch (Poco::Exception& e) { msg = QString::fromStdString(e.displayText()); } catch (std::exception& e) { msg = e.what(); } catch (...) { msg = "Unknown exception"; } MITK_ERROR << "An error occurred: " << msg.toStdString(); QMessageBox msgBox; msgBox.setText("An error occurred. You should save all data and quit the program to prevent possible data loss."); msgBox.setDetailedText(msg); msgBox.setIcon(QMessageBox::Critical); msgBox.addButton(trUtf8("Exit immediately"), QMessageBox::YesRole); msgBox.addButton(trUtf8("Ignore"), QMessageBox::NoRole); int ret = msgBox.exec(); switch(ret) { case 0: MITK_ERROR << "The program was closed."; this->closeAllWindows(); break; case 1: MITK_ERROR << "The error was ignored by the user. The program may be in a corrupt state and don't behave like expected!"; break; } return false; } }; int main(int argc, char** argv) { // Create a QApplication instance first QtSafeApplication qSafeApp(argc, argv); qSafeApp.setApplicationName("MITK Workbench"); qSafeApp.setOrganizationName("DKFZ"); // This function checks if an instance is already running // and either sends a message to it (containing the command // line arguments) or checks if a new instance was forced by // providing the BlueBerry.newInstance command line argument. // In the latter case, a path to a temporary directory for // the new application's storage directory is returned. QString storageDir = handleNewAppInstance(&qSafeApp, argc, argv, "BlueBerry.newInstance"); if (storageDir.isEmpty()) { // This is a new instance and no other instance is already running. We specify // the storage directory here (this is the same code as in berryInternalPlatform.cpp // so that we can re-use the location for the persistent data location of the // the CppMicroServices library. // Append a hash value of the absolute path of the executable to the data location. // This allows to start the same application from different build or install trees. storageDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation) + '_'; storageDir += QString::number(qHash(QCoreApplication::applicationDirPath())) + "/"; } us::ModuleSettings::SetStoragePath((storageDir + "us/").toStdString()); // These paths replace the .ini file and are tailored for installation // packages created with CPack. If a .ini file is presented, it will // overwrite the settings in MapConfiguration Poco::Path basePath(argv[0]); basePath.setFileName(""); Poco::Path provFile(basePath); provFile.setFileName("mitkWorkbench.provisioning"); Poco::Path extPath(basePath); extPath.pushDirectory("ExtBundles"); std::string pluginDirs = extPath.toString(); Poco::Util::MapConfiguration* extConfig(new Poco::Util::MapConfiguration()); if (!storageDir.isEmpty()) { extConfig->setString(berry::Platform::ARG_STORAGE_DIR, storageDir.toStdString()); } extConfig->setString(berry::Platform::ARG_PLUGIN_DIRS, pluginDirs); extConfig->setString(berry::Platform::ARG_PROVISIONING, provFile.toString()); extConfig->setString(berry::Platform::ARG_APPLICATION, "org.mitk.qt.extapplication"); #ifdef Q_OS_WIN #define CTK_LIB_PREFIX #else #define CTK_LIB_PREFIX "lib" #endif // Preload the org.mitk.gui.qt.ext plug-in (and hence also QmitkExt) to speed // up a clean-cache start. This also works around bugs in older gcc and glibc implementations, // which have difficulties with multiple dynamic opening and closing of shared libraries with // many global static initializers. It also helps if dependent libraries have weird static // initialization methods and/or missing de-initialization code. extConfig->setString(berry::Platform::ARG_PRELOAD_LIBRARY, "liborg_mitk_gui_qt_ext," CTK_LIB_PREFIX "CTKDICOMCore:0.1"); // Seed the random number generator, once at startup. QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // Run the workbench. return berry::Starter::Run(argc, argv, extConfig); } <|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 "remoting/jingle_glue/ssl_socket_adapter.h" #include "base/base64.h" #include "base/compiler_specific.h" #include "base/message_loop.h" #include "jingle/glue/utils.h" #include "net/base/address_list.h" #include "net/base/cert_verifier.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/base/ssl_config_service.h" #include "net/base/sys_addrinfo.h" #include "net/socket/client_socket_factory.h" #include "net/url_request/url_request_context.h" namespace remoting { namespace { // NSS doesn't load root certificates when running in sandbox, so we // need to have gmail's cert hardcoded. // // TODO(sergeyu): Remove this when we don't make XMPP connection from // inside of sandbox. const char kGmailCertBase64[] = "MIIC2TCCAkKgAwIBAgIDBz+SMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT" "MRAwDgYDVQQKEwdFcXVpZmF4MS0wKwYDVQQLEyRFcXVpZmF4IFNlY3VyZSBDZXJ0" "aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDcwNDExMTcxNzM4WhcNMTIwNDEwMTcxNzM4" "WjBkMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMN" "TW91bnRhaW4gVmlldzEUMBIGA1UEChMLR29vZ2xlIEluYy4xEjAQBgNVBAMTCWdt" "YWlsLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1Hds2jWwXAVGef06" "7PeSJF/h9BnoYlTdykx0lBTDc92/JLvuq0lJkytqll1UR4kHmF4vwqQkwcqOK03w" "k8qDK8fh6M13PYhvPEXP02ozsuL3vqE8hcCva2B9HVnOPY17Qok37rYQ+yexswN5" "eh0+93nddEa1PyHgEQ8CDKCJaWUCAwEAAaOBrjCBqzAOBgNVHQ8BAf8EBAMCBPAw" "HQYDVR0OBBYEFJcjzXEevMEDIEvuQiT7puEJY737MDoGA1UdHwQzMDEwL6AtoCuG" "KWh0dHA6Ly9jcmwuZ2VvdHJ1c3QuY29tL2NybHMvc2VjdXJlY2EuY3JsMB8GA1Ud" "IwQYMBaAFEjmaPkr0rKV10fYIyAQTzOYkJ/UMB0GA1UdJQQWMBQGCCsGAQUFBwMB" "BggrBgEFBQcDAjANBgkqhkiG9w0BAQUFAAOBgQB74cGpjdENf9U+WEd29dfzY3Tz" "JehnlY5cH5as8bOTe7PNPzj967OJ7TPWEycMwlS7CsqIsmfRGOFFfoHxo+iPugZ8" "uO2Kd++QHCXL+MumGjkW4FcTFmceV/Q12Wdh3WApcqIZZciQ79MAeFh7bzteAYqf" "wC98YQwylC9wVhf1yw=="; } // namespace SSLSocketAdapter* SSLSocketAdapter::Create(AsyncSocket* socket) { return new SSLSocketAdapter(socket); } SSLSocketAdapter::SSLSocketAdapter(AsyncSocket* socket) : SSLAdapter(socket), ignore_bad_cert_(false), cert_verifier_(new net::CertVerifier()), ALLOW_THIS_IN_INITIALIZER_LIST( connected_callback_(this, &SSLSocketAdapter::OnConnected)), ALLOW_THIS_IN_INITIALIZER_LIST( read_callback_(this, &SSLSocketAdapter::OnRead)), ALLOW_THIS_IN_INITIALIZER_LIST( write_callback_(this, &SSLSocketAdapter::OnWrite)), ssl_state_(SSLSTATE_NONE), read_state_(IOSTATE_NONE), write_state_(IOSTATE_NONE) { transport_socket_ = new TransportSocket(socket, this); } SSLSocketAdapter::~SSLSocketAdapter() { } int SSLSocketAdapter::StartSSL(const char* hostname, bool restartable) { DCHECK(!restartable); hostname_ = hostname; if (socket_->GetState() != Socket::CS_CONNECTED) { ssl_state_ = SSLSTATE_WAIT; return 0; } else { return BeginSSL(); } } int SSLSocketAdapter::BeginSSL() { if (!MessageLoop::current()) { // Certificate verification is done via the Chrome message loop. // Without this check, if we don't have a chrome message loop the // SSL connection just hangs silently. LOG(DFATAL) << "Chrome message loop (needed by SSL certificate " << "verification) does not exist"; return net::ERR_UNEXPECTED; } // SSLConfigService is not thread-safe, and the default values for SSLConfig // are correct for us, so we don't use the config service to initialize this // object. net::SSLConfig ssl_config; std::string gmail_cert_binary; base::Base64Decode(kGmailCertBase64, &gmail_cert_binary); scoped_refptr<net::X509Certificate> gmail_cert = net::X509Certificate::CreateFromBytes(gmail_cert_binary.data(), gmail_cert_binary.size()); DCHECK(gmail_cert); net::SSLConfig::CertAndStatus gmail_cert_status; gmail_cert_status.cert = gmail_cert; gmail_cert_status.cert_status = 0; ssl_config.allowed_bad_certs.push_back(gmail_cert_status); transport_socket_->set_addr(talk_base::SocketAddress(hostname_, 0)); ssl_socket_.reset( net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket( transport_socket_, net::HostPortPair(hostname_, 443), ssl_config, NULL /* ssl_host_info */, cert_verifier_.get())); int result = ssl_socket_->Connect(&connected_callback_); if (result == net::ERR_IO_PENDING || result == net::OK) { return 0; } else { LOG(ERROR) << "Could not start SSL: " << net::ErrorToString(result); return result; } } int SSLSocketAdapter::Send(const void* buf, size_t len) { if (ssl_state_ != SSLSTATE_CONNECTED) { return AsyncSocketAdapter::Send(buf, len); } else { scoped_refptr<net::IOBuffer> transport_buf(new net::IOBuffer(len)); memcpy(transport_buf->data(), buf, len); int result = ssl_socket_->Write(transport_buf, len, NULL); if (result == net::ERR_IO_PENDING) { SetError(EWOULDBLOCK); } transport_buf = NULL; return result; } } int SSLSocketAdapter::Recv(void* buf, size_t len) { switch (ssl_state_) { case SSLSTATE_NONE: return AsyncSocketAdapter::Recv(buf, len); case SSLSTATE_WAIT: SetError(EWOULDBLOCK); return -1; case SSLSTATE_CONNECTED: switch (read_state_) { case IOSTATE_NONE: { transport_buf_ = new net::IOBuffer(len); int result = ssl_socket_->Read(transport_buf_, len, &read_callback_); if (result >= 0) { memcpy(buf, transport_buf_->data(), len); } if (result == net::ERR_IO_PENDING) { read_state_ = IOSTATE_PENDING; SetError(EWOULDBLOCK); } else { if (result < 0) { SetError(result); VLOG(1) << "Socket error " << result; } transport_buf_ = NULL; } return result; } case IOSTATE_PENDING: SetError(EWOULDBLOCK); return -1; case IOSTATE_COMPLETE: memcpy(buf, transport_buf_->data(), len); transport_buf_ = NULL; read_state_ = IOSTATE_NONE; return data_transferred_; } } NOTREACHED(); return -1; } void SSLSocketAdapter::OnConnected(int result) { if (result == net::OK) { ssl_state_ = SSLSTATE_CONNECTED; OnConnectEvent(this); } else { LOG(WARNING) << "OnConnected failed with error " << result; } } void SSLSocketAdapter::OnRead(int result) { DCHECK(read_state_ == IOSTATE_PENDING); read_state_ = IOSTATE_COMPLETE; data_transferred_ = result; AsyncSocketAdapter::OnReadEvent(this); } void SSLSocketAdapter::OnWrite(int result) { DCHECK(write_state_ == IOSTATE_PENDING); write_state_ = IOSTATE_COMPLETE; data_transferred_ = result; AsyncSocketAdapter::OnWriteEvent(this); } void SSLSocketAdapter::OnConnectEvent(talk_base::AsyncSocket* socket) { if (ssl_state_ != SSLSTATE_WAIT) { AsyncSocketAdapter::OnConnectEvent(socket); } else { ssl_state_ = SSLSTATE_NONE; int result = BeginSSL(); if (0 != result) { // TODO(zork): Handle this case gracefully. LOG(WARNING) << "BeginSSL() failed with " << result; } } } TransportSocket::TransportSocket(talk_base::AsyncSocket* socket, SSLSocketAdapter *ssl_adapter) : read_callback_(NULL), write_callback_(NULL), read_buffer_len_(0), write_buffer_len_(0), socket_(socket), was_used_to_convey_data_(false) { socket_->SignalReadEvent.connect(this, &TransportSocket::OnReadEvent); socket_->SignalWriteEvent.connect(this, &TransportSocket::OnWriteEvent); } TransportSocket::~TransportSocket() { } int TransportSocket::Connect(net::CompletionCallback* callback) { // Connect is never called by SSLClientSocket, instead SSLSocketAdapter // calls Connect() on socket_ directly. NOTREACHED(); return false; } void TransportSocket::Disconnect() { socket_->Close(); } bool TransportSocket::IsConnected() const { return (socket_->GetState() == talk_base::Socket::CS_CONNECTED); } bool TransportSocket::IsConnectedAndIdle() const { // Not implemented. NOTREACHED(); return false; } int TransportSocket::GetPeerAddress(net::AddressList* address) const { talk_base::SocketAddress socket_address = socket_->GetRemoteAddress(); // libjingle supports only IPv4 addresses. sockaddr_in ipv4addr; socket_address.ToSockAddr(&ipv4addr); struct addrinfo ai; memset(&ai, 0, sizeof(ai)); ai.ai_family = ipv4addr.sin_family; ai.ai_socktype = SOCK_STREAM; ai.ai_protocol = IPPROTO_TCP; ai.ai_addr = reinterpret_cast<struct sockaddr*>(&ipv4addr); ai.ai_addrlen = sizeof(ipv4addr); *address = net::AddressList::CreateByCopyingFirstAddress(&ai); return net::OK; } int TransportSocket::GetLocalAddress(net::IPEndPoint* address) const { talk_base::SocketAddress socket_address = socket_->GetLocalAddress(); if (jingle_glue::SocketAddressToIPEndPoint(socket_address, address)) { return net::OK; } else { return net::ERR_FAILED; } } const net::BoundNetLog& TransportSocket::NetLog() const { return net_log_; } void TransportSocket::SetSubresourceSpeculation() { NOTREACHED(); } void TransportSocket::SetOmniboxSpeculation() { NOTREACHED(); } bool TransportSocket::WasEverUsed() const { // We don't use this in ClientSocketPools, so this should never be used. NOTREACHED(); return was_used_to_convey_data_; } bool TransportSocket::UsingTCPFastOpen() const { return false; } int TransportSocket::Read(net::IOBuffer* buf, int buf_len, net::CompletionCallback* callback) { DCHECK(buf); DCHECK(!read_callback_); DCHECK(!read_buffer_.get()); int result = socket_->Recv(buf->data(), buf_len); if (result < 0) { result = net::MapSystemError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { read_callback_ = callback; read_buffer_ = buf; read_buffer_len_ = buf_len; } } if (result != net::ERR_IO_PENDING) was_used_to_convey_data_ = true; return result; } int TransportSocket::Write(net::IOBuffer* buf, int buf_len, net::CompletionCallback* callback) { DCHECK(buf); DCHECK(!write_callback_); DCHECK(!write_buffer_.get()); int result = socket_->Send(buf->data(), buf_len); if (result < 0) { result = net::MapSystemError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { write_callback_ = callback; write_buffer_ = buf; write_buffer_len_ = buf_len; } } if (result != net::ERR_IO_PENDING) was_used_to_convey_data_ = true; return result; } bool TransportSocket::SetReceiveBufferSize(int32 size) { // Not implemented. return false; } bool TransportSocket::SetSendBufferSize(int32 size) { // Not implemented. return false; } void TransportSocket::OnReadEvent(talk_base::AsyncSocket* socket) { if (read_callback_) { DCHECK(read_buffer_.get()); net::CompletionCallback* callback = read_callback_; scoped_refptr<net::IOBuffer> buffer = read_buffer_; int buffer_len = read_buffer_len_; read_callback_ = NULL; read_buffer_ = NULL; read_buffer_len_ = 0; int result = socket_->Recv(buffer->data(), buffer_len); if (result < 0) { result = net::MapSystemError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { read_callback_ = callback; read_buffer_ = buffer; read_buffer_len_ = buffer_len; return; } } was_used_to_convey_data_ = true; callback->RunWithParams(Tuple1<int>(result)); } } void TransportSocket::OnWriteEvent(talk_base::AsyncSocket* socket) { if (write_callback_) { DCHECK(write_buffer_.get()); net::CompletionCallback* callback = write_callback_; scoped_refptr<net::IOBuffer> buffer = write_buffer_; int buffer_len = write_buffer_len_; write_callback_ = NULL; write_buffer_ = NULL; write_buffer_len_ = 0; int result = socket_->Send(buffer->data(), buffer_len); if (result < 0) { result = net::MapSystemError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { write_callback_ = callback; write_buffer_ = buffer; write_buffer_len_ = buffer_len; return; } } was_used_to_convey_data_ = true; callback->RunWithParams(Tuple1<int>(result)); } } } // namespace remoting <commit_msg>Remove gmail cert from SSLSocketAdapter.<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 "remoting/jingle_glue/ssl_socket_adapter.h" #include "base/base64.h" #include "base/compiler_specific.h" #include "base/message_loop.h" #include "jingle/glue/utils.h" #include "net/base/address_list.h" #include "net/base/cert_verifier.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/base/ssl_config_service.h" #include "net/base/sys_addrinfo.h" #include "net/socket/client_socket_factory.h" #include "net/url_request/url_request_context.h" namespace remoting { SSLSocketAdapter* SSLSocketAdapter::Create(AsyncSocket* socket) { return new SSLSocketAdapter(socket); } SSLSocketAdapter::SSLSocketAdapter(AsyncSocket* socket) : SSLAdapter(socket), ignore_bad_cert_(false), cert_verifier_(new net::CertVerifier()), ALLOW_THIS_IN_INITIALIZER_LIST( connected_callback_(this, &SSLSocketAdapter::OnConnected)), ALLOW_THIS_IN_INITIALIZER_LIST( read_callback_(this, &SSLSocketAdapter::OnRead)), ALLOW_THIS_IN_INITIALIZER_LIST( write_callback_(this, &SSLSocketAdapter::OnWrite)), ssl_state_(SSLSTATE_NONE), read_state_(IOSTATE_NONE), write_state_(IOSTATE_NONE) { transport_socket_ = new TransportSocket(socket, this); } SSLSocketAdapter::~SSLSocketAdapter() { } int SSLSocketAdapter::StartSSL(const char* hostname, bool restartable) { DCHECK(!restartable); hostname_ = hostname; if (socket_->GetState() != Socket::CS_CONNECTED) { ssl_state_ = SSLSTATE_WAIT; return 0; } else { return BeginSSL(); } } int SSLSocketAdapter::BeginSSL() { if (!MessageLoop::current()) { // Certificate verification is done via the Chrome message loop. // Without this check, if we don't have a chrome message loop the // SSL connection just hangs silently. LOG(DFATAL) << "Chrome message loop (needed by SSL certificate " << "verification) does not exist"; return net::ERR_UNEXPECTED; } // SSLConfigService is not thread-safe, and the default values for SSLConfig // are correct for us, so we don't use the config service to initialize this // object. net::SSLConfig ssl_config; transport_socket_->set_addr(talk_base::SocketAddress(hostname_, 0)); ssl_socket_.reset( net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket( transport_socket_, net::HostPortPair(hostname_, 443), ssl_config, NULL /* ssl_host_info */, cert_verifier_.get())); int result = ssl_socket_->Connect(&connected_callback_); if (result == net::ERR_IO_PENDING || result == net::OK) { return 0; } else { LOG(ERROR) << "Could not start SSL: " << net::ErrorToString(result); return result; } } int SSLSocketAdapter::Send(const void* buf, size_t len) { if (ssl_state_ != SSLSTATE_CONNECTED) { return AsyncSocketAdapter::Send(buf, len); } else { scoped_refptr<net::IOBuffer> transport_buf(new net::IOBuffer(len)); memcpy(transport_buf->data(), buf, len); int result = ssl_socket_->Write(transport_buf, len, NULL); if (result == net::ERR_IO_PENDING) { SetError(EWOULDBLOCK); } transport_buf = NULL; return result; } } int SSLSocketAdapter::Recv(void* buf, size_t len) { switch (ssl_state_) { case SSLSTATE_NONE: return AsyncSocketAdapter::Recv(buf, len); case SSLSTATE_WAIT: SetError(EWOULDBLOCK); return -1; case SSLSTATE_CONNECTED: switch (read_state_) { case IOSTATE_NONE: { transport_buf_ = new net::IOBuffer(len); int result = ssl_socket_->Read(transport_buf_, len, &read_callback_); if (result >= 0) { memcpy(buf, transport_buf_->data(), len); } if (result == net::ERR_IO_PENDING) { read_state_ = IOSTATE_PENDING; SetError(EWOULDBLOCK); } else { if (result < 0) { SetError(result); VLOG(1) << "Socket error " << result; } transport_buf_ = NULL; } return result; } case IOSTATE_PENDING: SetError(EWOULDBLOCK); return -1; case IOSTATE_COMPLETE: memcpy(buf, transport_buf_->data(), len); transport_buf_ = NULL; read_state_ = IOSTATE_NONE; return data_transferred_; } } NOTREACHED(); return -1; } void SSLSocketAdapter::OnConnected(int result) { if (result == net::OK) { ssl_state_ = SSLSTATE_CONNECTED; OnConnectEvent(this); } else { LOG(WARNING) << "OnConnected failed with error " << result; } } void SSLSocketAdapter::OnRead(int result) { DCHECK(read_state_ == IOSTATE_PENDING); read_state_ = IOSTATE_COMPLETE; data_transferred_ = result; AsyncSocketAdapter::OnReadEvent(this); } void SSLSocketAdapter::OnWrite(int result) { DCHECK(write_state_ == IOSTATE_PENDING); write_state_ = IOSTATE_COMPLETE; data_transferred_ = result; AsyncSocketAdapter::OnWriteEvent(this); } void SSLSocketAdapter::OnConnectEvent(talk_base::AsyncSocket* socket) { if (ssl_state_ != SSLSTATE_WAIT) { AsyncSocketAdapter::OnConnectEvent(socket); } else { ssl_state_ = SSLSTATE_NONE; int result = BeginSSL(); if (0 != result) { // TODO(zork): Handle this case gracefully. LOG(WARNING) << "BeginSSL() failed with " << result; } } } TransportSocket::TransportSocket(talk_base::AsyncSocket* socket, SSLSocketAdapter *ssl_adapter) : read_callback_(NULL), write_callback_(NULL), read_buffer_len_(0), write_buffer_len_(0), socket_(socket), was_used_to_convey_data_(false) { socket_->SignalReadEvent.connect(this, &TransportSocket::OnReadEvent); socket_->SignalWriteEvent.connect(this, &TransportSocket::OnWriteEvent); } TransportSocket::~TransportSocket() { } int TransportSocket::Connect(net::CompletionCallback* callback) { // Connect is never called by SSLClientSocket, instead SSLSocketAdapter // calls Connect() on socket_ directly. NOTREACHED(); return false; } void TransportSocket::Disconnect() { socket_->Close(); } bool TransportSocket::IsConnected() const { return (socket_->GetState() == talk_base::Socket::CS_CONNECTED); } bool TransportSocket::IsConnectedAndIdle() const { // Not implemented. NOTREACHED(); return false; } int TransportSocket::GetPeerAddress(net::AddressList* address) const { talk_base::SocketAddress socket_address = socket_->GetRemoteAddress(); // libjingle supports only IPv4 addresses. sockaddr_in ipv4addr; socket_address.ToSockAddr(&ipv4addr); struct addrinfo ai; memset(&ai, 0, sizeof(ai)); ai.ai_family = ipv4addr.sin_family; ai.ai_socktype = SOCK_STREAM; ai.ai_protocol = IPPROTO_TCP; ai.ai_addr = reinterpret_cast<struct sockaddr*>(&ipv4addr); ai.ai_addrlen = sizeof(ipv4addr); *address = net::AddressList::CreateByCopyingFirstAddress(&ai); return net::OK; } int TransportSocket::GetLocalAddress(net::IPEndPoint* address) const { talk_base::SocketAddress socket_address = socket_->GetLocalAddress(); if (jingle_glue::SocketAddressToIPEndPoint(socket_address, address)) { return net::OK; } else { return net::ERR_FAILED; } } const net::BoundNetLog& TransportSocket::NetLog() const { return net_log_; } void TransportSocket::SetSubresourceSpeculation() { NOTREACHED(); } void TransportSocket::SetOmniboxSpeculation() { NOTREACHED(); } bool TransportSocket::WasEverUsed() const { // We don't use this in ClientSocketPools, so this should never be used. NOTREACHED(); return was_used_to_convey_data_; } bool TransportSocket::UsingTCPFastOpen() const { return false; } int TransportSocket::Read(net::IOBuffer* buf, int buf_len, net::CompletionCallback* callback) { DCHECK(buf); DCHECK(!read_callback_); DCHECK(!read_buffer_.get()); int result = socket_->Recv(buf->data(), buf_len); if (result < 0) { result = net::MapSystemError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { read_callback_ = callback; read_buffer_ = buf; read_buffer_len_ = buf_len; } } if (result != net::ERR_IO_PENDING) was_used_to_convey_data_ = true; return result; } int TransportSocket::Write(net::IOBuffer* buf, int buf_len, net::CompletionCallback* callback) { DCHECK(buf); DCHECK(!write_callback_); DCHECK(!write_buffer_.get()); int result = socket_->Send(buf->data(), buf_len); if (result < 0) { result = net::MapSystemError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { write_callback_ = callback; write_buffer_ = buf; write_buffer_len_ = buf_len; } } if (result != net::ERR_IO_PENDING) was_used_to_convey_data_ = true; return result; } bool TransportSocket::SetReceiveBufferSize(int32 size) { // Not implemented. return false; } bool TransportSocket::SetSendBufferSize(int32 size) { // Not implemented. return false; } void TransportSocket::OnReadEvent(talk_base::AsyncSocket* socket) { if (read_callback_) { DCHECK(read_buffer_.get()); net::CompletionCallback* callback = read_callback_; scoped_refptr<net::IOBuffer> buffer = read_buffer_; int buffer_len = read_buffer_len_; read_callback_ = NULL; read_buffer_ = NULL; read_buffer_len_ = 0; int result = socket_->Recv(buffer->data(), buffer_len); if (result < 0) { result = net::MapSystemError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { read_callback_ = callback; read_buffer_ = buffer; read_buffer_len_ = buffer_len; return; } } was_used_to_convey_data_ = true; callback->RunWithParams(Tuple1<int>(result)); } } void TransportSocket::OnWriteEvent(talk_base::AsyncSocket* socket) { if (write_callback_) { DCHECK(write_buffer_.get()); net::CompletionCallback* callback = write_callback_; scoped_refptr<net::IOBuffer> buffer = write_buffer_; int buffer_len = write_buffer_len_; write_callback_ = NULL; write_buffer_ = NULL; write_buffer_len_ = 0; int result = socket_->Send(buffer->data(), buffer_len); if (result < 0) { result = net::MapSystemError(socket_->GetError()); if (result == net::ERR_IO_PENDING) { write_callback_ = callback; write_buffer_ = buffer; write_buffer_len_ = buffer_len; return; } } was_used_to_convey_data_ = true; callback->RunWithParams(Tuple1<int>(result)); } } } // namespace remoting <|endoftext|>
<commit_before>#include "audiostreamer.h" #include "audiocallback.h" #include <QSettings> using namespace std; /* * Class to handle the RtAudio soundcard API. */ AudioStreamer::AudioStreamer(QObject *parent) : QObject(parent) { QSettings settings; unsigned int processingInterval = settings.value("audiostreamer/processingInterval", 25).toUInt(); unsigned int processingBufferSize = settings.value("audiostreamer/processingBufferSize", 8192).toUInt(); try { rtAudio = new RtAudio(); activeDeviceId = settings.value("audiostreamer/activeDeviceId", rtAudio->getDefaultInputDevice()).toUInt(); } #ifdef RTERROR_H catch( RtError &error ) #else catch( RtAudioError& error ) #endif { error.printMessage(); } setupDeviceList(); allocateRingBuffers( getInputChannelIds(activeDeviceId), processingBufferSize ); // todo audioProcessing should be independant lib connected form outside .. connect(this, SIGNAL(triggerAudioProcessing(AudioBuffer*)), &audioProcessing, SLOT(processAudio(AudioBuffer*))); processingTimer = new QTimer(this); connect(processingTimer, SIGNAL(timeout()), this, SLOT(slotUpdateProcessingBuffer())); processingTimer->start(processingInterval); } /* * Class destructor stop all streams and free .. */ AudioStreamer::~AudioStreamer() { stopStream(); delete rtAudio; } /* * Request a list of devices known to RtAudio Api and collect them in a list. */ void AudioStreamer::setupDeviceList() { devices.clear(); for (unsigned int i = 0; i < rtAudio->getDeviceCount(); i++) { try { RtAudio::DeviceInfo info = rtAudio->getDeviceInfo(i); devices.push_back(info); } #ifdef RTERROR_H catch( RtError &error ) #else catch( RtAudioError &error ) #endif { error.printMessage(); break; } } } /* * Returns the list of detected RtAudio devices. */ QList<RtAudio::DeviceInfo> AudioStreamer::getListOfDevices() { return devices; } /* * Prints the list of devices to to console. */ void AudioStreamer::printListOfDevices() { int index = 0; foreach (RtAudio::DeviceInfo info, devices) { cout << (int)info.isDefaultInput << " [" << index++ << "] " << info.name; cout << ": max outputs = " << info.outputChannels << " "; cout << ": max inputs = " << info.inputChannels << " "; cout << ": dup chCount = " << info.duplexChannels << "\n"; std::vector<unsigned int> sampleRates = info.sampleRates; cout << " SR [kHz]: "; for( unsigned int j=0; j<sampleRates.size(); j++ ) { cout << sampleRates[j] << ", "; } cout << endl; } } /* * Returns a list of ids of all available input channels of the active device. */ QList<unsigned int> AudioStreamer::getInputChannelIds(int deviceId) { QList<unsigned int> channels; for( unsigned int i=0; i<numberOfInputChannels(deviceId); i++ ) { channels.push_back(i); } return channels; } /* * Returns the number of input channels for the given device. * If the given id <= -1 returns the input channels of the active device. */ unsigned int AudioStreamer::numberOfInputChannels(int deviceId) { unsigned int id = activeDeviceId; if( deviceId > -1 && deviceId < devices.size() ) id = deviceId; return devices.at(id).inputChannels; } /* * Allocates ringbuffers for aquisition and processing of each channel for the active device. */ void AudioStreamer::allocateRingBuffers(QList<unsigned int> channels, unsigned int size) { acquisitionBuffer.allocateRingbuffers(size, channels); processingBuffer.allocateRingbuffers(size, channels); } /* * Changes the channel ids used for audio streaming. */ void AudioStreamer::setActiveChannels(QList<unsigned int> channels) { setActiveDevice(activeDeviceId, channels); } /* * Switches the audio device to be used. Stops running stream and resets buffers. */ void AudioStreamer::setActiveDevice(unsigned int id, QList<unsigned int> channels) { stopStream(); activeDeviceId = id; if( channels.isEmpty() ) channels = getInputChannelIds(); allocateRingBuffers(channels, acquisitionBuffer.ringBufferSize); } /* * Opens and starts the audio stream to be prossessed by audioprocessor callback. */ bool AudioStreamer::startStream(StreamSettings settings) { if( acquisitionBuffer.numberOfChannels() == 0 ) { cout << "Warning: Unable to start stream without input channels!" << endl; return false; } unsigned int firstChannelId = acquisitionBuffer.activeChannelIds.first(); unsigned int lastChannelId = acquisitionBuffer.activeChannelIds.last(); RtAudio::StreamParameters parameters = settings.parameters; parameters.nChannels = lastChannelId - firstChannelId + 1; parameters.deviceId = activeDeviceId; parameters.firstChannel = firstChannelId; double msInBuffer = 1000. * acquisitionBuffer.ringBufferSize / (double)settings.hwSampleRate; cout << "Starting audio stream of " << parameters.nChannels << " channels for device [" << activeDeviceId << "], buffer " << msInBuffer << " [ms]" << endl; cout << " - Active channels: "; foreach (unsigned int id, acquisitionBuffer.activeChannelIds) cout << "Ch" << id << " "; cout << endl; try { // todo: make audio format a config option rtAudio->openStream(NULL, &parameters, RTAUDIO_SINT16, settings.hwSampleRate, &settings.hwBufferSize, &AudioCallback::interleaved, &acquisitionBuffer); rtAudio->startStream(); } #ifdef RTERROR_H catch( RtError &error ) #else catch( RtAudioError& error ) #endif { error.printMessage(); return false; } return true; } /* * Stop and close the active audio stream. */ bool AudioStreamer::stopStream() { if( rtAudio->isStreamRunning() ) { try { rtAudio->stopStream(); } #ifdef RTERROR_H catch( RtError& error ) #else catch( RtAudioError& error ) #endif { error.printMessage(); return false; } } if( rtAudio->isStreamOpen() ) { try { rtAudio->closeStream(); } #ifdef RTERROR_H catch( RtError& error ) #else catch( RtAudioError& error ) #endif { error.printMessage(); return false; }; } return true; } /* * Refreshes processing buffer, copying actual content of the aquisition buffer and trigger processing. */ void AudioStreamer::slotUpdateProcessingBuffer() { if( rtAudio->isStreamRunning() && rtAudio->isStreamOpen() ) { if( acquisitionBuffer.frameCounter / acquisitionBuffer.ringBufferSize > 1 ) { processingBuffer = acquisitionBuffer; cout << acquisitionBuffer.frameCounter; } emit triggerAudioProcessing(&processingBuffer); } } <commit_msg>Fixed initialization for devices with zero channels<commit_after>#include "audiostreamer.h" #include "audiocallback.h" #include <QSettings> using namespace std; /* * Class to handle the RtAudio soundcard API. */ AudioStreamer::AudioStreamer(QObject *parent) : QObject(parent) { QSettings settings; unsigned int processingInterval = settings.value("audiostreamer/processingInterval", 25).toUInt(); unsigned int processingBufferSize = settings.value("audiostreamer/processingBufferSize", 8192).toUInt(); try { rtAudio = new RtAudio(); activeDeviceId = settings.value("audiostreamer/activeDeviceId", rtAudio->getDefaultInputDevice()).toUInt(); } #ifdef RTERROR_H catch( RtError &error ) #else catch( RtAudioError& error ) #endif { error.printMessage(); } setupDeviceList(); allocateRingBuffers( getInputChannelIds(activeDeviceId), processingBufferSize ); // todo audioProcessing should be independant lib connected form outside .. connect(this, SIGNAL(triggerAudioProcessing(AudioBuffer*)), &audioProcessing, SLOT(processAudio(AudioBuffer*))); processingTimer = new QTimer(this); connect(processingTimer, SIGNAL(timeout()), this, SLOT(slotUpdateProcessingBuffer())); processingTimer->start(processingInterval); } /* * Class destructor stop all streams and free .. */ AudioStreamer::~AudioStreamer() { stopStream(); delete rtAudio; } /* * Request a list of devices known to RtAudio Api and collect them in a list. */ void AudioStreamer::setupDeviceList() { devices.clear(); try { for (unsigned int i = 0; i < rtAudio->getDeviceCount(); i++) { RtAudio::DeviceInfo info = rtAudio->getDeviceInfo(i); devices.push_back(info); } } #ifdef RTERROR_H catch( RtError &error ) #else catch( RtAudioError &error ) #endif { error.printMessage(); } } /* * Returns the list of detected RtAudio devices. */ QList<RtAudio::DeviceInfo> AudioStreamer::getListOfDevices() { return devices; } /* * Prints the list of devices to to console. */ void AudioStreamer::printListOfDevices() { int index = 0; foreach (RtAudio::DeviceInfo info, devices) { cout << (int)info.isDefaultInput << " [" << index++ << "] " << info.name; cout << ": max outputs = " << info.outputChannels << " "; cout << ": max inputs = " << info.inputChannels << " "; cout << ": dup chCount = " << info.duplexChannels << "\n"; std::vector<unsigned int> sampleRates = info.sampleRates; cout << " SR [kHz]: "; for( unsigned int j=0; j<sampleRates.size(); j++ ) { cout << sampleRates[j] << ", "; } cout << endl; } } /* * Returns a list of ids of all available input channels of the active device. */ QList<unsigned int> AudioStreamer::getInputChannelIds(int deviceId) { QList<unsigned int> channels; for( unsigned int i=0; i<numberOfInputChannels(deviceId); i++ ) { channels.push_back(i); } return channels; } /* * Returns the number of input channels for the active device (deviceId == -1). * If the given deviceId > -1 returns the input channels of this device. */ unsigned int AudioStreamer::numberOfInputChannels(int deviceId) { unsigned int channelCount = 0; unsigned int id = activeDeviceId; if( deviceId > -1 ) id = deviceId; if( !devices.isEmpty() && id < (unsigned int)devices.size() ) channelCount = devices.at(id).inputChannels; return channelCount; } /* * Allocates ringbuffers for aquisition and processing of each channel for the active device. */ void AudioStreamer::allocateRingBuffers(QList<unsigned int> channels, unsigned int size) { acquisitionBuffer.allocateRingbuffers(size, channels); processingBuffer.allocateRingbuffers(size, channels); } /* * Changes the channel ids used for audio streaming. */ void AudioStreamer::setActiveChannels(QList<unsigned int> channels) { setActiveDevice(activeDeviceId, channels); } /* * Switches the audio device to be used. Stops running stream and resets buffers. */ void AudioStreamer::setActiveDevice(unsigned int id, QList<unsigned int> channels) { stopStream(); activeDeviceId = id; if( channels.isEmpty() ) channels = getInputChannelIds(); allocateRingBuffers(channels, acquisitionBuffer.ringBufferSize); } /* * Opens and starts the audio stream to be prossessed by audioprocessor callback. */ bool AudioStreamer::startStream(StreamSettings settings) { if( acquisitionBuffer.numberOfChannels() == 0 ) { cout << "Warning: Unable to start stream without input channels!" << endl; return false; } unsigned int firstChannelId = acquisitionBuffer.activeChannelIds.first(); unsigned int lastChannelId = acquisitionBuffer.activeChannelIds.last(); RtAudio::StreamParameters parameters = settings.parameters; parameters.nChannels = lastChannelId - firstChannelId + 1; parameters.deviceId = activeDeviceId; parameters.firstChannel = firstChannelId; double msInBuffer = 1000. * acquisitionBuffer.ringBufferSize / (double)settings.hwSampleRate; cout << "Starting audio stream of " << parameters.nChannels << " channels for device [" << activeDeviceId << "], buffer " << msInBuffer << " [ms]" << endl; cout << " - Active channels: "; foreach (unsigned int id, acquisitionBuffer.activeChannelIds) cout << "Ch" << id << " "; cout << endl; try { // todo: make audio format a config option rtAudio->openStream(NULL, &parameters, RTAUDIO_SINT16, settings.hwSampleRate, &settings.hwBufferSize, &AudioCallback::interleaved, &acquisitionBuffer); rtAudio->startStream(); } #ifdef RTERROR_H catch( RtError &error ) #else catch( RtAudioError& error ) #endif { error.printMessage(); return false; } return true; } /* * Stop and close the active audio stream. */ bool AudioStreamer::stopStream() { if( rtAudio->isStreamRunning() ) { try { rtAudio->stopStream(); } #ifdef RTERROR_H catch( RtError& error ) #else catch( RtAudioError& error ) #endif { error.printMessage(); return false; } } if( rtAudio->isStreamOpen() ) { try { rtAudio->closeStream(); } #ifdef RTERROR_H catch( RtError& error ) #else catch( RtAudioError& error ) #endif { error.printMessage(); return false; }; } return true; } /* * Refreshes processing buffer, copying actual content of the aquisition buffer and trigger processing. */ void AudioStreamer::slotUpdateProcessingBuffer() { if( rtAudio->isStreamRunning() && rtAudio->isStreamOpen() ) { if( acquisitionBuffer.frameCounter / acquisitionBuffer.ringBufferSize > 1 ) { processingBuffer = acquisitionBuffer; cout << acquisitionBuffer.frameCounter; } emit triggerAudioProcessing(&processingBuffer); } } <|endoftext|>
<commit_before>#include <iostream> /* allows to perform standard input and output operations */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <string> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ //#include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int16_t EncoderL; /* stores encoder value left read from md49 */ int16_t EncoderR; /* stores encoder value right read from md49 */ int speed_l=128, speed_r=128; /* speed to set for MD49 */ bool cmd_vel_received=true; double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ int filedesc; /* filedescriptor serialport */ int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; /* stores original settings */ int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (int speed_l, int speed_r); void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z); //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden //serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed //serialBuffer[2] = 255; // speed1 //serialBuffer[3] = 255; // speed2 //writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } cmd_vel_received=true; } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",100); // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000); // Sleep for UART to power up and set options ROS_DEBUG("Serial Port opened \n"); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(10); while( n.ok() ) { // Read encoder and other data from MD49 // ************************************* read_MD49_Data(); // Set speed left andright for MD49 // ******************************** if (cmd_vel_received=true) {set_MD49_speed(speed_l,speed_r); cmd_vel_received=false;} //set_MD49_speed(speed_l,speed_r); // Publish encoder values to topic /encoders (custom message) // ******************************************************************** base_controller::encoders encoders; encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Loop // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); //printf("Encoder1 Byte1: %i ",serialBuffer[0]); //printf("Byte2: %i ",serialBuffer[1]); //printf("Byte3: % i ",serialBuffer[2]); //printf("Byte4: %i \n",serialBuffer[3]); //printf("Encoder2 Byte1: %i ",serialBuffer[4]); //printf("Byte2: %i ",serialBuffer[5]); //printf("Byte3: %i ",serialBuffer[6]); //printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("vl= %f \n", vl); printf("vr= %f \n", vr); } void set_MD49_speed (int speed_l, int speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); } <commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <string> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ //#include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int16_t EncoderL; /* stores encoder value left read from md49 */ int16_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ bool cmd_vel_received=true; double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ int filedesc; /* filedescriptor serialport */ int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; /* stores original settings */ int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z); //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden //serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed //serialBuffer[2] = 255; // speed1 //serialBuffer[3] = 255; // speed2 //writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } cmd_vel_received=true; } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",100); // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000); // Sleep for UART to power up and set options ROS_DEBUG("Serial Port opened \n"); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(10); while( n.ok() ) { // Read encoder and other data from MD49 // ************************************* read_MD49_Data(); // Set speed left andright for MD49 // ******************************** if (cmd_vel_received=true) {set_MD49_speed(speed_l,speed_r); cmd_vel_received=false;} //set_MD49_speed(speed_l,speed_r); // Publish encoder values to topic /encoders (custom message) // ******************************************************************** base_controller::encoders encoders; encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Loop // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); //printf("Encoder1 Byte1: %i ",serialBuffer[0]); //printf("Byte2: %i ",serialBuffer[1]); //printf("Byte3: % i ",serialBuffer[2]); //printf("Byte4: %i \n",serialBuffer[3]); //printf("Encoder2 Byte1: %i ",serialBuffer[4]); //printf("Byte2: %i ",serialBuffer[5]); //printf("Byte3: %i ",serialBuffer[6]); //printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("vl= %f \n", vl); printf("vr= %f \n", vr); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: WW8PieceTableImpl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hbrinkm $ $Date: 2006-11-15 16:36:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <algorithm> #include <iterator> #ifndef INCLUDED_DOCTOK_EXCEPTIONS #include <doctok/exceptions.hxx> #endif #ifndef INCLUDED_WW8_PIECE_TABLE_IMPL_HXX #include <WW8PieceTableImpl.hxx> #endif #ifndef INCLUDED_WW8_CLX_HXX #include <WW8Clx.hxx> #endif namespace doctok { using namespace ::std; ostream & operator << (ostream & o, const WW8PieceTable & rPieceTable) { rPieceTable.dump(o); return o; } WW8PieceTableImpl::WW8PieceTableImpl(WW8Stream & rStream, sal_uInt32 nOffset, sal_uInt32 nCount) { WW8Clx aClx(rStream, nOffset, nCount); sal_uInt32 nPieceCount = aClx.getPieceCount(); if (nPieceCount > 0) { for (sal_uInt32 n = 0; n < nPieceCount; n++) { Cp aCp(aClx.getCp(n)); Fc aFc(aClx.getFc(n), aClx.isComplexFc(n)); CpAndFc aCpAndFc(aCp, aFc, PROP_DOC); mEntries.push_back(aCpAndFc); } CpAndFc aBack = mEntries.back(); Cp aCp(aClx.getCp(aClx.getPieceCount())); Fc aFc(aBack.getFc() + (aCp - aBack.getCp())); CpAndFc aCpAndFc(aCp, aFc, PROP_DOC); mEntries.push_back(aCpAndFc); } } sal_uInt32 WW8PieceTableImpl::getCount() const { return mEntries.size(); } WW8PieceTableImpl::tEntries::const_iterator WW8PieceTableImpl::findCp(const Cp & rCp) const { tEntries::const_iterator aResult = mEntries.end(); tEntries::const_iterator aEnd = mEntries.end(); for (tEntries::const_iterator aIt = mEntries.begin(); aIt != aEnd; aIt++) { if (aIt->getCp() <= rCp) { aResult = aIt; //break; } } return aResult; } WW8PieceTableImpl::tEntries::const_iterator WW8PieceTableImpl::findFc(const Fc & rFc) const { tEntries::const_iterator aResult = mEntries.end(); tEntries::const_iterator aEnd = mEntries.end(); if (mEntries.size() > 0) { if (rFc < mEntries.begin()->getFc()) aResult = mEntries.begin(); else { for (tEntries::const_iterator aIt = mEntries.begin(); aIt != aEnd; aIt++) { if (aIt->getFc() <= rFc) { tEntries::const_iterator aItNext = aIt; aItNext++; if (aItNext != aEnd) { sal_uInt32 nOffset = rFc.get() - aIt->getFc().get(); sal_uInt32 nLength = aItNext->getCp() - aIt->getCp(); if (! aIt->isComplex()) nLength *= 2; if (nOffset < nLength) { aResult = aIt; break; } } } } } } return aResult; } Cp WW8PieceTableImpl::getFirstCp() const { Cp aResult; if (getCount() > 0) aResult = getCp(0); else throw ExceptionNotFound("WW8PieceTableImpl::getFirstCp"); return aResult; } Fc WW8PieceTableImpl::getFirstFc() const { Fc aResult; if (getCount() > 0) aResult = getFc(0); else throw ExceptionNotFound(" WW8PieceTableImpl::getFirstFc"); return aResult; } Cp WW8PieceTableImpl::getLastCp() const { Cp aResult; if (getCount() > 0) aResult = getCp(getCount() - 1); else throw ExceptionNotFound("WW8PieceTableImpl::getLastCp"); return aResult; } Fc WW8PieceTableImpl::getLastFc() const { Fc aResult; if (getCount() > 0) aResult = getFc(getCount() - 1); else throw ExceptionNotFound("WW8PieceTableImpl::getLastFc"); return aResult; } Cp WW8PieceTableImpl::getCp(sal_uInt32 nIndex) const { return mEntries[nIndex].getCp(); } Fc WW8PieceTableImpl::getFc(sal_uInt32 nIndex) const { return mEntries[nIndex].getFc(); } Cp WW8PieceTableImpl::fc2cp(const Fc & rFc) const { Cp cpResult; if (mEntries.size() > 0) { Fc aFc; if (rFc < mEntries.begin()->getFc()) aFc = mEntries.begin()->getFc(); else aFc = rFc; tEntries::const_iterator aIt = findFc(aFc); if (aIt != mEntries.end()) { cpResult = aIt->getCp() + (aFc - aIt->getFc()); } else throw ExceptionNotFound("WW8PieceTableImpl::fc2cp: " + aFc.toString()); } return cpResult; } Fc WW8PieceTableImpl::cp2fc(const Cp & rCp) const { Fc aResult; Cp2FcHashMap_t::iterator aItCp = mCp2FcCache.find(rCp); if (aItCp == mCp2FcCache.end()) { tEntries::const_iterator aIt = findCp(rCp); if (aIt != mEntries.end()) { aResult = aIt->getFc() + (rCp - aIt->getCp()); mCp2FcCache[rCp] = aResult; } else throw ExceptionNotFound ("WW8PieceTableImpl::cp2fc: " + rCp.toString()); } else aResult = mCp2FcCache[rCp]; return aResult; } bool WW8PieceTableImpl::isComplex(const Cp & rCp) const { bool bResult = false; tEntries::const_iterator aIt = findCp(rCp); if (aIt != mEntries.end()) bResult = aIt->isComplex(); return bResult; } bool WW8PieceTableImpl::isComplex(const Fc & rFc) const { bool bResult = false; tEntries::const_iterator aIt = findFc(rFc); if (aIt != mEntries.end()) bResult = aIt->isComplex(); return bResult; } CpAndFc WW8PieceTableImpl::createCpAndFc (const Cp & rCp, PropertyType eType) const { return CpAndFc(rCp, cp2fc(rCp), eType); } CpAndFc WW8PieceTableImpl::createCpAndFc (const Fc & rFc, PropertyType eType) const { return CpAndFc(fc2cp(rFc), rFc, eType); } void WW8PieceTableImpl::dump(ostream & o) const { o << "<piecetable>" << endl; copy(mEntries.begin(), mEntries.end(), ostream_iterator<CpAndFc>(o, "\n")); o << "</piecetable>" << endl; } } <commit_msg>INTEGRATION: CWS xmlfilter02 (1.3.12); FILE MERGED 2007/12/03 09:34:58 hbrinkm 1.3.12.2: exceptions.hxx moved to resourcemodel 2007/11/14 12:57:47 hbrinkm 1.3.12.1: namespace clean up<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: WW8PieceTableImpl.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2008-01-10 11:48:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <algorithm> #include <iterator> #ifndef INCLUDED_DOCTOK_EXCEPTIONS #include <resourcemodel/exceptions.hxx> #endif #ifndef INCLUDED_WW8_PIECE_TABLE_IMPL_HXX #include <WW8PieceTableImpl.hxx> #endif #ifndef INCLUDED_WW8_CLX_HXX #include <WW8Clx.hxx> #endif namespace writerfilter { namespace doctok { using namespace ::std; ostream & operator << (ostream & o, const WW8PieceTable & rPieceTable) { rPieceTable.dump(o); return o; } WW8PieceTableImpl::WW8PieceTableImpl(WW8Stream & rStream, sal_uInt32 nOffset, sal_uInt32 nCount) { WW8Clx aClx(rStream, nOffset, nCount); sal_uInt32 nPieceCount = aClx.getPieceCount(); if (nPieceCount > 0) { for (sal_uInt32 n = 0; n < nPieceCount; n++) { Cp aCp(aClx.getCp(n)); Fc aFc(aClx.getFc(n), aClx.isComplexFc(n)); CpAndFc aCpAndFc(aCp, aFc, PROP_DOC); mEntries.push_back(aCpAndFc); } CpAndFc aBack = mEntries.back(); Cp aCp(aClx.getCp(aClx.getPieceCount())); Fc aFc(aBack.getFc() + (aCp - aBack.getCp())); CpAndFc aCpAndFc(aCp, aFc, PROP_DOC); mEntries.push_back(aCpAndFc); } } sal_uInt32 WW8PieceTableImpl::getCount() const { return mEntries.size(); } WW8PieceTableImpl::tEntries::const_iterator WW8PieceTableImpl::findCp(const Cp & rCp) const { tEntries::const_iterator aResult = mEntries.end(); tEntries::const_iterator aEnd = mEntries.end(); for (tEntries::const_iterator aIt = mEntries.begin(); aIt != aEnd; aIt++) { if (aIt->getCp() <= rCp) { aResult = aIt; //break; } } return aResult; } WW8PieceTableImpl::tEntries::const_iterator WW8PieceTableImpl::findFc(const Fc & rFc) const { tEntries::const_iterator aResult = mEntries.end(); tEntries::const_iterator aEnd = mEntries.end(); if (mEntries.size() > 0) { if (rFc < mEntries.begin()->getFc()) aResult = mEntries.begin(); else { for (tEntries::const_iterator aIt = mEntries.begin(); aIt != aEnd; aIt++) { if (aIt->getFc() <= rFc) { tEntries::const_iterator aItNext = aIt; aItNext++; if (aItNext != aEnd) { sal_uInt32 nOffset = rFc.get() - aIt->getFc().get(); sal_uInt32 nLength = aItNext->getCp() - aIt->getCp(); if (! aIt->isComplex()) nLength *= 2; if (nOffset < nLength) { aResult = aIt; break; } } } } } } return aResult; } Cp WW8PieceTableImpl::getFirstCp() const { Cp aResult; if (getCount() > 0) aResult = getCp(0); else throw ExceptionNotFound("WW8PieceTableImpl::getFirstCp"); return aResult; } Fc WW8PieceTableImpl::getFirstFc() const { Fc aResult; if (getCount() > 0) aResult = getFc(0); else throw ExceptionNotFound(" WW8PieceTableImpl::getFirstFc"); return aResult; } Cp WW8PieceTableImpl::getLastCp() const { Cp aResult; if (getCount() > 0) aResult = getCp(getCount() - 1); else throw ExceptionNotFound("WW8PieceTableImpl::getLastCp"); return aResult; } Fc WW8PieceTableImpl::getLastFc() const { Fc aResult; if (getCount() > 0) aResult = getFc(getCount() - 1); else throw ExceptionNotFound("WW8PieceTableImpl::getLastFc"); return aResult; } Cp WW8PieceTableImpl::getCp(sal_uInt32 nIndex) const { return mEntries[nIndex].getCp(); } Fc WW8PieceTableImpl::getFc(sal_uInt32 nIndex) const { return mEntries[nIndex].getFc(); } Cp WW8PieceTableImpl::fc2cp(const Fc & rFc) const { Cp cpResult; if (mEntries.size() > 0) { Fc aFc; if (rFc < mEntries.begin()->getFc()) aFc = mEntries.begin()->getFc(); else aFc = rFc; tEntries::const_iterator aIt = findFc(aFc); if (aIt != mEntries.end()) { cpResult = aIt->getCp() + (aFc - aIt->getFc()); } else throw ExceptionNotFound("WW8PieceTableImpl::fc2cp: " + aFc.toString()); } return cpResult; } Fc WW8PieceTableImpl::cp2fc(const Cp & rCp) const { Fc aResult; Cp2FcHashMap_t::iterator aItCp = mCp2FcCache.find(rCp); if (aItCp == mCp2FcCache.end()) { tEntries::const_iterator aIt = findCp(rCp); if (aIt != mEntries.end()) { aResult = aIt->getFc() + (rCp - aIt->getCp()); mCp2FcCache[rCp] = aResult; } else throw ExceptionNotFound ("WW8PieceTableImpl::cp2fc: " + rCp.toString()); } else aResult = mCp2FcCache[rCp]; return aResult; } bool WW8PieceTableImpl::isComplex(const Cp & rCp) const { bool bResult = false; tEntries::const_iterator aIt = findCp(rCp); if (aIt != mEntries.end()) bResult = aIt->isComplex(); return bResult; } bool WW8PieceTableImpl::isComplex(const Fc & rFc) const { bool bResult = false; tEntries::const_iterator aIt = findFc(rFc); if (aIt != mEntries.end()) bResult = aIt->isComplex(); return bResult; } CpAndFc WW8PieceTableImpl::createCpAndFc (const Cp & rCp, PropertyType eType) const { return CpAndFc(rCp, cp2fc(rCp), eType); } CpAndFc WW8PieceTableImpl::createCpAndFc (const Fc & rFc, PropertyType eType) const { return CpAndFc(fc2cp(rFc), rFc, eType); } void WW8PieceTableImpl::dump(ostream & o) const { o << "<piecetable>" << endl; copy(mEntries.begin(), mEntries.end(), ostream_iterator<CpAndFc>(o, "\n")); o << "</piecetable>" << endl; } }} <|endoftext|>
<commit_before>// Python includes #include <Python.h> // Stl includes #include <fstream> // Qt includes #include <QResource> #include <QMetaType> #include <QFile> #include <QDir> // hyperion util includes #include <utils/jsonschema/QJsonSchemaChecker.h> #include <utils/FileUtils.h> #include <utils/Components.h> // effect engine includes #include <effectengine/EffectEngine.h> #include "Effect.h" #include "HyperionConfig.h" EffectEngine::EffectEngine(Hyperion * hyperion, const QJsonObject & jsonEffectConfig) : _hyperion(hyperion) , _availableEffects() , _activeEffects() , _mainThreadState(nullptr) , _log(Logger::getInstance("EFFECTENGINE")) { Q_INIT_RESOURCE(EffectEngine); qRegisterMetaType<std::vector<ColorRgb>>("std::vector<ColorRgb>"); qRegisterMetaType<hyperion::Components>("hyperion::Components"); // connect the Hyperion channel clear feedback connect(_hyperion, SIGNAL(channelCleared(int)), this, SLOT(channelCleared(int))); connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared())); // read all effects const QJsonArray & paths = jsonEffectConfig["paths"].toArray(); const QJsonArray & disabledEfx = jsonEffectConfig["disable"].toArray(); QStringList efxPathList; efxPathList << ":/effects/"; QStringList disableList; QJsonArray::ConstIterator iterPaths = paths.begin(); QJsonArray::ConstIterator iterDisabledEfx = disabledEfx.begin(); for(; iterPaths != paths.end() and iterDisabledEfx != disabledEfx.end() ; ++iterPaths, ++iterDisabledEfx) { efxPathList << (*iterPaths).toString(); disableList << (*iterDisabledEfx).toString(); } std::map<QString, EffectDefinition> availableEffects; foreach (const QString & path, efxPathList ) { QDir directory(path); if (directory.exists()) { int efxCount = 0; QStringList filenames = directory.entryList(QStringList() << "*.json", QDir::Files, QDir::Name | QDir::IgnoreCase); foreach (const QString & filename, filenames) { EffectDefinition def; if (loadEffectDefinition(path, filename, def)) { if (availableEffects.find(def.name) != availableEffects.end()) { Info(_log, "effect overload effect '%s' is now taken from %s'", def.name.toUtf8().constData(), path.toUtf8().constData() ); } if ( disableList.contains(def.name) ) { Info(_log, "effect '%s' not loaded, because it is disabled in hyperion config", def.name.toUtf8().constData()); } else { availableEffects[def.name] = def; efxCount++; } } } Info(_log, "%d effects loaded from directory %s", efxCount, path.toUtf8().constData()); } } foreach(auto item, availableEffects) { _availableEffects.push_back(item.second); } if (_availableEffects.size() == 0) { Error(_log, "no effects found, check your effect directories"); } // initialize the python interpreter Debug(_log,"Initializing Python interpreter"); Effect::registerHyperionExtensionModule(); Py_InitializeEx(0); PyEval_InitThreads(); // Create the GIL _mainThreadState = PyEval_SaveThread(); } EffectEngine::~EffectEngine() { // clean up the Python interpreter Debug(_log, "Cleaning up Python interpreter"); PyEval_RestoreThread(_mainThreadState); Py_Finalize(); } const std::list<EffectDefinition> &EffectEngine::getEffects() const { return _availableEffects; } const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects() { _availableActiveEffects.clear(); for (Effect * effect : _activeEffects) { ActiveEffectDefinition activeEffectDefinition; activeEffectDefinition.script = effect->getScript(); activeEffectDefinition.name = effect->getName(); activeEffectDefinition.priority = effect->getPriority(); activeEffectDefinition.timeout = effect->getTimeout(); activeEffectDefinition.args = effect->getArgs(); _availableActiveEffects.push_back(activeEffectDefinition); } return _availableActiveEffects; } bool EffectEngine::loadEffectDefinition(const QString &path, const QString &effectConfigFile, EffectDefinition & effectDefinition) { Logger * log = Logger::getInstance("EFFECTENGINE"); QString fileName = path + QDir::separator() + effectConfigFile; QJsonParseError error; // ---------- Read the effect json config file ---------- QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { Error( log, "Effect file '%s' could not be loaded", fileName.toUtf8().constData()); return false; } QByteArray fileContent = file.readAll(); QJsonDocument configEffect = QJsonDocument::fromJson(fileContent, &error); if (error.error != QJsonParseError::NoError) { // report to the user the failure and their locations in the document. int errorLine(0), errorColumn(0); for( int i=0, count=qMin( error.offset,fileContent.size()); i<count; ++i ) { ++errorColumn; if(fileContent.at(i) == '\n' ) { errorColumn = 0; ++errorLine; } } Error( log, "Error while reading effect: '%s' at Line: '%i' , Column: %i", error.errorString().toUtf8().constData(), errorLine, errorColumn); } file.close(); // ---------- Read the effect json schema file ---------- Q_INIT_RESOURCE(EffectEngine); QFile schema(":effect-schema"); if (!schema.open(QIODevice::ReadOnly)) { Error( log, "Schema not found: %s", schema.errorString().toUtf8().constData()); return false; } QByteArray schemaContent = schema.readAll(); QJsonDocument configSchema = QJsonDocument::fromJson(schemaContent, &error); if (error.error != QJsonParseError::NoError) { // report to the user the failure and their locations in the document. int errorLine(0), errorColumn(0); for( int i=0, count=qMin( error.offset,schemaContent.size()); i<count; ++i ) { ++errorColumn; if(schemaContent.at(i) == '\n' ) { errorColumn = 0; ++errorLine; } } Error( log, "ERROR: Json schema wrong: '%s' at Line: '%i' , Column: %i", error.errorString().toUtf8().constData(), errorLine, errorColumn); } schema.close(); // ---------- validate effect config with effect schema ---------- QJsonSchemaChecker schemaChecker; schemaChecker.setSchema(configSchema.object()); if (!schemaChecker.validate(configEffect.object())) { const std::list<std::string> & errors = schemaChecker.getMessages(); foreach (const std::string & error, errors) { Error( log, "Error while checking '%s':%s", fileName.toUtf8().constData(), error.c_str()); } return false; } // ---------- setup the definition ---------- QJsonObject config = configEffect.object(); QString scriptName = config["script"].toString(); effectDefinition.name = config["name"].toString(); if (scriptName.isEmpty()) return false; if (scriptName.mid(0, 1) == ":" ) effectDefinition.script = ":/effects/"+scriptName.mid(1); else effectDefinition.script = path + QDir::separator().toLatin1() + scriptName; effectDefinition.args = config["args"].toObject(); return true; } int EffectEngine::runEffect(const QString &effectName, int priority, int timeout) { return runEffect(effectName, QJsonObject(), priority, timeout); } int EffectEngine::runEffect(const QString &effectName, const QJsonObject &args, int priority, int timeout) { Info( _log, "run effect %s on channel %d", effectName.toUtf8().constData(), priority); const EffectDefinition * effectDefinition = nullptr; for (const EffectDefinition & e : _availableEffects) { if (e.name == effectName) { effectDefinition = &e; break; } } if (effectDefinition == nullptr) { // no such effect Error(_log, "effect %s not found", effectName.toUtf8().constData()); return -1; } return runEffectScript(effectDefinition->script, effectName, args.isEmpty() ? effectDefinition->args : args, priority, timeout); } int EffectEngine::runEffectScript(const QString &script, const QString &name, const QJsonObject &args, int priority, int timeout) { // clear current effect on the channel channelCleared(priority); // create the effect Effect * effect = new Effect(_mainThreadState, priority, timeout, script, name, args); connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool,hyperion::Components)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool,hyperion::Components)), Qt::QueuedConnection); connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*))); _activeEffects.push_back(effect); // start the effect _hyperion->registerPriority("EFFECT: "+name.toStdString(), priority); effect->start(); return 0; } void EffectEngine::channelCleared(int priority) { for (Effect * effect : _activeEffects) { if (effect->getPriority() == priority) { effect->abort(); } } } void EffectEngine::allChannelsCleared() { for (Effect * effect : _activeEffects) { effect->abort(); } } void EffectEngine::effectFinished(Effect *effect) { if (!effect->isAbortRequested()) { // effect stopped by itself. Clear the channel _hyperion->clear(effect->getPriority()); } Info( _log, "effect finished"); for (auto effectIt = _activeEffects.begin(); effectIt != _activeEffects.end(); ++effectIt) { if (*effectIt == effect) { _activeEffects.erase(effectIt); break; } } // cleanup the effect effect->deleteLater(); _hyperion->unRegisterPriority("EFFECT: " + effect->getName().toStdString()); } <commit_msg>fix effect overlay not evaluated correctly<commit_after>// Python includes #include <Python.h> // Stl includes #include <fstream> // Qt includes #include <QResource> #include <QMetaType> #include <QFile> #include <QDir> // hyperion util includes #include <utils/jsonschema/QJsonSchemaChecker.h> #include <utils/FileUtils.h> #include <utils/Components.h> // effect engine includes #include <effectengine/EffectEngine.h> #include "Effect.h" #include "HyperionConfig.h" EffectEngine::EffectEngine(Hyperion * hyperion, const QJsonObject & jsonEffectConfig) : _hyperion(hyperion) , _availableEffects() , _activeEffects() , _mainThreadState(nullptr) , _log(Logger::getInstance("EFFECTENGINE")) { Q_INIT_RESOURCE(EffectEngine); qRegisterMetaType<std::vector<ColorRgb>>("std::vector<ColorRgb>"); qRegisterMetaType<hyperion::Components>("hyperion::Components"); // connect the Hyperion channel clear feedback connect(_hyperion, SIGNAL(channelCleared(int)), this, SLOT(channelCleared(int))); connect(_hyperion, SIGNAL(allChannelsCleared()), this, SLOT(allChannelsCleared())); // read all effects const QJsonArray & paths = jsonEffectConfig["paths"].toArray(); const QJsonArray & disabledEfx = jsonEffectConfig["disable"].toArray(); QStringList efxPathList; efxPathList << ":/effects/"; QStringList disableList; for(auto p : paths) { efxPathList << p.toString(); } for(auto efx : disabledEfx) { disableList << efx.toString(); } std::map<QString, EffectDefinition> availableEffects; foreach (const QString & path, efxPathList ) { QDir directory(path); if (directory.exists()) { int efxCount = 0; QStringList filenames = directory.entryList(QStringList() << "*.json", QDir::Files, QDir::Name | QDir::IgnoreCase); foreach (const QString & filename, filenames) { EffectDefinition def; if (loadEffectDefinition(path, filename, def)) { if (availableEffects.find(def.name) != availableEffects.end()) { Info(_log, "effect overload effect '%s' is now taken from %s'", def.name.toUtf8().constData(), path.toUtf8().constData() ); } if ( disableList.contains(def.name) ) { Info(_log, "effect '%s' not loaded, because it is disabled in hyperion config", def.name.toUtf8().constData()); } else { availableEffects[def.name] = def; efxCount++; } } } Info(_log, "%d effects loaded from directory %s", efxCount, path.toUtf8().constData()); } else { Warning(_log, "Effect path \"%s\" does not exist",path.toUtf8().constData() ); } } foreach(auto item, availableEffects) { _availableEffects.push_back(item.second); } if (_availableEffects.size() == 0) { Error(_log, "no effects found, check your effect directories"); } // initialize the python interpreter Debug(_log,"Initializing Python interpreter"); Effect::registerHyperionExtensionModule(); Py_InitializeEx(0); PyEval_InitThreads(); // Create the GIL _mainThreadState = PyEval_SaveThread(); } EffectEngine::~EffectEngine() { // clean up the Python interpreter Debug(_log, "Cleaning up Python interpreter"); PyEval_RestoreThread(_mainThreadState); Py_Finalize(); } const std::list<EffectDefinition> &EffectEngine::getEffects() const { return _availableEffects; } const std::list<ActiveEffectDefinition> &EffectEngine::getActiveEffects() { _availableActiveEffects.clear(); for (Effect * effect : _activeEffects) { ActiveEffectDefinition activeEffectDefinition; activeEffectDefinition.script = effect->getScript(); activeEffectDefinition.name = effect->getName(); activeEffectDefinition.priority = effect->getPriority(); activeEffectDefinition.timeout = effect->getTimeout(); activeEffectDefinition.args = effect->getArgs(); _availableActiveEffects.push_back(activeEffectDefinition); } return _availableActiveEffects; } bool EffectEngine::loadEffectDefinition(const QString &path, const QString &effectConfigFile, EffectDefinition & effectDefinition) { Logger * log = Logger::getInstance("EFFECTENGINE"); QString fileName = path + QDir::separator() + effectConfigFile; QJsonParseError error; // ---------- Read the effect json config file ---------- QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { Error( log, "Effect file '%s' could not be loaded", fileName.toUtf8().constData()); return false; } QByteArray fileContent = file.readAll(); QJsonDocument configEffect = QJsonDocument::fromJson(fileContent, &error); if (error.error != QJsonParseError::NoError) { // report to the user the failure and their locations in the document. int errorLine(0), errorColumn(0); for( int i=0, count=qMin( error.offset,fileContent.size()); i<count; ++i ) { ++errorColumn; if(fileContent.at(i) == '\n' ) { errorColumn = 0; ++errorLine; } } Error( log, "Error while reading effect: '%s' at Line: '%i' , Column: %i", error.errorString().toUtf8().constData(), errorLine, errorColumn); } file.close(); // ---------- Read the effect json schema file ---------- Q_INIT_RESOURCE(EffectEngine); QFile schema(":effect-schema"); if (!schema.open(QIODevice::ReadOnly)) { Error( log, "Schema not found: %s", schema.errorString().toUtf8().constData()); return false; } QByteArray schemaContent = schema.readAll(); QJsonDocument configSchema = QJsonDocument::fromJson(schemaContent, &error); if (error.error != QJsonParseError::NoError) { // report to the user the failure and their locations in the document. int errorLine(0), errorColumn(0); for( int i=0, count=qMin( error.offset,schemaContent.size()); i<count; ++i ) { ++errorColumn; if(schemaContent.at(i) == '\n' ) { errorColumn = 0; ++errorLine; } } Error( log, "ERROR: Json schema wrong: '%s' at Line: '%i' , Column: %i", error.errorString().toUtf8().constData(), errorLine, errorColumn); } schema.close(); // ---------- validate effect config with effect schema ---------- QJsonSchemaChecker schemaChecker; schemaChecker.setSchema(configSchema.object()); if (!schemaChecker.validate(configEffect.object())) { const std::list<std::string> & errors = schemaChecker.getMessages(); foreach (const std::string & error, errors) { Error( log, "Error while checking '%s':%s", fileName.toUtf8().constData(), error.c_str()); } return false; } // ---------- setup the definition ---------- QJsonObject config = configEffect.object(); QString scriptName = config["script"].toString(); effectDefinition.name = config["name"].toString(); if (scriptName.isEmpty()) return false; if (scriptName.mid(0, 1) == ":" ) effectDefinition.script = ":/effects/"+scriptName.mid(1); else effectDefinition.script = path + QDir::separator().toLatin1() + scriptName; effectDefinition.args = config["args"].toObject(); return true; } int EffectEngine::runEffect(const QString &effectName, int priority, int timeout) { return runEffect(effectName, QJsonObject(), priority, timeout); } int EffectEngine::runEffect(const QString &effectName, const QJsonObject &args, int priority, int timeout) { Info( _log, "run effect %s on channel %d", effectName.toUtf8().constData(), priority); const EffectDefinition * effectDefinition = nullptr; for (const EffectDefinition & e : _availableEffects) { if (e.name == effectName) { effectDefinition = &e; break; } } if (effectDefinition == nullptr) { // no such effect Error(_log, "effect %s not found", effectName.toUtf8().constData()); return -1; } return runEffectScript(effectDefinition->script, effectName, args.isEmpty() ? effectDefinition->args : args, priority, timeout); } int EffectEngine::runEffectScript(const QString &script, const QString &name, const QJsonObject &args, int priority, int timeout) { // clear current effect on the channel channelCleared(priority); // create the effect Effect * effect = new Effect(_mainThreadState, priority, timeout, script, name, args); connect(effect, SIGNAL(setColors(int,std::vector<ColorRgb>,int,bool,hyperion::Components)), _hyperion, SLOT(setColors(int,std::vector<ColorRgb>,int,bool,hyperion::Components)), Qt::QueuedConnection); connect(effect, SIGNAL(effectFinished(Effect*)), this, SLOT(effectFinished(Effect*))); _activeEffects.push_back(effect); // start the effect _hyperion->registerPriority("EFFECT: "+name.toStdString(), priority); effect->start(); return 0; } void EffectEngine::channelCleared(int priority) { for (Effect * effect : _activeEffects) { if (effect->getPriority() == priority) { effect->abort(); } } } void EffectEngine::allChannelsCleared() { for (Effect * effect : _activeEffects) { effect->abort(); } } void EffectEngine::effectFinished(Effect *effect) { if (!effect->isAbortRequested()) { // effect stopped by itself. Clear the channel _hyperion->clear(effect->getPriority()); } Info( _log, "effect finished"); for (auto effectIt = _activeEffects.begin(); effectIt != _activeEffects.end(); ++effectIt) { if (*effectIt == effect) { _activeEffects.erase(effectIt); break; } } // cleanup the effect effect->deleteLater(); _hyperion->unRegisterPriority("EFFECT: " + effect->getName().toStdString()); } <|endoftext|>
<commit_before><commit_msg>-Werror,-Wunused-private-field (Clang towards 3.2)<commit_after><|endoftext|>
<commit_before>/* * This file is part of the statismo library. * * Author: Marcel Luethi (marcel.luethi@unibas.ch) * * Copyright (c) 2011 University of Basel * All rights reserved. * * Statismo is licensed under the BSD licence (3 clause) license */ #include "LowRankGPModelBuilder.h" #include "StatisticalModel.h" #include "vtkPolyDataReader.h" #include "vtkStandardMeshRepresenter.h" #include "Kernels.h" #include "KernelCombinators.h" #include <iostream> #include <memory> using namespace statismo; /* * We use a sum of gaussian kernels as our main model. */ class MultiscaleGaussianKernel: public MatrixValuedKernel<vtkPoint> { public: MultiscaleGaussianKernel(float baseWidth, float baseScale, unsigned nLevels) : m_baseWidth(baseWidth), m_baseScale(baseScale), m_nLevels(nLevels), MatrixValuedKernel<vtkPoint>(3) { } inline MatrixType operator()(const vtkPoint& x, const vtkPoint& y) const { VectorType r(3); r << x[0] - y[0], x[1] - y[1], x[2] - y[2]; const float minusRDotR = - r.dot(r); float kernelValue = 0.; for (unsigned l = 1 ; l <= m_nLevels; ++l) { const float scaleOnLevel = m_baseScale / static_cast< float >( l ); const float widthOnLevel = m_baseWidth / static_cast< float >( l ); kernelValue += scaleOnLevel * std::exp( minusRDotR / (widthOnLevel * widthOnLevel)); } return statismo::MatrixType::Identity(3,3) * kernelValue; } std::string GetKernelInfo() const { std::ostringstream os; os << "Multiscale GaussianKernel"; return os.str(); } private: float m_baseWidth; float m_baseScale; unsigned m_nLevels; }; // load a mesh vtkPolyData* loadVTKPolyData(const std::string& filename) { vtkPolyDataReader* reader = vtkPolyDataReader::New(); reader->SetFileName(filename.c_str()); reader->Update(); vtkPolyData* pd = vtkPolyData::New(); pd->ShallowCopy(reader->GetOutput()); reader->Delete(); return pd; } // compute the center of mass for the given mesh vtkPoint centerOfMass(const vtkPolyData* _pd) { // vtk is not const-correct, but we will not mutate pd here; vtkPolyData* pd = const_cast<vtkPolyData*>(_pd); vtkIdType numPoints = pd->GetNumberOfPoints(); vtkPoint centerOfMass(0.0, 0.0, 0.0); for (vtkIdType i = 0; i < numPoints; ++i) { double *ithPoint = pd->GetPoint(i); for (unsigned d = 0; d < 3; ++d) { centerOfMass[d] += ithPoint[d]; } } double V = 1.0 / static_cast<double>(numPoints); for (unsigned d = 0; d < 3; ++d) { centerOfMass[d] * V; } return centerOfMass; } // As an example of a tempering function, we use a function which is more smooth for points whose // x-component is smaller than the x-component of the center of mass. To achieve a smooth transition between the areas, we use a sigmoid function. // The variable a controls how fast the value of the tempering function changes from 0 to 1. struct MyTemperingFunction : public TemperingFunction<vtkPoint> { MyTemperingFunction(const vtkPoint& centerOfMass) : m_centerOfMass(centerOfMass) {} static const double a; double operator() (const vtkPoint& pt) const { double xDiffToCenter = m_centerOfMass[0] - pt[0]; return (1.0 / ( 1.0 + std::exp(-xDiffToCenter * a)) + 1.0) ; } private: vtkPoint m_centerOfMass; }; const double MyTemperingFunction::a = 0.5; // // Computes a multi-scale gaussian model and uses spatial tempering to make the smoothness spatially varying. // // For mathematical details of this procedure, refer to the paper: // T. Gerig, K. Shahim, M. Reyes, T. Vetter, M. Luethi, Spatially-varying registration using Gaussian Processes. // int main(int argc, char** argv) { if (argc < 7) { std::cerr << "Usage " << argv[0] << " referenceMesh baseKernelWidth baseScale numLevels numberOfComponents outputmodelName" << std::endl; return EXIT_FAILURE; } std::string refFilename(argv[1]); double baseKernelWidth = std::atof(argv[2]); double baseScale = std::atof(argv[3]); unsigned numLevels = std::atoi(argv[4]); int numberOfComponents = std::atoi(argv[5]); std::string outputModelFilename(argv[6]); // All the statismo classes have to be parameterized with the RepresenterType. typedef vtkStandardMeshRepresenter RepresenterType; typedef LowRankGPModelBuilder<vtkPolyData> ModelBuilderType; typedef StatisticalModel<vtkPolyData> StatisticalModelType; typedef MultiscaleGaussianKernel GaussianKernelType; typedef MatrixValuedKernel<vtkPoint> MatrixValuedKernelType; try { vtkPolyData* referenceMesh = loadVTKPolyData(refFilename); vtkStandardMeshRepresenter* representer = vtkStandardMeshRepresenter::Create(referenceMesh); MultiscaleGaussianKernel gk = MultiscaleGaussianKernel(baseKernelWidth, baseScale, numLevels); MyTemperingFunction temperingFun(centerOfMass(referenceMesh)); const MatrixValuedKernelType& temperedKernel = SpatiallyVaryingKernel<RepresenterType::DatasetType>(representer, gk, temperingFun , numberOfComponents, numberOfComponents * 2, true); // We create a new model using the combined kernel. The new model will be more flexible than the original statistical model. ModelBuilderType* modelBuilder = ModelBuilderType::Create(representer); StatisticalModelType* newModel = modelBuilder->BuildNewModel(referenceMesh, temperedKernel, numberOfComponents); // Once we have built the model, we can save it to disk. newModel->Save(outputModelFilename); std::cout << "Successfully saved shape model as " << outputModelFilename << std::endl; referenceMesh->Delete(); representer->Delete(); modelBuilder->Delete(); newModel->Delete(); } catch (StatisticalModelException& e) { std::cerr << "Exception occured while building the shape model" << std::endl; std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Avoid creation of temporary object when creating SpatiallyVaryingKernel. Fixes #124.<commit_after>/* * This file is part of the statismo library. * * Author: Marcel Luethi (marcel.luethi@unibas.ch) * * Copyright (c) 2011 University of Basel * All rights reserved. * * Statismo is licensed under the BSD licence (3 clause) license */ #include "LowRankGPModelBuilder.h" #include "StatisticalModel.h" #include "vtkPolyDataReader.h" #include "vtkStandardMeshRepresenter.h" #include "Kernels.h" #include "KernelCombinators.h" #include <iostream> #include <memory> using namespace statismo; /* * We use a sum of gaussian kernels as our main model. */ class MultiscaleGaussianKernel: public MatrixValuedKernel<vtkPoint> { public: MultiscaleGaussianKernel(float baseWidth, float baseScale, unsigned nLevels) : m_baseWidth(baseWidth), m_baseScale(baseScale), m_nLevels(nLevels), MatrixValuedKernel<vtkPoint>(3) { } inline MatrixType operator()(const vtkPoint& x, const vtkPoint& y) const { VectorType r(3); r << x[0] - y[0], x[1] - y[1], x[2] - y[2]; const float minusRDotR = - r.dot(r); float kernelValue = 0.; for (unsigned l = 1 ; l <= m_nLevels; ++l) { const float scaleOnLevel = m_baseScale / static_cast< float >( l ); const float widthOnLevel = m_baseWidth / static_cast< float >( l ); kernelValue += scaleOnLevel * std::exp( minusRDotR / (widthOnLevel * widthOnLevel)); } return statismo::MatrixType::Identity(3,3) * kernelValue; } std::string GetKernelInfo() const { std::ostringstream os; os << "Multiscale GaussianKernel"; return os.str(); } private: float m_baseWidth; float m_baseScale; unsigned m_nLevels; }; // load a mesh vtkPolyData* loadVTKPolyData(const std::string& filename) { vtkPolyDataReader* reader = vtkPolyDataReader::New(); reader->SetFileName(filename.c_str()); reader->Update(); vtkPolyData* pd = vtkPolyData::New(); pd->ShallowCopy(reader->GetOutput()); reader->Delete(); return pd; } // compute the center of mass for the given mesh vtkPoint centerOfMass(const vtkPolyData* _pd) { // vtk is not const-correct, but we will not mutate pd here; vtkPolyData* pd = const_cast<vtkPolyData*>(_pd); vtkIdType numPoints = pd->GetNumberOfPoints(); vtkPoint centerOfMass(0.0, 0.0, 0.0); for (vtkIdType i = 0; i < numPoints; ++i) { double *ithPoint = pd->GetPoint(i); for (unsigned d = 0; d < 3; ++d) { centerOfMass[d] += ithPoint[d]; } } double V = 1.0 / static_cast<double>(numPoints); for (unsigned d = 0; d < 3; ++d) { centerOfMass[d] * V; } return centerOfMass; } // As an example of a tempering function, we use a function which is more smooth for points whose // x-component is smaller than the x-component of the center of mass. To achieve a smooth transition between the areas, we use a sigmoid function. // The variable a controls how fast the value of the tempering function changes from 0 to 1. struct MyTemperingFunction : public TemperingFunction<vtkPoint> { MyTemperingFunction(const vtkPoint& centerOfMass) : m_centerOfMass(centerOfMass) {} static const double a; double operator() (const vtkPoint& pt) const { double xDiffToCenter = m_centerOfMass[0] - pt[0]; return (1.0 / ( 1.0 + std::exp(-xDiffToCenter * a)) + 1.0) ; } private: vtkPoint m_centerOfMass; }; const double MyTemperingFunction::a = 0.5; // // Computes a multi-scale gaussian model and uses spatial tempering to make the smoothness spatially varying. // // For mathematical details of this procedure, refer to the paper: // T. Gerig, K. Shahim, M. Reyes, T. Vetter, M. Luethi, Spatially-varying registration using Gaussian Processes. // int main(int argc, char** argv) { if (argc < 7) { std::cerr << "Usage " << argv[0] << " referenceMesh baseKernelWidth baseScale numLevels numberOfComponents outputmodelName" << std::endl; return EXIT_FAILURE; } std::string refFilename(argv[1]); double baseKernelWidth = std::atof(argv[2]); double baseScale = std::atof(argv[3]); unsigned numLevels = std::atoi(argv[4]); int numberOfComponents = std::atoi(argv[5]); std::string outputModelFilename(argv[6]); // All the statismo classes have to be parameterized with the RepresenterType. typedef vtkStandardMeshRepresenter RepresenterType; typedef LowRankGPModelBuilder<vtkPolyData> ModelBuilderType; typedef StatisticalModel<vtkPolyData> StatisticalModelType; typedef MultiscaleGaussianKernel GaussianKernelType; typedef MatrixValuedKernel<vtkPoint> MatrixValuedKernelType; try { vtkPolyData* referenceMesh = loadVTKPolyData(refFilename); vtkStandardMeshRepresenter* representer = vtkStandardMeshRepresenter::Create(referenceMesh); MultiscaleGaussianKernel gk = MultiscaleGaussianKernel(baseKernelWidth, baseScale, numLevels); MyTemperingFunction temperingFun(centerOfMass(referenceMesh)); SpatiallyVaryingKernel<RepresenterType::DatasetType> temperedKernel(representer, gk, temperingFun , numberOfComponents, numberOfComponents * 2, true); // We create a new model using the combined kernel. The new model will be more flexible than the original statistical model. ModelBuilderType* modelBuilder = ModelBuilderType::Create(representer); StatisticalModelType* newModel = modelBuilder->BuildNewModel(referenceMesh, temperedKernel, numberOfComponents); // Once we have built the model, we can save it to disk. newModel->Save(outputModelFilename); std::cout << "Successfully saved shape model as " << outputModelFilename << std::endl; referenceMesh->Delete(); representer->Delete(); modelBuilder->Delete(); newModel->Delete(); } catch (StatisticalModelException& e) { std::cerr << "Exception occured while building the shape model" << std::endl; std::cerr << e.what() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <caf/ref_counted.hpp> #include "vast/fwd.hpp" #include "vast/view.hpp" namespace vast { /// Enables incremental construction of a table slice. /// @relates table_slice class table_slice_builder : public caf::ref_counted { public: // -- constructors, destructors, and assignment operators -------------------- table_slice_builder(record_type layout); ~table_slice_builder(); // -- properties ------------------------------------------------------------- /// Calls `add(x)` as long as `x` is not a vector, otherwise calls `add(y)` /// for each `y` in `x`. bool recursive_add(const data& x, const type& t); /// Adds data to the builder. /// @param x The data to add. /// @returns `true` on success. virtual bool add(data_view x) = 0; /// Constructs a table_slice from the currently accumulated state. After /// calling this function, implementations must reset their internal state /// such that subsequent calls to add will restart with a new table_slice. /// @returns A table slice from the accumulated calls to add or `nullptr` on /// failure. virtual table_slice_ptr finish() = 0; /// @returns the current number of rows in the table slice. virtual size_t rows() const noexcept = 0; /// Allows the table slice builder to allocate sufficient storage for up to /// `num_rows` rows. virtual void reserve(size_t num_rows); const record_type& layout() const noexcept { return layout_; } private: record_type layout_; }; /// @relates table_slice_builder using table_slice_builder_ptr = caf::intrusive_ptr<table_slice_builder>; } // namespace vast <commit_msg>Add missing documentation<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <caf/ref_counted.hpp> #include "vast/fwd.hpp" #include "vast/view.hpp" namespace vast { /// Enables incremental construction of a table slice. /// @relates table_slice class table_slice_builder : public caf::ref_counted { public: // -- constructors, destructors, and assignment operators -------------------- table_slice_builder(record_type layout); ~table_slice_builder(); // -- properties ------------------------------------------------------------- /// Calls `add(x)` as long as `x` is not a vector, otherwise calls `add(y)` /// for each `y` in `x`. bool recursive_add(const data& x, const type& t); /// Adds data to the builder. /// @param x The data to add. /// @returns `true` on success. virtual bool add(data_view x) = 0; /// Constructs a table_slice from the currently accumulated state. After /// calling this function, implementations must reset their internal state /// such that subsequent calls to add will restart with a new table_slice. /// @returns A table slice from the accumulated calls to add or `nullptr` on /// failure. virtual table_slice_ptr finish() = 0; /// @returns the current number of rows in the table slice. virtual size_t rows() const noexcept = 0; /// Allows the table slice builder to allocate sufficient storage for up to /// `num_rows` rows. virtual void reserve(size_t num_rows); /// @returns the table layout. const record_type& layout() const noexcept { return layout_; } private: record_type layout_; }; /// @relates table_slice_builder using table_slice_builder_ptr = caf::intrusive_ptr<table_slice_builder>; } // namespace vast <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2015-2019 Ingo Wald // // // // 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. // // ======================================================================== // // pbrt_parser #include "pbrtParser/semantic/Scene.h" // ospcommon #include "ospcommon/common.h" // stl #include <iostream> #include <vector> #include <sstream> #include <set> namespace pbrt { namespace semantic { using std::cout; using std::endl; bool endsWith(const std::string &s, const std::string &suffix) { return s.substr(s.size()-suffix.size(),suffix.size()) == suffix; } struct PBRTInfo { PBRTInfo(Scene::SP scene) { traverse(scene->world); numObjects.print("objects"); numShapes.print("shapes"); numTriangles.print("triangles"); numQuads.print("quads"); numDisks.print("disks"); numSpheres.print("spheres"); numCurves.print("curves"); numCurveSegments.print("curve segments"); numLights.print("lights"); std::cout << "total num materials " << usedMaterials.size() << std::endl; } void traverse(Object::SP object) { const bool firstTime = (alreadyTraversed.find(object) == alreadyTraversed.end()); alreadyTraversed.insert(object); numObjects.add(firstTime,1); // numLights.add(firstTime,object->lightSources.size()); // numVolumes.add(firstTime,object->volumes.size()); numShapes.add(firstTime,object->shapes.size()); for (auto geom : object->shapes) { usedMaterials.insert(geom->material); if (TriangleMesh::SP mesh=std::dynamic_pointer_cast<TriangleMesh>(geom)){ numTriangles.add(firstTime,mesh->index.size()); } else if (QuadMesh::SP mesh=std::dynamic_pointer_cast<QuadMesh>(geom)){ numQuads.add(firstTime,mesh->index.size()); } else if (Sphere::SP sphere=std::dynamic_pointer_cast<Sphere>(geom)){ numSpheres.add(firstTime,1); } else if (Disk::SP disk=std::dynamic_pointer_cast<Disk>(geom)){ numDisks.add(firstTime,1); } else if (Curve::SP curves=std::dynamic_pointer_cast<Curve>(geom)){ numCurves.add(firstTime,1); } else std::cout << "un-handled geometry type : " << geom->toString() << std::endl; } numInstances.add(firstTime,object->instances.size()); for (auto inst : object->instances) { traverse(inst->object); } } std::set<Object::SP> alreadyTraversed; struct Counter { void print(const std::string &name) { std::cout << "number of " << name << std::endl; std::cout << " - unique : " << ospcommon::prettyNumber(unique) << std::endl; std::cout << " - instanced : " << ospcommon::prettyNumber(instanced) << std::endl; } void add(bool firstTime, size_t N) { instanced += N; if (firstTime) unique += N; } size_t unique = 0; size_t instanced = 0; }; Counter numInstances, numTriangles, numQuads, numSpheres, numDisks, numObjects, numVertices, numCurves, numCurveSegments, numShapes, numLights, numVolumes; std::set<Material::SP> usedMaterials; }; void pbfInfo(int ac, char **av) { std::string fileName; bool parseOnly = false; for (int i=1;i<ac;i++) { const std::string arg = av[i]; if (arg == "--lint" || arg == "-lint") { parseOnly = true; } else if (arg[0] == '-') { throw std::runtime_error("invalid argument '"+arg+"'"); } else { fileName = arg; } } std::cout << "-------------------------------------------------------" << std::endl; std::cout << "pbrtinfo - printing info on pbrt file ..." << std::endl; std::cout << "-------------------------------------------------------" << std::endl; std::shared_ptr<Scene> scene; try { if (endsWith(fileName,".pbsf") || endsWith(fileName,".pbrt")) scene = importPBRT(fileName); else if (endsWith(fileName,".pbf")) // scene = importPBRT(fileName); scene = Scene::loadFrom(fileName); else throw std::runtime_error("un-recognized input file extension"); std::cout << " => yay! parsing successful..." << std::endl; if (parseOnly) exit(0); PBRTInfo info(scene); } catch (std::runtime_error e) { std::cerr << "**** ERROR IN PARSING ****" << std::endl << e.what() << std::endl; std::cerr << "(this means that either there's something wrong with that PBRT file, or that the parser can't handle it)" << std::endl; exit(1); } } extern "C" int main(int ac, char **av) { pbfInfo(ac,av); return 0; } } // ::pbrt::semantic } // ::pbrt <commit_msg>add bound printing to test<commit_after>// ======================================================================== // // Copyright 2015-2019 Ingo Wald // // // // 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. // // ======================================================================== // // ospcommon, which we use for a vector class #include "ospcommon/vec.h" #include "ospcommon/AffineSpace.h" // pbrt-parser #define PBRT_PARSER_VECTYPE_NAMESPACE ospcommon #include "pbrtParser/semantic/Scene.h" // stl #include <iostream> #include <vector> #include <sstream> #include <set> namespace pbrt { namespace semantic { using std::cout; using std::endl; bool endsWith(const std::string &s, const std::string &suffix) { return s.substr(s.size()-suffix.size(),suffix.size()) == suffix; } struct PBRTInfo { PBRTInfo(Scene::SP scene) { traverse(scene->world); numObjects.print("objects"); numShapes.print("shapes"); numTriangles.print("triangles"); numQuads.print("quads"); numDisks.print("disks"); numSpheres.print("spheres"); numCurves.print("curves"); numCurveSegments.print("curve segments"); numLights.print("lights"); std::cout << "total num materials " << usedMaterials.size() << std::endl; std::cout << "scene bounds " << scene->getBounds() << std::endl; } void traverse(Object::SP object) { const bool firstTime = (alreadyTraversed.find(object) == alreadyTraversed.end()); alreadyTraversed.insert(object); numObjects.add(firstTime,1); // numLights.add(firstTime,object->lightSources.size()); // numVolumes.add(firstTime,object->volumes.size()); numShapes.add(firstTime,object->shapes.size()); for (auto geom : object->shapes) { usedMaterials.insert(geom->material); if (TriangleMesh::SP mesh=std::dynamic_pointer_cast<TriangleMesh>(geom)){ numTriangles.add(firstTime,mesh->index.size()); } else if (QuadMesh::SP mesh=std::dynamic_pointer_cast<QuadMesh>(geom)){ numQuads.add(firstTime,mesh->index.size()); } else if (Sphere::SP sphere=std::dynamic_pointer_cast<Sphere>(geom)){ numSpheres.add(firstTime,1); } else if (Disk::SP disk=std::dynamic_pointer_cast<Disk>(geom)){ numDisks.add(firstTime,1); } else if (Curve::SP curves=std::dynamic_pointer_cast<Curve>(geom)){ numCurves.add(firstTime,1); } else std::cout << "un-handled geometry type : " << geom->toString() << std::endl; } numInstances.add(firstTime,object->instances.size()); for (auto inst : object->instances) { traverse(inst->object); } } std::set<Object::SP> alreadyTraversed; struct Counter { void print(const std::string &name) { std::cout << "number of " << name << std::endl; std::cout << " - unique : " << ospcommon::prettyNumber(unique) << std::endl; std::cout << " - instanced : " << ospcommon::prettyNumber(instanced) << std::endl; } void add(bool firstTime, size_t N) { instanced += N; if (firstTime) unique += N; } size_t unique = 0; size_t instanced = 0; }; Counter numInstances, numTriangles, numQuads, numSpheres, numDisks, numObjects, numVertices, numCurves, numCurveSegments, numShapes, numLights, numVolumes; std::set<Material::SP> usedMaterials; }; void pbfInfo(int ac, char **av) { std::string fileName; bool parseOnly = false; for (int i=1;i<ac;i++) { const std::string arg = av[i]; if (arg == "--lint" || arg == "-lint") { parseOnly = true; } else if (arg[0] == '-') { throw std::runtime_error("invalid argument '"+arg+"'"); } else { fileName = arg; } } std::cout << "-------------------------------------------------------" << std::endl; std::cout << "pbrtinfo - printing info on pbrt file ..." << std::endl; std::cout << "-------------------------------------------------------" << std::endl; std::shared_ptr<Scene> scene; try { if (endsWith(fileName,".pbsf") || endsWith(fileName,".pbrt")) scene = importPBRT(fileName); else if (endsWith(fileName,".pbf")) // scene = importPBRT(fileName); scene = Scene::loadFrom(fileName); else throw std::runtime_error("un-recognized input file extension"); std::cout << " => yay! parsing successful..." << std::endl; if (parseOnly) exit(0); PBRTInfo info(scene); } catch (std::runtime_error e) { std::cerr << "**** ERROR IN PARSING ****" << std::endl << e.what() << std::endl; std::cerr << "(this means that either there's something wrong with that PBRT file, or that the parser can't handle it)" << std::endl; exit(1); } } extern "C" int main(int ac, char **av) { pbfInfo(ac,av); return 0; } } // ::pbrt::semantic } // ::pbrt <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2012, Howard Butler (hobu.inc@gmail.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 <iostream> #include <boost/scoped_ptr.hpp> #include <pdal/Stage.hpp> #include <pdal/StageIterator.hpp> #include <pdal/FileUtils.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/filters/Index.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/json_parser.hpp> #include "AppSupport.hpp" #include "Application.hpp" #include <cstdarg> #include <map> #include <vector> using namespace pdal; class Point { public: double x; double y; double z; boost::uint64_t id; }; class PcEqual : public Application { public: PcEqual(int argc, char* argv[]); int execute(); // overrride private: void addSwitches(); // overrride void validateSwitches(); // overrride void readPoints(std::vector<Point>* points, boost::scoped_ptr<StageSequentialIterator>& iter, PointBuffer& data); std::string m_sourceFile; std::string m_candidateFile; std::string m_wkt; pdal::Options m_options; }; PcEqual::PcEqual(int argc, char* argv[]) : Application(argc, argv, "pcquery") , m_sourceFile("") , m_candidateFile("") { return; } void PcEqual::validateSwitches() { return; } void PcEqual::addSwitches() { namespace po = boost::program_options; po::options_description* file_options = new po::options_description("file options"); file_options->add_options() ("source", po::value<std::string>(&m_sourceFile), "source file name") ("candidate", po::value<std::string>(&m_candidateFile), "candidate file name") ; addSwitchSet(file_options); po::options_description* processing_options = new po::options_description("processing options"); processing_options->add_options() ; addSwitchSet(processing_options); addPositionalSwitch("source", 1); addPositionalSwitch("candidate", 2); return; } void PcEqual::readPoints( std::vector<Point>* points, boost::scoped_ptr<StageSequentialIterator>& iter, PointBuffer& data) { const Schema& schema = data.getSchema(); Dimension const& dimX = schema.getDimension("X"); Dimension const& dimY = schema.getDimension("Y"); Dimension const& dimZ = schema.getDimension("Z"); boost::uint64_t id = 0; while (!iter->atEnd()) { const boost::uint32_t numRead = iter->read(data); for (boost::uint32_t i = 0; i < data.getNumPoints(); ++i) { boost::int32_t xi = data.getField<boost::uint32_t>(dimX, i); boost::int32_t yi = data.getField<boost::uint32_t>(dimY, i); boost::int32_t zi = data.getField<boost::uint32_t>(dimZ, i); Point p; p.x = dimX.applyScaling<boost::int32_t>(xi); p.y = dimY.applyScaling<boost::int32_t>(yi); p.z = dimZ.applyScaling<boost::int32_t>(zi); p.id = id; id += 1; points->push_back(p); } } } int PcEqual::execute() { Options sourceOptions; { sourceOptions.add<std::string>("filename", m_sourceFile); sourceOptions.add<bool>("debug", isDebug()); sourceOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } Stage* source = AppSupport::makeReader(sourceOptions); source->initialize(); std::vector<Point>* source_points = new std::vector<Point>(); source_points->reserve(source->getNumPoints()); boost::uint32_t chunkSize = m_chunkSize != 0 ? m_chunkSize : 1048576; PointBuffer source_data(source->getSchema(), chunkSize); boost::scoped_ptr<StageSequentialIterator> reader_iter(source->createSequentialIterator(source_data)); readPoints(source_points, reader_iter, source_data); std::cout << "read " << source_points->size() << " source points" << std::endl; delete source; Options candidateOptions; { candidateOptions.add<std::string>("filename", m_candidateFile); candidateOptions.add<bool>("debug", isDebug()); candidateOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } Stage* candidate = AppSupport::makeReader(candidateOptions); pdal::filters::Index* index_filter = new pdal::filters::Index(*candidate, candidateOptions); index_filter->initialize(); std::vector<Point>* candidate_points = new std::vector<Point>(); candidate_points->reserve(candidate->getNumPoints()); PointBuffer candidate_data(candidate->getSchema(), chunkSize); boost::scoped_ptr<StageSequentialIterator> index_iter(candidate->createSequentialIterator(candidate_data)); readPoints(candidate_points, index_iter, candidate_data); std::cout << "read " << candidate_points->size() << " candidate points" << std::endl; delete index_filter; std::cout << std::endl; if (candidate_points->size() != source_points->size()) { throw app_runtime_error("Source and candidate files do not have the same point count!"); } delete candidate_points; delete source_points; return 0; } int main(int argc, char* argv[]) { PcEqual app(argc, argv); return app.run(); } <commit_msg>pcequal now working -- outputs a simple delta{X|Y|Z} file per-point.<commit_after>/****************************************************************************** * Copyright (c) 2012, Howard Butler (hobu.inc@gmail.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 <iostream> #include <boost/scoped_ptr.hpp> #include <pdal/Stage.hpp> #include <pdal/StageIterator.hpp> #include <pdal/FileUtils.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/filters/Index.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/property_tree/json_parser.hpp> #include "AppSupport.hpp" #include "Application.hpp" #include <cstdarg> #include <map> #include <vector> using namespace pdal; class Point { public: double x; double y; double z; boost::uint64_t id; bool equal(Point const& other) { return (Utils::compare_distance(x, other.x) && Utils::compare_distance(y, other.y) && Utils::compare_distance(z, other.z)); } bool operator==(Point const& other) { return equal(other); } bool operator!=(Point const& other) { return !equal(other); } }; class PcEqual : public Application { public: PcEqual(int argc, char* argv[]); int execute(); // overrride private: void addSwitches(); // overrride void validateSwitches(); // overrride void readPoints(std::vector<Point>* points, StageSequentialIterator* iter, PointBuffer& data); std::string m_sourceFile; std::string m_candidateFile; std::string m_wkt; pdal::Options m_options; }; PcEqual::PcEqual(int argc, char* argv[]) : Application(argc, argv, "pcquery") , m_sourceFile("") , m_candidateFile("") { return; } void PcEqual::validateSwitches() { if( m_chunkSize == 0) m_chunkSize = 1048576; return; } void PcEqual::addSwitches() { namespace po = boost::program_options; po::options_description* file_options = new po::options_description("file options"); file_options->add_options() ("source", po::value<std::string>(&m_sourceFile), "source file name") ("candidate", po::value<std::string>(&m_candidateFile), "candidate file name") ; addSwitchSet(file_options); po::options_description* processing_options = new po::options_description("processing options"); processing_options->add_options() ; addSwitchSet(processing_options); addPositionalSwitch("source", 1); addPositionalSwitch("candidate", 2); return; } void PcEqual::readPoints( std::vector<Point>* points, StageSequentialIterator* iter, PointBuffer& data) { const Schema& schema = data.getSchema(); Dimension const& dimX = schema.getDimension("X"); Dimension const& dimY = schema.getDimension("Y"); Dimension const& dimZ = schema.getDimension("Z"); boost::uint64_t id = 0; while (!iter->atEnd()) { const boost::uint32_t numRead = iter->read(data); for (boost::uint32_t i = 0; i < data.getNumPoints(); ++i) { boost::int32_t xi = data.getField<boost::int32_t>(dimX, i); boost::int32_t yi = data.getField<boost::int32_t>(dimY, i); boost::int32_t zi = data.getField<boost::int32_t>(dimZ, i); Point p; p.x = dimX.applyScaling<boost::int32_t>(xi); p.y = dimY.applyScaling<boost::int32_t>(yi); p.z = dimZ.applyScaling<boost::int32_t>(zi); p.id = id; id += 1; points->push_back(p); } } } std::ostream& writeHeader(std::ostream& strm) { strm << "\"ID\", \"DeltaX\", \"DeltaY\", \"DeltaZ\"" << std::endl; return strm; } int PcEqual::execute() { std::vector<Point>* source_points = new std::vector<Point>(); std::vector<Point>* candidate_points = new std::vector<Point>(); { Options sourceOptions; { sourceOptions.add<std::string>("filename", m_sourceFile); sourceOptions.add<bool>("debug", isDebug()); sourceOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } Stage* source = AppSupport::makeReader(sourceOptions); source->initialize(); source_points->reserve(source->getNumPoints()); PointBuffer source_data(source->getSchema(), m_chunkSize); StageSequentialIterator* reader_iter = source->createSequentialIterator(source_data); readPoints(source_points, reader_iter, source_data); delete reader_iter; delete source; } Options candidateOptions; { candidateOptions.add<std::string>("filename", m_candidateFile); candidateOptions.add<bool>("debug", isDebug()); candidateOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } Stage* candidate = AppSupport::makeReader(candidateOptions); pdal::filters::Index* index_filter = new pdal::filters::Index(*candidate, candidateOptions); index_filter->initialize(); candidate_points->reserve(candidate->getNumPoints()); PointBuffer candidate_data(candidate->getSchema(), m_chunkSize); StageSequentialIterator* index_iter = index_filter->createSequentialIterator(candidate_data); readPoints(candidate_points, index_iter, candidate_data); if (candidate_points->size() != source_points->size()) { throw app_runtime_error("Source and candidate files do not have the same point count!"); } pdal::filters::iterators::sequential::Index* idx = dynamic_cast<pdal::filters::iterators::sequential::Index*>(index_iter); if (!idx) { throw app_runtime_error("unable to cast iterator to Index iterator!"); } Stage* candidates = AppSupport::makeReader(candidateOptions); candidates->initialize(); PointBuffer candidates_data(candidates->getSchema(), 1); StageRandomIterator* random_iterator = candidates->createRandomIterator(candidates_data); Schema const& schema = candidates_data.getSchema(); Dimension const& dimX = schema.getDimension("X"); Dimension const& dimY = schema.getDimension("Y"); Dimension const& dimZ = schema.getDimension("Z"); bool bWroteHeader(false); for (std::size_t i = 0; i < source_points->size(); ++i) { Point& source = (*source_points)[i]; std::vector<boost::uint32_t> ids = idx->query(source.x, source.y, source.z, 0.0, 1); if (ids.size()) random_iterator->seek(ids[0]); else throw app_runtime_error("unable to find point for id" + i ); random_iterator->read(candidates_data); boost::int32_t xi = candidates_data.getField<boost::int32_t>(dimX, 0); boost::int32_t yi = candidates_data.getField<boost::int32_t>(dimY, 0); boost::int32_t zi = candidates_data.getField<boost::int32_t>(dimZ, 0); Point p; p.x = dimX.applyScaling<boost::int32_t>(xi); p.y = dimY.applyScaling<boost::int32_t>(yi); p.z = dimZ.applyScaling<boost::int32_t>(zi); double xd = source.x - p.x; double yd = source.y - p.y; double zd = source.z - p.z; if (!bWroteHeader) { writeHeader(std::cout); bWroteHeader = true; } std::cout << i << ","; boost::uint32_t precision = Utils::getStreamPrecision(dimX.getNumericScale()); std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield); std::cout.precision(precision); std::cout << xd << ","; precision = Utils::getStreamPrecision(dimY.getNumericScale()); std::cout.precision(precision); std::cout << yd << ","; precision = Utils::getStreamPrecision(dimZ.getNumericScale()); std::cout.precision(precision); std::cout << zd; std::cout << std::endl; } delete index_iter; delete index_filter; delete candidate_points; delete source_points; return 0; } int main(int argc, char* argv[]) { PcEqual app(argc, argv); return app.run(); } <|endoftext|>
<commit_before>/* ux++ - ux implementation for C++ */ /* LICENSE - The MIT License (MIT) Copyright (c) 2013 Tomona Nanase 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 ENVELOPESTATE_H #define ENVELOPESTATE_H #include <unordered_map> #include <string> #include "EnumBase.hpp" using namespace std; namespace uxpp { /** * エンベロープの状態を表す列挙体です。 */ class EnvelopeState : public EnumBase { public: // <editor-fold desc="-- Enums --"> enum values { /** * 無音状態。 */ silence, /** * アタック(立ち上がり)状態。 */ attack, /** * リリース(余韻)状態。 */ release, }; // </editor-fold> // <editor-fold desc="-- Methods --"> _key_exists_impl(EnvelopeState); _value_exists_impl(EnvelopeState); _toString_impl(EnvelopeState); _tryParse_impl(EnvelopeState); // </editor-fold> private: static const unordered_map<string, values> map; }; const unordered_map<string, EnvelopeState::values> EnvelopeState::map = { {"silence", silence}, {"attack", attack}, {"release", release}, }; } #endif /* ENVELOPESTATE_H */ <commit_msg>EnvelopeStateクラスのusingディレクティブを削除<commit_after>/* ux++ - ux implementation for C++ */ /* LICENSE - The MIT License (MIT) Copyright (c) 2013 Tomona Nanase 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 ENVELOPESTATE_H #define ENVELOPESTATE_H #include <unordered_map> #include <string> #include "EnumBase.hpp" namespace uxpp { /** * エンベロープの状態を表す列挙体です。 */ class EnvelopeState : public EnumBase { public: // <editor-fold desc="-- Enums --"> enum values { /** * 無音状態。 */ silence, /** * アタック(立ち上がり)状態。 */ attack, /** * リリース(余韻)状態。 */ release, }; // </editor-fold> // <editor-fold desc="-- Methods --"> _key_exists_impl(EnvelopeState); _value_exists_impl(EnvelopeState); _toString_impl(EnvelopeState); _tryParse_impl(EnvelopeState); // </editor-fold> private: static const std::unordered_map<std::string, values> map; }; const std::unordered_map<std::string, EnvelopeState::values> EnvelopeState::map = { {"silence", silence}, {"attack", attack}, {"release", release}, }; } #endif /* ENVELOPESTATE_H */ <|endoftext|>
<commit_before>// // version.hpp // *********** // // Copyright (c) 2018 Sharon W (sharon at aegis dot gg) // // Distributed under the MIT License. (See accompanying file LICENSE) // #pragma once #if !defined(AEGIS_VERSION_LONG) #define AEGIS_VERSION_LONG 0x00020000 #define AEGIS_VERSION_SHORT 020000 #define AEGIS_VERSION_TEXT "aegis.cpp 2.0.0 2019/2/3" #define AEGIS_VERSION_MAJOR ((AEGIS_VERSION_LONG & 0x00ff0000) >> 16) #define AEGIS_VERSION_MINOR ((AEGIS_VERSION_LONG & 0x0000ff00) >> 8) #define AEGIS_VERSION_PATCH (AEGIS_VERSION_LONG & 0x000000ff) #endif <commit_msg>version bump<commit_after>// // version.hpp // *********** // // Copyright (c) 2018 Sharon W (sharon at aegis dot gg) // // Distributed under the MIT License. (See accompanying file LICENSE) // #pragma once #if !defined(AEGIS_VERSION_LONG) #define AEGIS_VERSION_LONG 0x00020000 #define AEGIS_VERSION_SHORT 020000 #define AEGIS_VERSION_TEXT "aegis.cpp 2.0.0 2019/2/7" #define AEGIS_VERSION_MAJOR ((AEGIS_VERSION_LONG & 0x00ff0000) >> 16) #define AEGIS_VERSION_MINOR ((AEGIS_VERSION_LONG & 0x0000ff00) >> 8) #define AEGIS_VERSION_PATCH (AEGIS_VERSION_LONG & 0x000000ff) #endif <|endoftext|>
<commit_before>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once // YYYYMMPP // where: // YYYY = 4-digit year number // MM = 2-digit month number // PP = 2-digit patch number #define ARMNN_VERSION "20190200" <commit_msg>IVGCVSW-3087 Changing version to 19.05<commit_after>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once // YYYYMMPP // where: // YYYY = 4-digit year number // MM = 2-digit month number // PP = 2-digit patch number #define ARMNN_VERSION "20190500" <|endoftext|>
<commit_before>#include "common/upstream/eds.h" #include "envoy/api/v2/eds.pb.validate.h" #include "envoy/common/exception.h" #include "envoy/stats/scope.h" #include "common/common/fmt.h" #include "common/config/metadata.h" #include "common/config/subscription_factory.h" #include "common/config/utility.h" #include "common/config/well_known_names.h" #include "common/network/address_impl.h" #include "common/network/resolver_impl.h" #include "common/network/utility.h" #include "common/protobuf/utility.h" #include "common/upstream/load_balancer_impl.h" #include "common/upstream/sds_subscription.h" namespace Envoy { namespace Upstream { EdsClusterImpl::EdsClusterImpl( const envoy::api::v2::Cluster& cluster, Runtime::Loader& runtime, Server::Configuration::TransportSocketFactoryContext& factory_context, Stats::ScopePtr&& stats_scope, bool added_via_api) : BaseDynamicClusterImpl(cluster, runtime, factory_context, std::move(stats_scope), added_via_api), cm_(factory_context.clusterManager()), local_info_(factory_context.localInfo()), cluster_name_(cluster.eds_cluster_config().service_name().empty() ? cluster.name() : cluster.eds_cluster_config().service_name()) { Config::Utility::checkLocalInfo("eds", local_info_); const auto& eds_config = cluster.eds_cluster_config().eds_config(); Event::Dispatcher& dispatcher = factory_context.dispatcher(); Runtime::RandomGenerator& random = factory_context.random(); Upstream::ClusterManager& cm = factory_context.clusterManager(); subscription_ = Config::SubscriptionFactory::subscriptionFromConfigSource< envoy::api::v2::ClusterLoadAssignment>( eds_config, local_info_, dispatcher, cm, random, info_->statsScope(), [this, &eds_config, &cm, &dispatcher, &random]() -> Config::Subscription<envoy::api::v2::ClusterLoadAssignment>* { return new SdsSubscription(info_->stats(), eds_config, cm, dispatcher, random); }, "envoy.api.v2.EndpointDiscoveryService.FetchEndpoints", "envoy.api.v2.EndpointDiscoveryService.StreamEndpoints"); } void EdsClusterImpl::startPreInit() { subscription_->start({cluster_name_}, *this); } void EdsClusterImpl::onConfigUpdate(const ResourceVector& resources, const std::string&) { if (resources.empty()) { ENVOY_LOG(debug, "Missing ClusterLoadAssignment for {} in onConfigUpdate()", cluster_name_); info_->stats().update_empty_.inc(); onPreInitComplete(); return; } if (resources.size() != 1) { throw EnvoyException(fmt::format("Unexpected EDS resource length: {}", resources.size())); } const auto& cluster_load_assignment = resources[0]; MessageUtil::validate(cluster_load_assignment); // TODO(PiotrSikora): Remove this hack once fixed internally. if (!(cluster_load_assignment.cluster_name() == cluster_name_)) { throw EnvoyException(fmt::format("Unexpected EDS cluster (expecting {}): {}", cluster_name_, cluster_load_assignment.cluster_name())); } std::unordered_map<std::string, HostSharedPtr> updated_hosts; PriorityStateManager priority_state_manager(*this, local_info_); for (const auto& locality_lb_endpoint : cluster_load_assignment.endpoints()) { const uint32_t priority = locality_lb_endpoint.priority(); if (priority > 0 && !cluster_name_.empty() && cluster_name_ == cm_.localClusterName()) { throw EnvoyException( fmt::format("Unexpected non-zero priority for local cluster '{}'.", cluster_name_)); } priority_state_manager.initializePriorityFor(locality_lb_endpoint); for (const auto& lb_endpoint : locality_lb_endpoint.lb_endpoints()) { priority_state_manager.registerHostForPriority( "", resolveProtoAddress(lb_endpoint.endpoint().address()), locality_lb_endpoint, lb_endpoint, Host::HealthFlag::FAILED_EDS_HEALTH); } } // Track whether we rebuilt any LB structures. bool cluster_rebuilt = false; const uint32_t overprovisioning_factor = PROTOBUF_GET_WRAPPED_OR_DEFAULT( cluster_load_assignment.policy(), overprovisioning_factor, kDefaultOverProvisioningFactor); // Loop over existing priorities not present in the config. This will empty out any priorities // the config update did not refer to auto& priority_state = priority_state_manager.priorityState(); for (size_t i = 0; i < priority_state.size(); ++i) { if (priority_state[i].first != nullptr) { if (locality_weights_map_.size() <= i) { locality_weights_map_.resize(i + 1); } cluster_rebuilt |= updateHostsPerLocality( i, overprovisioning_factor, *priority_state[i].first, locality_weights_map_[i], priority_state[i].second, priority_state_manager, updated_hosts); } } // Loop over all priorities not present in the config that already exists. This will // empty out any remaining priority that the config update did not refer to. for (size_t i = priority_state.size(); i < priority_set_.hostSetsPerPriority().size(); ++i) { const HostVector empty_hosts; LocalityWeightsMap empty_locality_map; if (locality_weights_map_.size() <= i) { locality_weights_map_.resize(i + 1); } cluster_rebuilt |= updateHostsPerLocality(i, overprovisioning_factor, empty_hosts, locality_weights_map_[i], empty_locality_map, priority_state_manager, updated_hosts); } updateHostMap(std::move(updated_hosts)); if (!cluster_rebuilt) { info_->stats().update_no_rebuild_.inc(); } // If we didn't setup to initialize when our first round of health checking is complete, just // do it now. onPreInitComplete(); } bool EdsClusterImpl::updateHostsPerLocality( const uint32_t priority, const uint32_t overprovisioning_factor, const HostVector& new_hosts, LocalityWeightsMap& locality_weights_map, LocalityWeightsMap& new_locality_weights_map, PriorityStateManager& priority_state_manager, std::unordered_map<std::string, HostSharedPtr>& updated_hosts) { const auto& host_set = priority_set_.getOrCreateHostSet(priority, overprovisioning_factor); HostVectorSharedPtr current_hosts_copy(new HostVector(host_set.hosts())); HostVector hosts_added; HostVector hosts_removed; // We need to trigger updateHosts with the new host vectors if they have changed. We also do this // when the locality weight map changes. // TODO(htuch): We eagerly update all the host sets here on weight changes, which isn't great, // since this has the knock on effect that we rebuild the load balancers and locality scheduler. // We could make this happen lazily, as we do for host-level weight updates, where as things age // out of the locality scheduler, we discover their new weights. We don't currently have a shared // object for locality weights that we can update here, we should add something like this to // improve performance and scalability of locality weight updates. if (host_set.overprovisioning_factor() != overprovisioning_factor || updateDynamicHostList(new_hosts, *current_hosts_copy, hosts_added, hosts_removed, updated_hosts) || locality_weights_map != new_locality_weights_map) { locality_weights_map = new_locality_weights_map; ENVOY_LOG(debug, "EDS hosts or locality weights changed for cluster: {} ({}) priority {}", info_->name(), host_set.hosts().size(), host_set.priority()); priority_state_manager.updateClusterPrioritySet(priority, std::move(current_hosts_copy), hosts_added, hosts_removed, absl::nullopt, overprovisioning_factor); return true; } return false; } void EdsClusterImpl::onConfigUpdateFailed(const EnvoyException* e) { UNREFERENCED_PARAMETER(e); // We need to allow server startup to continue, even if we have a bad config. onPreInitComplete(); } } // namespace Upstream } // namespace Envoy <commit_msg>upstream: update incorrect comment (#4502)<commit_after>#include "common/upstream/eds.h" #include "envoy/api/v2/eds.pb.validate.h" #include "envoy/common/exception.h" #include "envoy/stats/scope.h" #include "common/common/fmt.h" #include "common/config/metadata.h" #include "common/config/subscription_factory.h" #include "common/config/utility.h" #include "common/config/well_known_names.h" #include "common/network/address_impl.h" #include "common/network/resolver_impl.h" #include "common/network/utility.h" #include "common/protobuf/utility.h" #include "common/upstream/load_balancer_impl.h" #include "common/upstream/sds_subscription.h" namespace Envoy { namespace Upstream { EdsClusterImpl::EdsClusterImpl( const envoy::api::v2::Cluster& cluster, Runtime::Loader& runtime, Server::Configuration::TransportSocketFactoryContext& factory_context, Stats::ScopePtr&& stats_scope, bool added_via_api) : BaseDynamicClusterImpl(cluster, runtime, factory_context, std::move(stats_scope), added_via_api), cm_(factory_context.clusterManager()), local_info_(factory_context.localInfo()), cluster_name_(cluster.eds_cluster_config().service_name().empty() ? cluster.name() : cluster.eds_cluster_config().service_name()) { Config::Utility::checkLocalInfo("eds", local_info_); const auto& eds_config = cluster.eds_cluster_config().eds_config(); Event::Dispatcher& dispatcher = factory_context.dispatcher(); Runtime::RandomGenerator& random = factory_context.random(); Upstream::ClusterManager& cm = factory_context.clusterManager(); subscription_ = Config::SubscriptionFactory::subscriptionFromConfigSource< envoy::api::v2::ClusterLoadAssignment>( eds_config, local_info_, dispatcher, cm, random, info_->statsScope(), [this, &eds_config, &cm, &dispatcher, &random]() -> Config::Subscription<envoy::api::v2::ClusterLoadAssignment>* { return new SdsSubscription(info_->stats(), eds_config, cm, dispatcher, random); }, "envoy.api.v2.EndpointDiscoveryService.FetchEndpoints", "envoy.api.v2.EndpointDiscoveryService.StreamEndpoints"); } void EdsClusterImpl::startPreInit() { subscription_->start({cluster_name_}, *this); } void EdsClusterImpl::onConfigUpdate(const ResourceVector& resources, const std::string&) { if (resources.empty()) { ENVOY_LOG(debug, "Missing ClusterLoadAssignment for {} in onConfigUpdate()", cluster_name_); info_->stats().update_empty_.inc(); onPreInitComplete(); return; } if (resources.size() != 1) { throw EnvoyException(fmt::format("Unexpected EDS resource length: {}", resources.size())); } const auto& cluster_load_assignment = resources[0]; MessageUtil::validate(cluster_load_assignment); // TODO(PiotrSikora): Remove this hack once fixed internally. if (!(cluster_load_assignment.cluster_name() == cluster_name_)) { throw EnvoyException(fmt::format("Unexpected EDS cluster (expecting {}): {}", cluster_name_, cluster_load_assignment.cluster_name())); } std::unordered_map<std::string, HostSharedPtr> updated_hosts; PriorityStateManager priority_state_manager(*this, local_info_); for (const auto& locality_lb_endpoint : cluster_load_assignment.endpoints()) { const uint32_t priority = locality_lb_endpoint.priority(); if (priority > 0 && !cluster_name_.empty() && cluster_name_ == cm_.localClusterName()) { throw EnvoyException( fmt::format("Unexpected non-zero priority for local cluster '{}'.", cluster_name_)); } priority_state_manager.initializePriorityFor(locality_lb_endpoint); for (const auto& lb_endpoint : locality_lb_endpoint.lb_endpoints()) { priority_state_manager.registerHostForPriority( "", resolveProtoAddress(lb_endpoint.endpoint().address()), locality_lb_endpoint, lb_endpoint, Host::HealthFlag::FAILED_EDS_HEALTH); } } // Track whether we rebuilt any LB structures. bool cluster_rebuilt = false; const uint32_t overprovisioning_factor = PROTOBUF_GET_WRAPPED_OR_DEFAULT( cluster_load_assignment.policy(), overprovisioning_factor, kDefaultOverProvisioningFactor); // Loop over all priorities that exist in the new configuration. auto& priority_state = priority_state_manager.priorityState(); for (size_t i = 0; i < priority_state.size(); ++i) { if (priority_state[i].first != nullptr) { if (locality_weights_map_.size() <= i) { locality_weights_map_.resize(i + 1); } cluster_rebuilt |= updateHostsPerLocality( i, overprovisioning_factor, *priority_state[i].first, locality_weights_map_[i], priority_state[i].second, priority_state_manager, updated_hosts); } } // Loop over all priorities not present in the config that already exists. This will // empty out any remaining priority that the config update did not refer to. for (size_t i = priority_state.size(); i < priority_set_.hostSetsPerPriority().size(); ++i) { const HostVector empty_hosts; LocalityWeightsMap empty_locality_map; if (locality_weights_map_.size() <= i) { locality_weights_map_.resize(i + 1); } cluster_rebuilt |= updateHostsPerLocality(i, overprovisioning_factor, empty_hosts, locality_weights_map_[i], empty_locality_map, priority_state_manager, updated_hosts); } updateHostMap(std::move(updated_hosts)); if (!cluster_rebuilt) { info_->stats().update_no_rebuild_.inc(); } // If we didn't setup to initialize when our first round of health checking is complete, just // do it now. onPreInitComplete(); } bool EdsClusterImpl::updateHostsPerLocality( const uint32_t priority, const uint32_t overprovisioning_factor, const HostVector& new_hosts, LocalityWeightsMap& locality_weights_map, LocalityWeightsMap& new_locality_weights_map, PriorityStateManager& priority_state_manager, std::unordered_map<std::string, HostSharedPtr>& updated_hosts) { const auto& host_set = priority_set_.getOrCreateHostSet(priority, overprovisioning_factor); HostVectorSharedPtr current_hosts_copy(new HostVector(host_set.hosts())); HostVector hosts_added; HostVector hosts_removed; // We need to trigger updateHosts with the new host vectors if they have changed. We also do this // when the locality weight map changes. // TODO(htuch): We eagerly update all the host sets here on weight changes, which isn't great, // since this has the knock on effect that we rebuild the load balancers and locality scheduler. // We could make this happen lazily, as we do for host-level weight updates, where as things age // out of the locality scheduler, we discover their new weights. We don't currently have a shared // object for locality weights that we can update here, we should add something like this to // improve performance and scalability of locality weight updates. if (host_set.overprovisioning_factor() != overprovisioning_factor || updateDynamicHostList(new_hosts, *current_hosts_copy, hosts_added, hosts_removed, updated_hosts) || locality_weights_map != new_locality_weights_map) { locality_weights_map = new_locality_weights_map; ENVOY_LOG(debug, "EDS hosts or locality weights changed for cluster: {} ({}) priority {}", info_->name(), host_set.hosts().size(), host_set.priority()); priority_state_manager.updateClusterPrioritySet(priority, std::move(current_hosts_copy), hosts_added, hosts_removed, absl::nullopt, overprovisioning_factor); return true; } return false; } void EdsClusterImpl::onConfigUpdateFailed(const EnvoyException* e) { UNREFERENCED_PARAMETER(e); // We need to allow server startup to continue, even if we have a bad config. onPreInitComplete(); } } // namespace Upstream } // namespace Envoy <|endoftext|>
<commit_before>#ifndef CAFFE_UTIL_IO_H_ #define CAFFE_UTIL_IO_H_ #include <string> #include "google/protobuf/message.h" #include "hdf5.h" #include "hdf5_hl.h" #include "caffe/blob.hpp" #include "caffe/proto/caffe.pb.h" #define HDF5_NUM_DIMS 4 namespace leveldb { // Forward declaration for leveldb::Options to be used in GetlevelDBOptions(). class Options; } namespace caffe { using ::google::protobuf::Message; bool ReadProtoFromTextFile(const char* filename, Message* proto); inline bool ReadProtoFromTextFile(const string& filename, Message* proto) { return ReadProtoFromTextFile(filename.c_str(), proto); } inline void ReadProtoFromTextFileOrDie(const char* filename, Message* proto) { CHECK(ReadProtoFromTextFile(filename, proto)); } inline void ReadProtoFromTextFileOrDie(const string& filename, Message* proto) { ReadProtoFromTextFileOrDie(filename.c_str(), proto); } void WriteProtoToTextFile(const Message& proto, const char* filename); inline void WriteProtoToTextFile(const Message& proto, const string& filename) { WriteProtoToTextFile(proto, filename.c_str()); } bool ReadProtoFromBinaryFile(const char* filename, Message* proto); inline bool ReadProtoFromBinaryFile(const string& filename, Message* proto) { return ReadProtoFromBinaryFile(filename.c_str(), proto); } inline void ReadProtoFromBinaryFileOrDie(const char* filename, Message* proto) { CHECK(ReadProtoFromBinaryFile(filename, proto)); } inline void ReadProtoFromBinaryFileOrDie(const string& filename, Message* proto) { ReadProtoFromBinaryFileOrDie(filename.c_str(), proto); } void WriteProtoToBinaryFile(const Message& proto, const char* filename); inline void WriteProtoToBinaryFile( const Message& proto, const string& filename) { WriteProtoToBinaryFile(proto, filename.c_str()); } bool ReadImageToDatum(const string& filename, const int label, const int height, const int width, const bool is_color, Datum* datum); inline bool ReadImageToDatum(const string& filename, const int label, const int height, const int width, Datum* datum) { return ReadImageToDatum(filename, label, height, width, true, datum); } inline bool ReadImageToDatum(const string& filename, const int label, Datum* datum) { return ReadImageToDatum(filename, label, 0, 0, datum); } leveldb::Options GetLevelDBOptions(); template <typename Dtype> void hdf5_load_nd_dataset_helper( hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<Dtype>* blob); template <typename Dtype> void hdf5_load_nd_dataset( hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<Dtype>* blob); template <typename Dtype> void hdf5_save_nd_dataset( const hid_t file_id, const string dataset_name, const Blob<Dtype>& blob); } // namespace caffe #endif // CAFFE_UTIL_IO_H_ <commit_msg>xcode compiler complaints (warnings)...<commit_after>#ifndef CAFFE_UTIL_IO_H_ #define CAFFE_UTIL_IO_H_ #include <string> #include "google/protobuf/message.h" #include "hdf5.h" #include "hdf5_hl.h" #include "caffe/blob.hpp" #include "caffe/proto/caffe.pb.h" #define HDF5_NUM_DIMS 4 namespace leveldb { // Forward declaration for leveldb::Options to be used in GetlevelDBOptions(). struct Options; } namespace caffe { using ::google::protobuf::Message; bool ReadProtoFromTextFile(const char* filename, Message* proto); inline bool ReadProtoFromTextFile(const string& filename, Message* proto) { return ReadProtoFromTextFile(filename.c_str(), proto); } inline void ReadProtoFromTextFileOrDie(const char* filename, Message* proto) { CHECK(ReadProtoFromTextFile(filename, proto)); } inline void ReadProtoFromTextFileOrDie(const string& filename, Message* proto) { ReadProtoFromTextFileOrDie(filename.c_str(), proto); } void WriteProtoToTextFile(const Message& proto, const char* filename); inline void WriteProtoToTextFile(const Message& proto, const string& filename) { WriteProtoToTextFile(proto, filename.c_str()); } bool ReadProtoFromBinaryFile(const char* filename, Message* proto); inline bool ReadProtoFromBinaryFile(const string& filename, Message* proto) { return ReadProtoFromBinaryFile(filename.c_str(), proto); } inline void ReadProtoFromBinaryFileOrDie(const char* filename, Message* proto) { CHECK(ReadProtoFromBinaryFile(filename, proto)); } inline void ReadProtoFromBinaryFileOrDie(const string& filename, Message* proto) { ReadProtoFromBinaryFileOrDie(filename.c_str(), proto); } void WriteProtoToBinaryFile(const Message& proto, const char* filename); inline void WriteProtoToBinaryFile( const Message& proto, const string& filename) { WriteProtoToBinaryFile(proto, filename.c_str()); } bool ReadImageToDatum(const string& filename, const int label, const int height, const int width, const bool is_color, Datum* datum); inline bool ReadImageToDatum(const string& filename, const int label, const int height, const int width, Datum* datum) { return ReadImageToDatum(filename, label, height, width, true, datum); } inline bool ReadImageToDatum(const string& filename, const int label, Datum* datum) { return ReadImageToDatum(filename, label, 0, 0, datum); } leveldb::Options GetLevelDBOptions(); template <typename Dtype> void hdf5_load_nd_dataset_helper( hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<Dtype>* blob); template <typename Dtype> void hdf5_load_nd_dataset( hid_t file_id, const char* dataset_name_, int min_dim, int max_dim, Blob<Dtype>* blob); template <typename Dtype> void hdf5_save_nd_dataset( const hid_t file_id, const string dataset_name, const Blob<Dtype>& blob); } // namespace caffe #endif // CAFFE_UTIL_IO_H_ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Contains forward declarations and using declarations for * the various value types. */ #pragma once #include <cstddef> #include "cpp_utils/array_wrapper.hpp" #include "cpp_utils/aligned_vector.hpp" #include "cpp_utils/aligned_array.hpp" namespace etl { /*! * \brief Compute the real size to allocate for a vector of the * given size and type * \param size The number of elements of the vector * \tparam T The type contained in the vector * \return The size to be allocated */ template <typename T> static constexpr size_t alloc_size_vec(size_t size) { return padding ? size + (size % default_intrinsic_traits<T>::size == 0 ? 0 : (default_intrinsic_traits<T>::size - (size % default_intrinsic_traits<T>::size))) : size; } #ifdef ETL_ADVANCED_PADDING /*! * \brief Compute the real allocated size for a 2D matrix * \tparam T the type of the elements of the matrix * \param size The size of the matrix * \param last The last dimension of the matrix * \return the allocated size for the matrix */ template <typename T> static constexpr size_t alloc_size_mat(size_t size, size_t last) { return size == 0 ? 0 : (padding ? (size / last) * (last + (last % default_intrinsic_traits<T>::size == 0 ? 0 : (default_intrinsic_traits<T>::size - last % default_intrinsic_traits<T>::size))) : size); } #else /*! * \brief Compute the real allocated size for a 2D matrix * \tparam T the type of the elements of the matrix * \param size The size of the matrix * \param last The last dimension of the matrix * \return the allocated size for the matrix */ template <typename T> static constexpr size_t alloc_size_mat(size_t size, size_t last) { cpp_unused(last); return size == 0 ? 0 : alloc_size_vec<T>(size); } #endif /*! * \brief Compute the real allocated size for a matrix * \tparam T the type of the elements of the matrix * \tparam Dims The dimensions of the matrix * \return the allocated size for the matrix */ template <typename T, size_t... Dims> static constexpr size_t alloc_size_mat() { return alloc_size_mat<T>(mul_all<Dims...>(), nth_size<sizeof...(Dims) - 1, 0, Dims...>::value); } template <typename T, typename ST, order SO, size_t... Dims> struct fast_matrix_impl; template <typename T, typename ST, order SO, size_t... Dims> struct custom_fast_matrix_impl; template <typename T, order SO, size_t D = 2> struct dyn_matrix_impl; template <typename T, order SO, size_t D = 2> struct custom_dyn_matrix_impl; template <typename T, sparse_storage SS, size_t D> struct sparse_matrix_impl; template <typename Stream> struct serializer; template <typename Stream> struct deserializer; /*! * \brief Symmetric matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct symmetric_matrix; /*! * \brief Hermitian matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct hermitian_matrix; /*! * \brief Diagonal matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct diagonal_matrix; /*! * \brief Upper triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct upper_matrix; /*! * \brief Strictly upper triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct strictly_upper_matrix; /*! * \brief Uni upper triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct uni_upper_matrix; /*! * \brief Lower triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct lower_matrix; /*! * \brief Strictly lower triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct strictly_lower_matrix; /*! * \brief Uni lower triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct uni_lower_matrix; /*! * \brief A static matrix with fixed dimensions, in row-major order */ template <typename T, size_t... Dims> using fast_matrix = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_mat<T, Dims...>(), default_intrinsic_traits<T>::alignment>, order::RowMajor, Dims...>; /*! * \brief A static matrix with fixed dimensions, in column-major order */ template <typename T, size_t... Dims> using fast_matrix_cm = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_mat<T, Dims...>(), default_intrinsic_traits<T>::alignment>, order::ColumnMajor, Dims...>; /*! * \brief A static vector with fixed dimensions, in row-major order */ template <typename T, size_t Rows> using fast_vector = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_vec<T>(Rows), default_intrinsic_traits<T>::alignment>, order::RowMajor, Rows>; /*! * \brief A static vector with fixed dimensions, in column-major order */ template <typename T, size_t Rows> using fast_vector_cm = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_vec<T>(Rows), default_intrinsic_traits<T>::alignment>, order::ColumnMajor, Rows>; /*! * \brief A hybrid vector with fixed dimensions, in row-major order */ template <typename T, size_t Rows> using fast_dyn_vector = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, order::RowMajor, Rows>; /*! * \brief A hybrid matrix with fixed dimensions, in row-major order */ template <typename T, size_t... Dims> using fast_dyn_matrix = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, order::RowMajor, Dims...>; /*! * \brief A hybrid matrix with fixed dimensions, in specified order */ template <typename T, order SO, size_t... Dims> using fast_dyn_matrix_o = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, SO, Dims...>; /*! * \brief A dynamic matrix, in row-major order, of D dimensions */ template <typename T, size_t D = 2> using dyn_matrix = dyn_matrix_impl<T, order::RowMajor, D>; /*! * \brief A dynamic matrix, in column-major order, of D dimensions */ template <typename T, size_t D = 2> using dyn_matrix_cm = dyn_matrix_impl<T, order::ColumnMajor, D>; /*! * \brief A dynamic matrix, in specific storage order, of D dimensions */ template <typename T, order SO, size_t D = 2> using dyn_matrix_o = dyn_matrix_impl<T, SO, D>; /*! * \brief A dynamic vector, in row-major order */ template <typename T> using dyn_vector = dyn_matrix_impl<T, order::RowMajor, 1>; /*! * \brief A dynamic matrix, in row-major order, of D dimensions */ template <typename T, size_t D = 2> using custom_dyn_matrix = custom_dyn_matrix_impl<T, order::RowMajor, D>; /*! * \brief A dynamic matrix, in column-major order, of D dimensions */ template <typename T, size_t D = 2> using custom_dyn_matrix_cm = custom_dyn_matrix_impl<T, order::ColumnMajor, D>; /*! * \brief A dynamic vector, in row-major order */ template <typename T> using custom_dyn_vector = custom_dyn_matrix_impl<T, order::RowMajor, 1>; /*! * \brief A hybrid vector with fixed dimensions, in row-major order */ template <typename T, size_t Rows> using custom_fast_vector = custom_fast_matrix_impl<T, cpp::array_wrapper<T>, order::RowMajor, Rows>; /*! * \brief A hybrid matrix with fixed dimensions, in row-major order */ template <typename T, size_t... Dims> using custom_fast_matrix = custom_fast_matrix_impl<T, cpp::array_wrapper<T>, order::RowMajor, Dims...>; /*! * \brief A sparse matrix, of D dimensions */ template <typename T, size_t D = 2> using sparse_matrix = sparse_matrix_impl<T, sparse_storage::COO, D>; } //end of namespace etl <commit_msg>Fix body of constexpr function<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Contains forward declarations and using declarations for * the various value types. */ #pragma once #include <cstddef> #include "cpp_utils/array_wrapper.hpp" #include "cpp_utils/aligned_vector.hpp" #include "cpp_utils/aligned_array.hpp" namespace etl { /*! * \brief Compute the real size to allocate for a vector of the * given size and type * \param size The number of elements of the vector * \tparam T The type contained in the vector * \return The size to be allocated */ template <typename T> static constexpr size_t alloc_size_vec(size_t size) { return padding ? size + (size % default_intrinsic_traits<T>::size == 0 ? 0 : (default_intrinsic_traits<T>::size - (size % default_intrinsic_traits<T>::size))) : size; } #ifdef ETL_ADVANCED_PADDING /*! * \brief Compute the real allocated size for a 2D matrix * \tparam T the type of the elements of the matrix * \param size The size of the matrix * \param last The last dimension of the matrix * \return the allocated size for the matrix */ template <typename T> static constexpr size_t alloc_size_mat(size_t size, size_t last) { return size == 0 ? 0 : (padding ? (size / last) * (last + (last % default_intrinsic_traits<T>::size == 0 ? 0 : (default_intrinsic_traits<T>::size - last % default_intrinsic_traits<T>::size))) : size); } #else /*! * \brief Compute the real allocated size for a 2D matrix * \tparam T the type of the elements of the matrix * \param size The size of the matrix * \param last The last dimension of the matrix * \return the allocated size for the matrix */ template <typename T> static constexpr size_t alloc_size_mat(size_t size, size_t last) { return (void) last, (size == 0 ? 0 : alloc_size_vec<T>(size)); } #endif /*! * \brief Compute the real allocated size for a matrix * \tparam T the type of the elements of the matrix * \tparam Dims The dimensions of the matrix * \return the allocated size for the matrix */ template <typename T, size_t... Dims> static constexpr size_t alloc_size_mat() { return alloc_size_mat<T>(mul_all<Dims...>(), nth_size<sizeof...(Dims) - 1, 0, Dims...>::value); } template <typename T, typename ST, order SO, size_t... Dims> struct fast_matrix_impl; template <typename T, typename ST, order SO, size_t... Dims> struct custom_fast_matrix_impl; template <typename T, order SO, size_t D = 2> struct dyn_matrix_impl; template <typename T, order SO, size_t D = 2> struct custom_dyn_matrix_impl; template <typename T, sparse_storage SS, size_t D> struct sparse_matrix_impl; template <typename Stream> struct serializer; template <typename Stream> struct deserializer; /*! * \brief Symmetric matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct symmetric_matrix; /*! * \brief Hermitian matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct hermitian_matrix; /*! * \brief Diagonal matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct diagonal_matrix; /*! * \brief Upper triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct upper_matrix; /*! * \brief Strictly upper triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct strictly_upper_matrix; /*! * \brief Uni upper triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct uni_upper_matrix; /*! * \brief Lower triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct lower_matrix; /*! * \brief Strictly lower triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct strictly_lower_matrix; /*! * \brief Uni lower triangular matrix adapter * \tparam Matrix The adapted matrix */ template <typename Matrix> struct uni_lower_matrix; /*! * \brief A static matrix with fixed dimensions, in row-major order */ template <typename T, size_t... Dims> using fast_matrix = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_mat<T, Dims...>(), default_intrinsic_traits<T>::alignment>, order::RowMajor, Dims...>; /*! * \brief A static matrix with fixed dimensions, in column-major order */ template <typename T, size_t... Dims> using fast_matrix_cm = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_mat<T, Dims...>(), default_intrinsic_traits<T>::alignment>, order::ColumnMajor, Dims...>; /*! * \brief A static vector with fixed dimensions, in row-major order */ template <typename T, size_t Rows> using fast_vector = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_vec<T>(Rows), default_intrinsic_traits<T>::alignment>, order::RowMajor, Rows>; /*! * \brief A static vector with fixed dimensions, in column-major order */ template <typename T, size_t Rows> using fast_vector_cm = fast_matrix_impl<T, cpp::aligned_array<T, alloc_size_vec<T>(Rows), default_intrinsic_traits<T>::alignment>, order::ColumnMajor, Rows>; /*! * \brief A hybrid vector with fixed dimensions, in row-major order */ template <typename T, size_t Rows> using fast_dyn_vector = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, order::RowMajor, Rows>; /*! * \brief A hybrid matrix with fixed dimensions, in row-major order */ template <typename T, size_t... Dims> using fast_dyn_matrix = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, order::RowMajor, Dims...>; /*! * \brief A hybrid matrix with fixed dimensions, in specified order */ template <typename T, order SO, size_t... Dims> using fast_dyn_matrix_o = fast_matrix_impl<T, cpp::aligned_vector<T, default_intrinsic_traits<T>::alignment>, SO, Dims...>; /*! * \brief A dynamic matrix, in row-major order, of D dimensions */ template <typename T, size_t D = 2> using dyn_matrix = dyn_matrix_impl<T, order::RowMajor, D>; /*! * \brief A dynamic matrix, in column-major order, of D dimensions */ template <typename T, size_t D = 2> using dyn_matrix_cm = dyn_matrix_impl<T, order::ColumnMajor, D>; /*! * \brief A dynamic matrix, in specific storage order, of D dimensions */ template <typename T, order SO, size_t D = 2> using dyn_matrix_o = dyn_matrix_impl<T, SO, D>; /*! * \brief A dynamic vector, in row-major order */ template <typename T> using dyn_vector = dyn_matrix_impl<T, order::RowMajor, 1>; /*! * \brief A dynamic matrix, in row-major order, of D dimensions */ template <typename T, size_t D = 2> using custom_dyn_matrix = custom_dyn_matrix_impl<T, order::RowMajor, D>; /*! * \brief A dynamic matrix, in column-major order, of D dimensions */ template <typename T, size_t D = 2> using custom_dyn_matrix_cm = custom_dyn_matrix_impl<T, order::ColumnMajor, D>; /*! * \brief A dynamic vector, in row-major order */ template <typename T> using custom_dyn_vector = custom_dyn_matrix_impl<T, order::RowMajor, 1>; /*! * \brief A hybrid vector with fixed dimensions, in row-major order */ template <typename T, size_t Rows> using custom_fast_vector = custom_fast_matrix_impl<T, cpp::array_wrapper<T>, order::RowMajor, Rows>; /*! * \brief A hybrid matrix with fixed dimensions, in row-major order */ template <typename T, size_t... Dims> using custom_fast_matrix = custom_fast_matrix_impl<T, cpp::array_wrapper<T>, order::RowMajor, Dims...>; /*! * \brief A sparse matrix, of D dimensions */ template <typename T, size_t D = 2> using sparse_matrix = sparse_matrix_impl<T, sparse_storage::COO, D>; } //end of namespace etl <|endoftext|>
<commit_before>#pragma once #include <random> using std::random_device; using std::mt19937_64; namespace hop { class Random { public: static mt19937_64 RNG; protected: static random_device RANDOM_DEVIDE; }; } <commit_msg>devel: Removed "using ..." notation and added namespaces directly<commit_after>#pragma once #include <random> namespace hop { class Random { public: static std::mt19937_64 RNG; protected: static std::random_device RANDOM_DEVIDE; }; } <|endoftext|>
<commit_before>#ifndef LIBICS3_ICS3_EEPPARAM_H_ #define LIBICS3_ICS3_EEPPARAM_H_ #include"ics3/check_invalid.hpp" #include"ics3/baudrate.hpp" #include<array> namespace ics { class EepParam { public: using type = uint16_t; using size_type = std::size_t; using TargetContainer = std::array<uint8_t, 64>; using InvalidChecker = type (&)(type, type, type); enum Flag : type { REVERSE = 0x01, FREE = 0x02, PWMINH = 0x08, ROLL_MODE = 0x10, SLAVE = 0x80 }; static constexpr int byteSize {4}; static constexpr type mask {0xF}; static constexpr EepParam stretch(type = 60); static constexpr EepParam speed(type = 127); static constexpr EepParam punch(type = 1); static constexpr EepParam deadBand(type = 2); static constexpr EepParam dumping(type = 40); static constexpr EepParam selfTimer(type = 250); static constexpr EepParam flag(type = 0x8C); static constexpr EepParam pulseMax(type = 11500); static constexpr EepParam pulseMin(type = 3500); static constexpr EepParam baudrate(type = 10); static constexpr EepParam temperature(type = 80); static constexpr EepParam current(type = 63); static constexpr EepParam response(type = 0); static constexpr EepParam userOffset(type = 0); static constexpr EepParam id(type = 0); static constexpr EepParam strech1(type = 60); static constexpr EepParam strech2(type = 60); static constexpr EepParam strech3(type = 60); static constexpr EepParam newEepParam(const EepParam&, type); constexpr type get() const noexcept; constexpr operator type() const noexcept; void set(type); EepParam& operator=(type); void read(const TargetContainer&); void write(TargetContainer&) const noexcept; private: constexpr EepParam( // non explicit, user cannot touch this size_type, size_type, type, type, InvalidChecker, type); static constexpr type checkInvalidRange(type, type, type); static constexpr type checkInvalidEvenRange(type, type, type); static constexpr type checkInvalidFlag(type, type, type); static constexpr type checkInvalidBaudrate(type, type, type); static constexpr type checkInvalidOffset(type, type, type); const size_type offset; const size_type length; const type min; const type max; InvalidChecker setFunc; type data; }; constexpr EepParam EepParam::stretch(type data) { return {2, 2, 2, 254, EepParam::checkInvalidEvenRange, data}; } constexpr EepParam EepParam::speed(type data) { return {4, 2, 1, 127, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::punch(type data) { return {6, 2, 0, 10, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::deadBand(type data) { return {8, 2, 0, 5, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::dumping(type data) { return {10, 2, 1, 255, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::selfTimer(type data) { return {12, 2, 10, 255, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::flag(type data) { return {14, 2, 0, 255, EepParam::checkInvalidFlag, data}; } constexpr EepParam EepParam::pulseMax(type data) { return {16, 4, 3500, 11500, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::pulseMin(type data) { return {20, 4, 3500, 11500, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::baudrate(type data) { return {26, 2, 0, 10, EepParam::checkInvalidBaudrate, data}; } constexpr EepParam EepParam::temperature(type data) { return {28, 2, 1, 127, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::current(type data) { return {30, 2, 1, 63, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::response(type data) { return {50, 2, 1, 5, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::userOffset(type data) { return {52, 2, 0x81, 127, EepParam::checkInvalidOffset, data}; // 0x81 is -127 on uint8_t type } constexpr EepParam EepParam::id(type data) { return {56, 2, 0, 31, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::strech1(type data) { return {58, 2, 2, 254, EepParam::checkInvalidEvenRange, data}; } constexpr EepParam EepParam::strech2(type data) { return {60, 2, 2, 254, EepParam::checkInvalidEvenRange, data}; } constexpr EepParam EepParam::strech3(type data) { return {62, 2, 2, 254, EepParam::checkInvalidEvenRange, data}; } constexpr EepParam EepParam::newEepParam(const EepParam& paramType, type data) { return {paramType.offset, paramType.length, paramType.min, paramType.max, paramType.setFunc, data}; } constexpr EepParam::type EepParam::get() const noexcept { return data; } constexpr EepParam::operator type() const noexcept { return get(); } inline void EepParam::set(type input) { data = (*setFunc)(input, min, max); // throw std::invalid_argument, std::out_of_range } inline EepParam& EepParam::operator=(type input) { set(input); return *this; } inline void EepParam::read(const TargetContainer& src) { type result {0}; const size_type loopend = offset + length; for (size_type i {offset}; i < loopend; ++i) { result <<= byteSize; result |= src[i] & mask; } set(result); // throw std::invalid_argument, std::out_of_range } inline void EepParam::write(TargetContainer& dest) const noexcept { type nowData {data}; for (size_type i {offset + length - 1}; i >= offset; --i) { dest[i] = nowData & mask; nowData >>= byteSize; } } constexpr EepParam::EepParam( size_type offset, size_type length, type min, type max, InvalidChecker setFunc, type data) : offset(offset), length(length), min(min), max(max), setFunc(setFunc), data(setFunc(data, min, max)) // throw std::invalid_argument, std::out_of_range {} constexpr EepParam::type EepParam::checkInvalidRange(type input, type min, type max) { return ics::checkInvalidRange(input, min, max); } constexpr EepParam::type EepParam::checkInvalidEvenRange(type input, type min, type max) { return input % 2 ? throw std::out_of_range {"Must even value"} : checkInvalidRange(input, min, max); // throw std::out_of_range } constexpr EepParam::type EepParam::checkInvalidFlag(type input, type, type) { return !(input & 0x04) ? throw std::invalid_argument {"Eepparam(flag): Must up bits 0x04"} : ~(input | ~0x60) ? throw std::invalid_argument {"Eepparam(flag): Must down bits 0x60"} : input; } constexpr EepParam::type EepParam::checkInvalidBaudrate(type input, type, type) { return input == Baudrate::RATE115200().get() ? input : //input == Baudrate::RATE625000().get() ? input : //input == Baudrate::RATE1250000().get() ? input : throw std::invalid_argument {"baudrate not exist"}; } constexpr EepParam::type EepParam::checkInvalidOffset(type input, type min, type max) { return input < max ? input : // this min < 0; min value is 0 min < input ? input : // this min < 0; input must is bigger than min. throw std::out_of_range {"Eeprom(offset): range over"}; // min < input < max is failed } } #endif // LIBICS3_ICS3_EEPPARAM_H_ <commit_msg>Update for recefence object<commit_after>#ifndef LIBICS3_ICS3_EEPPARAM_H_ #define LIBICS3_ICS3_EEPPARAM_H_ #include"ics3/check_invalid.hpp" #include"ics3/baudrate.hpp" #include<array> namespace ics { class EepParam { public: using type = uint16_t; using size_type = std::size_t; using TargetContainer = std::array<uint8_t, 64>; using InvalidChecker = type (&)(type, type, type); enum Flag : type { REVERSE = 0x01, FREE = 0x02, PWMINH = 0x08, ROLL_MODE = 0x10, SLAVE = 0x80 }; static constexpr int byteSize {4}; static constexpr type mask {0xF}; static constexpr EepParam stretch(type = 60); static constexpr EepParam speed(type = 127); static constexpr EepParam punch(type = 1); static constexpr EepParam deadBand(type = 2); static constexpr EepParam dumping(type = 40); static constexpr EepParam selfTimer(type = 250); static constexpr EepParam flag(type = 0x8C); static constexpr EepParam pulseMax(type = 11500); static constexpr EepParam pulseMin(type = 3500); static constexpr EepParam baudrate(type = 10); static constexpr EepParam temperature(type = 80); static constexpr EepParam current(type = 63); static constexpr EepParam response(type = 0); static constexpr EepParam userOffset(type = 0); static constexpr EepParam id(type = 0); static constexpr EepParam strech1(type = 60); static constexpr EepParam strech2(type = 60); static constexpr EepParam strech3(type = 60); static constexpr EepParam newEepParam(const EepParam&, type); constexpr type get() const noexcept; constexpr operator type() const noexcept; void set(type); EepParam& operator=(type); void read(const TargetContainer&); void write(TargetContainer&) const noexcept; private: constexpr EepParam( // non explicit, user cannot touch this size_type, size_type, type, type, InvalidChecker, type); static constexpr type checkInvalidRange(type, type, type); static constexpr type checkInvalidEvenRange(type, type, type); static constexpr type checkInvalidFlag(type, type, type); static constexpr type checkInvalidBaudrate(type, type, type); static constexpr type checkInvalidOffset(type, type, type); const size_type offset; const size_type length; const type min; const type max; InvalidChecker setFunc; type data; }; constexpr EepParam EepParam::stretch(type data) { return {2, 2, 2, 254, EepParam::checkInvalidEvenRange, data}; } constexpr EepParam EepParam::speed(type data) { return {4, 2, 1, 127, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::punch(type data) { return {6, 2, 0, 10, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::deadBand(type data) { return {8, 2, 0, 5, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::dumping(type data) { return {10, 2, 1, 255, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::selfTimer(type data) { return {12, 2, 10, 255, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::flag(type data) { return {14, 2, 0, 255, EepParam::checkInvalidFlag, data}; } constexpr EepParam EepParam::pulseMax(type data) { return {16, 4, 3500, 11500, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::pulseMin(type data) { return {20, 4, 3500, 11500, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::baudrate(type data) { return {26, 2, 0, 10, EepParam::checkInvalidBaudrate, data}; } constexpr EepParam EepParam::temperature(type data) { return {28, 2, 1, 127, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::current(type data) { return {30, 2, 1, 63, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::response(type data) { return {50, 2, 1, 5, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::userOffset(type data) { return {52, 2, 0x81, 127, EepParam::checkInvalidOffset, data}; // 0x81 is -127 on uint8_t type } constexpr EepParam EepParam::id(type data) { return {56, 2, 0, 31, EepParam::checkInvalidRange, data}; } constexpr EepParam EepParam::strech1(type data) { return {58, 2, 2, 254, EepParam::checkInvalidEvenRange, data}; } constexpr EepParam EepParam::strech2(type data) { return {60, 2, 2, 254, EepParam::checkInvalidEvenRange, data}; } constexpr EepParam EepParam::strech3(type data) { return {62, 2, 2, 254, EepParam::checkInvalidEvenRange, data}; } constexpr EepParam EepParam::newEepParam(const EepParam& paramType, type data) { return {paramType.offset, paramType.length, paramType.min, paramType.max, paramType.setFunc, data}; } constexpr EepParam::type EepParam::get() const noexcept { return data; } constexpr EepParam::operator type() const noexcept { return get(); } inline void EepParam::set(type input) { data = setFunc(input, min, max); // throw std::invalid_argument, std::out_of_range } inline EepParam& EepParam::operator=(type input) { set(input); return *this; } inline void EepParam::read(const TargetContainer& src) { type result {0}; const size_type loopend = offset + length; for (size_type i {offset}; i < loopend; ++i) { result <<= byteSize; result |= src[i] & mask; } set(result); // throw std::invalid_argument, std::out_of_range } inline void EepParam::write(TargetContainer& dest) const noexcept { type nowData {data}; for (size_type i {offset + length - 1}; i >= offset; --i) { dest[i] = nowData & mask; nowData >>= byteSize; } } constexpr EepParam::EepParam( size_type offset, size_type length, type min, type max, InvalidChecker setFunc, type data) : offset(offset), length(length), min(min), max(max), setFunc(setFunc), data(setFunc(data, min, max)) // throw std::invalid_argument, std::out_of_range {} constexpr EepParam::type EepParam::checkInvalidRange(type input, type min, type max) { return ics::checkInvalidRange(input, min, max); } constexpr EepParam::type EepParam::checkInvalidEvenRange(type input, type min, type max) { return input % 2 ? throw std::out_of_range {"Must even value"} : checkInvalidRange(input, min, max); // throw std::out_of_range } constexpr EepParam::type EepParam::checkInvalidFlag(type input, type, type) { return !(input & 0x04) ? throw std::invalid_argument {"Eepparam(flag): Must up bits 0x04"} : ~(input | ~0x60) ? throw std::invalid_argument {"Eepparam(flag): Must down bits 0x60"} : input; } constexpr EepParam::type EepParam::checkInvalidBaudrate(type input, type, type) { return input == Baudrate::RATE115200().get() ? input : //input == Baudrate::RATE625000().get() ? input : //input == Baudrate::RATE1250000().get() ? input : throw std::invalid_argument {"baudrate not exist"}; } constexpr EepParam::type EepParam::checkInvalidOffset(type input, type min, type max) { return input < max ? input : // this min < 0; min value is 0 min < input ? input : // this min < 0; input must is bigger than min. throw std::out_of_range {"Eeprom(offset): range over"}; // min < input < max is failed } } #endif // LIBICS3_ICS3_EEPPARAM_H_ <|endoftext|>
<commit_before>/* Copyright (c) 2015-present Advanced Micro Devices, Inc. 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 <hip/hip_runtime.h> #include "hip_event.hpp" namespace hip { bool Event::ready() { if (event_->status() != CL_COMPLETE) { event_->notifyCmdQueue(); } return (event_->status() == CL_COMPLETE); } hipError_t Event::query() { amd::ScopedLock lock(lock_); // If event is not recorded, event_ is null, hence return hipSuccess if (event_ == nullptr) { return hipSuccess; } return ready() ? hipSuccess : hipErrorNotReady; } hipError_t Event::synchronize() { amd::ScopedLock lock(lock_); // If event is not recorded, event_ is null, hence return hipSuccess if (event_ == nullptr) { return hipSuccess; } event_->awaitCompletion(); return hipSuccess; } hipError_t Event::elapsedTime(Event& eStop, float& ms) { amd::ScopedLock startLock(lock_); if (this == &eStop) { if (event_ == nullptr) { return hipErrorInvalidHandle; } if (flags & hipEventDisableTiming) { return hipErrorInvalidHandle; } if (!ready()) { return hipErrorNotReady; } ms = 0.f; return hipSuccess; } amd::ScopedLock stopLock(eStop.lock_); if (event_ == nullptr || eStop.event_ == nullptr) { return hipErrorInvalidHandle; } if ((flags | eStop.flags) & hipEventDisableTiming) { return hipErrorInvalidHandle; } if (!ready() || !eStop.ready()) { return hipErrorNotReady; } ms = static_cast<float>(static_cast<int64_t>(eStop.event_->profilingInfo().end_ - event_->profilingInfo().start_))/1000000.f; return hipSuccess; } hipError_t Event::streamWait(amd::HostQueue* hostQueue, uint flags) { if ((event_ == nullptr) || (event_->command().queue() == hostQueue)) { return hipSuccess; } amd::ScopedLock lock(lock_); bool retain = false; if (!event_->notifyCmdQueue()) { return hipErrorLaunchOutOfResources; } amd::Command::EventWaitList eventWaitList; eventWaitList.push_back(event_); amd::Command* command = new amd::Marker(*hostQueue, false, eventWaitList); if (command == NULL) { return hipErrorOutOfMemory; } command->enqueue(); command->release(); return hipSuccess; } void Event::addMarker(amd::HostQueue* queue, amd::Command* command) { amd::ScopedLock lock(lock_); if (event_ == &command->event()) return; if (event_ != nullptr) { event_->release(); } event_ = &command->event(); } } hipError_t ihipEventCreateWithFlags(hipEvent_t* event, unsigned flags) { if (event == nullptr) { return hipErrorInvalidValue; } unsigned supportedFlags = hipEventDefault | hipEventBlockingSync | hipEventDisableTiming | hipEventReleaseToDevice | hipEventReleaseToSystem; const unsigned releaseFlags = (hipEventReleaseToDevice | hipEventReleaseToSystem); const bool illegalFlags = (flags & ~supportedFlags) || // can't set any unsupported flags. (flags & releaseFlags) == releaseFlags; // can't set both release flags if (!illegalFlags) { hip::Event* e = new hip::Event(flags); if (e == nullptr) { return hipErrorOutOfMemory; } *event = reinterpret_cast<hipEvent_t>(e); } else { return hipErrorInvalidValue; } return hipSuccess; } hipError_t ihipEventQuery(hipEvent_t event) { if (event == nullptr) { return hipErrorInvalidHandle; } hip::Event* e = reinterpret_cast<hip::Event*>(event); return e->query(); } hipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags) { HIP_INIT_API(hipEventCreateWithFlags, event, flags); HIP_RETURN(ihipEventCreateWithFlags(event, flags)); } hipError_t hipEventCreate(hipEvent_t* event) { HIP_INIT_API(hipEventCreate, event); HIP_RETURN(ihipEventCreateWithFlags(event, 0)); } hipError_t hipEventDestroy(hipEvent_t event) { HIP_INIT_API(hipEventDestroy, event); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } delete reinterpret_cast<hip::Event*>(event); HIP_RETURN(hipSuccess); } hipError_t hipEventElapsedTime(float *ms, hipEvent_t start, hipEvent_t stop) { HIP_INIT_API(hipEventElapsedTime, ms, start, stop); if (start == nullptr || stop == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } if (ms == nullptr) { HIP_RETURN(hipErrorInvalidValue); } hip::Event* eStart = reinterpret_cast<hip::Event*>(start); hip::Event* eStop = reinterpret_cast<hip::Event*>(stop); HIP_RETURN(eStart->elapsedTime(*eStop, *ms)); } hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream) { HIP_INIT_API(hipEventRecord, event, stream); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } amd::HostQueue* queue = hip::getQueue(stream); amd::Command* command = queue->getLastQueuedCommand(true); if (command == nullptr) { command = new amd::Marker(*queue, false); command->enqueue(); } hip::Event* e = reinterpret_cast<hip::Event*>(event); e->addMarker(queue, command); HIP_RETURN(hipSuccess); } hipError_t hipEventSynchronize(hipEvent_t event) { HIP_INIT_API(hipEventSynchronize, event); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } hip::Event* e = reinterpret_cast<hip::Event*>(event); HIP_RETURN(e->synchronize()); } hipError_t hipEventQuery(hipEvent_t event) { HIP_INIT_API(hipEventQuery, event); HIP_RETURN(ihipEventQuery(event)); } <commit_msg>SWDEV-235495 Fix elapsed time calculation<commit_after>/* Copyright (c) 2015-present Advanced Micro Devices, Inc. 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 <hip/hip_runtime.h> #include "hip_event.hpp" namespace hip { bool Event::ready() { if (event_->status() != CL_COMPLETE) { event_->notifyCmdQueue(); } return (event_->status() == CL_COMPLETE); } hipError_t Event::query() { amd::ScopedLock lock(lock_); // If event is not recorded, event_ is null, hence return hipSuccess if (event_ == nullptr) { return hipSuccess; } return ready() ? hipSuccess : hipErrorNotReady; } hipError_t Event::synchronize() { amd::ScopedLock lock(lock_); // If event is not recorded, event_ is null, hence return hipSuccess if (event_ == nullptr) { return hipSuccess; } event_->awaitCompletion(); return hipSuccess; } hipError_t Event::elapsedTime(Event& eStop, float& ms) { amd::ScopedLock startLock(lock_); if (this == &eStop) { if (event_ == nullptr) { return hipErrorInvalidHandle; } if (flags & hipEventDisableTiming) { return hipErrorInvalidHandle; } if (!ready()) { return hipErrorNotReady; } ms = 0.f; return hipSuccess; } amd::ScopedLock stopLock(eStop.lock_); if (event_ == nullptr || eStop.event_ == nullptr) { return hipErrorInvalidHandle; } if ((flags | eStop.flags) & hipEventDisableTiming) { return hipErrorInvalidHandle; } if (!ready() || !eStop.ready()) { return hipErrorNotReady; } ms = static_cast<float>(static_cast<int64_t>(eStop.event_->profilingInfo().end_ - event_->profilingInfo().end_))/1000000.f; return hipSuccess; } hipError_t Event::streamWait(amd::HostQueue* hostQueue, uint flags) { if ((event_ == nullptr) || (event_->command().queue() == hostQueue)) { return hipSuccess; } amd::ScopedLock lock(lock_); bool retain = false; if (!event_->notifyCmdQueue()) { return hipErrorLaunchOutOfResources; } amd::Command::EventWaitList eventWaitList; eventWaitList.push_back(event_); amd::Command* command = new amd::Marker(*hostQueue, false, eventWaitList); if (command == NULL) { return hipErrorOutOfMemory; } command->enqueue(); command->release(); return hipSuccess; } void Event::addMarker(amd::HostQueue* queue, amd::Command* command) { amd::ScopedLock lock(lock_); if (event_ == &command->event()) return; if (event_ != nullptr) { event_->release(); } event_ = &command->event(); } } hipError_t ihipEventCreateWithFlags(hipEvent_t* event, unsigned flags) { if (event == nullptr) { return hipErrorInvalidValue; } unsigned supportedFlags = hipEventDefault | hipEventBlockingSync | hipEventDisableTiming | hipEventReleaseToDevice | hipEventReleaseToSystem; const unsigned releaseFlags = (hipEventReleaseToDevice | hipEventReleaseToSystem); const bool illegalFlags = (flags & ~supportedFlags) || // can't set any unsupported flags. (flags & releaseFlags) == releaseFlags; // can't set both release flags if (!illegalFlags) { hip::Event* e = new hip::Event(flags); if (e == nullptr) { return hipErrorOutOfMemory; } *event = reinterpret_cast<hipEvent_t>(e); } else { return hipErrorInvalidValue; } return hipSuccess; } hipError_t ihipEventQuery(hipEvent_t event) { if (event == nullptr) { return hipErrorInvalidHandle; } hip::Event* e = reinterpret_cast<hip::Event*>(event); return e->query(); } hipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags) { HIP_INIT_API(hipEventCreateWithFlags, event, flags); HIP_RETURN(ihipEventCreateWithFlags(event, flags)); } hipError_t hipEventCreate(hipEvent_t* event) { HIP_INIT_API(hipEventCreate, event); HIP_RETURN(ihipEventCreateWithFlags(event, 0)); } hipError_t hipEventDestroy(hipEvent_t event) { HIP_INIT_API(hipEventDestroy, event); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } delete reinterpret_cast<hip::Event*>(event); HIP_RETURN(hipSuccess); } hipError_t hipEventElapsedTime(float *ms, hipEvent_t start, hipEvent_t stop) { HIP_INIT_API(hipEventElapsedTime, ms, start, stop); if (start == nullptr || stop == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } if (ms == nullptr) { HIP_RETURN(hipErrorInvalidValue); } hip::Event* eStart = reinterpret_cast<hip::Event*>(start); hip::Event* eStop = reinterpret_cast<hip::Event*>(stop); HIP_RETURN(eStart->elapsedTime(*eStop, *ms)); } hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream) { HIP_INIT_API(hipEventRecord, event, stream); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } amd::HostQueue* queue = hip::getQueue(stream); amd::Command* command = queue->getLastQueuedCommand(true); if (command == nullptr) { command = new amd::Marker(*queue, false); command->enqueue(); } hip::Event* e = reinterpret_cast<hip::Event*>(event); e->addMarker(queue, command); HIP_RETURN(hipSuccess); } hipError_t hipEventSynchronize(hipEvent_t event) { HIP_INIT_API(hipEventSynchronize, event); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } hip::Event* e = reinterpret_cast<hip::Event*>(event); HIP_RETURN(e->synchronize()); } hipError_t hipEventQuery(hipEvent_t event) { HIP_INIT_API(hipEventQuery, event); HIP_RETURN(ihipEventQuery(event)); } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef __MINIZINC_UTILS_H__ #define __MINIZINC_UTILS_H__ #include <string> #include <sstream> #include <ctime> #include <limits> #include <iomanip> using namespace std; namespace MiniZinc { inline std::string stoptime(clock_t& start) { std::ostringstream oss; clock_t now = clock(); oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) / CLOCKS_PER_SEC) * 1000.0) << " ms"; start = now; return oss.str(); } inline std::string timeDiff(clock_t t2, clock_t t1) { std::ostringstream oss; oss << std::setprecision(2) << std::fixed << ((static_cast<double>(t2-t1) / CLOCKS_PER_SEC)) << " s"; return oss.str(); } inline bool beginswith(string s, string t) { return s.compare(0, t.length(), t)==0; } inline void checkIOStatus( bool fOk, string msg ) { if ( !fOk ) { std::cerr << "\n " << msg << strerror(errno) << "." << std::endl; exit(EXIT_FAILURE); } } template <class T> inline bool assignStr(T*, const string ) { return false; } template<> inline bool assignStr(string* pS, const string s ) { *pS = s; return true; } /// A simple per-cmdline option parser class CLOParser { int& i; // current item const int argc=0; const char* const* argv=0; public: CLOParser( int& ii, const int ac, const char* const* av ) : i(ii), argc(ac), argv(av) { } template <class Value=int> inline bool getOption( const char* names, // space-separated option list Value* pResult=nullptr, // pointer to value storage bool fValueOptional=false // if pResult, for non-string values ) { if( i>=argc ) return false; assert( argv[i] ); string arg( argv[i] ); /// Separate keywords string keyword; istringstream iss( names ); while ( iss >> keyword ) { if ( 0!=arg.compare( 0, keyword.size(), keyword ) ) continue; /// Process it if ( keyword.size() < arg.size() ) { if ( 0==pResult ) continue; arg.erase( 0, keyword.size() ); } else { if ( 0==pResult ) return true; i++; if( i>=argc ) return false; arg = argv[i]; } assert( pResult ); if ( assignStr( pResult, arg ) ) return true; istringstream iss( arg ); if ( !( iss >> (*pResult) ) ) { if ( fValueOptional ) { --i; return true; } cerr << "\nBad value for " << keyword << ": " << arg << endl; return false; } return true; } return false; } }; // class CLOParser /// This class prints a value if non-0 and adds comma if not 1st time class HadOne { bool fHadOne=false; public: template <class N> string operator()(const N& val, const char* descr=0) { ostringstream oss; if ( val ) { if ( fHadOne ) oss << ", "; fHadOne=true; oss << val; if ( descr ) oss << descr; } return oss.str(); } void reset() { fHadOne=false; } operator bool() const { return fHadOne; } bool operator!() const { return !fHadOne; } }; } #endif // __MINIZINC_FLATTENER_H__ <commit_msg>For optional cmdline values, can stop after the end of the list<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef __MINIZINC_UTILS_H__ #define __MINIZINC_UTILS_H__ #include <string> #include <sstream> #include <ctime> #include <limits> #include <iomanip> using namespace std; namespace MiniZinc { inline std::string stoptime(clock_t& start) { std::ostringstream oss; clock_t now = clock(); oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) / CLOCKS_PER_SEC) * 1000.0) << " ms"; start = now; return oss.str(); } inline std::string timeDiff(clock_t t2, clock_t t1) { std::ostringstream oss; oss << std::setprecision(2) << std::fixed << ((static_cast<double>(t2-t1) / CLOCKS_PER_SEC)) << " s"; return oss.str(); } inline bool beginswith(string s, string t) { return s.compare(0, t.length(), t)==0; } inline void checkIOStatus( bool fOk, string msg ) { if ( !fOk ) { std::cerr << "\n " << msg << strerror(errno) << "." << std::endl; exit(EXIT_FAILURE); } } template <class T> inline bool assignStr(T*, const string ) { return false; } template<> inline bool assignStr(string* pS, const string s ) { *pS = s; return true; } /// A simple per-cmdline option parser class CLOParser { int& i; // current item const int argc=0; const char* const* argv=0; public: CLOParser( int& ii, const int ac, const char* const* av ) : i(ii), argc(ac), argv(av) { } template <class Value=int> inline bool getOption( const char* names, // space-separated option list Value* pResult=nullptr, // pointer to value storage bool fValueOptional=false // if pResult, for non-string values ) { if( i>=argc ) return false; assert( argv[i] ); string arg( argv[i] ); /// Separate keywords string keyword; istringstream iss( names ); while ( iss >> keyword ) { if ( 0!=arg.compare( 0, keyword.size(), keyword ) ) continue; /// Process it if ( keyword.size() < arg.size() ) { if ( 0==pResult ) continue; arg.erase( 0, keyword.size() ); } else { if ( 0==pResult ) return true; i++; if( i>=argc ) return fValueOptional; arg = argv[i]; } assert( pResult ); if ( assignStr( pResult, arg ) ) return true; istringstream iss( arg ); if ( !( iss >> (*pResult) ) ) { if ( fValueOptional ) { --i; return true; } cerr << "\nBad value for " << keyword << ": " << arg << endl; return false; } return true; } return false; } }; // class CLOParser /// This class prints a value if non-0 and adds comma if not 1st time class HadOne { bool fHadOne=false; public: template <class N> string operator()(const N& val, const char* descr=0) { ostringstream oss; if ( val ) { if ( fHadOne ) oss << ", "; fHadOne=true; oss << val; if ( descr ) oss << descr; } return oss.str(); } void reset() { fHadOne=false; } operator bool() const { return fHadOne; } bool operator!() const { return !fHadOne; } }; } #endif // __MINIZINC_FLATTENER_H__ <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. /** * @namespace nix::util * @brief Namespace for utility functions. This namespace is not part of the public API. */ #ifndef NIX_UTIL_H #define NIX_UTIL_H #include <string> #include <sstream> #include <iostream> #include <vector> #include <boost/optional.hpp> #include <boost/none_t.hpp> #include <nix/Platform.hpp> #include <nix/Exception.hpp> namespace nix { namespace util { /** * Remove blank spaces from the entire string * * @param str The string to trim (will be modified in-place) */ NIXAPI void deblankString(std::string &str); /** * Remove blank spaces from the entire string * * @param str The string to trim * * @return The trimmed string */ NIXAPI std::string deblankString(const std::string &str); /** * Generates an ID-String. * * @param prefix The prefix to append to the generated id. * @param length The length of the ID. * * @return The generated id string. */ NIXAPI std::string createId(std::string prefix = "", int length = 16); /** * Convert a time value into a string representation. * @todo Maybe its better to use C++11 std::chrono::time_point instead of time_t * * @param time The time to convert. * * @return The sting representation of time. */ NIXAPI std::string timeToStr(time_t time); /** * Convert a string representation of a date into a time value. * * @param time The string representation of a date. * * @return The time value that is represented by the time parameter. */ NIXAPI time_t strToTime(const std::string &time); /** * Convert a time value into a string representation. * @todo Maybe its better to use C++11 std::chrono::time_point instead of time_t * * @return The default time. */ NIXAPI time_t getTime(); /* * * */ NIXAPI std::string unitSanitizer(const std::string &unit); /** * Converts minutes and hours to seconds. * * @param unit the original unit (i.e. h for hour, or min for minutes) * @param value the original value * @return the value in converted to seconds */ template <typename T> NIXAPI T convertToSeconds(const std::string &unit, T value) { T seconds; if (unit == "min") { seconds = value * 60; } else if (unit == "h") { std::string new_unit = "min"; seconds = convertToSeconds(new_unit, value * 60); } else if (unit == "s") { seconds = value; } else { std::cerr << "[nix::util::convertToSeconds] Warning: given unit is not supported!" << std::endl; seconds = value; } return seconds; } /** * Converts temperatures given in degrees Celsius of Fahren to Kelvin. * * @param unit the original unit {"F", "°F", "C", "°C"} * @param value the original value * @return the temperature in Kelvin */ template<typename T> NIXAPI T convertToKelvin(const std::string &unit, T value) { T temperature; if (unit == "°C" || unit == "C") { temperature = value + 273.15; } else if (unit == "°F" || unit == "F") { temperature = (value - 32) * 5/9 + 273.15; } else if (unit == "°K" || unit == "K") { temperature = value; } else { std::cerr << "[nix::util::convertToKelvin] Warning: given unit is not supported" << std::endl; temperature = value; } return temperature; } /** * Checks if the passed string represents a valid SI unit. * * @param unit a string that is supposed to represent an SI unit. * @return bool true or false */ NIXAPI bool isSIUnit(const std::string &unit); /** * Checks if the passed string is a valid combination of SI units. * For example mV^2*Hz^-1. Method accepts only the * notation. * * @param unit a string that should be tested * @return bool */ NIXAPI bool isCompoundSIUnit(const std::string &unit); /** * Get the scaling between two SI units that are identified by the two strings. * * @param originUnit the original unit * @param destinationUnit the one into which a scaling should be done * * @return A double with the appropriate scaling * @throw Runtime Exception when units cannot be converted into each other by mere scaling */ NIXAPI double getSIScaling(const std::string &originUnit, const std::string &destinationUnit); /** * Splits an SI unit into prefix, unit and the power components. * @param fullUnit * @param prefix * @param unit * @param power */ NIXAPI void splitUnit(const std::string &fullUnit, std::string &prefix, std::string &unit, std::string &power); /** * Splits a SI unit compound into its atomic parts. * * @param compoundUnit string representing an SI unit that consists of many atomic units * @param atomicUnits vector<string> that takes the atomic units */ NIXAPI void splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits); /** * Convert a number into a string representation. * * @param number The number to convert * * @return The string representation of number */ template<typename T> std::string numToStr(T number) { std::stringstream s; s << number; return s.str(); } /** * Convert a string representing a number into a number. * * @param str The string to convert. * * @return The number that was represented by the string. */ template<typename T> T strToNum(const std::string &str) { std::stringstream s(str); T number; return s >> number ? number : 0; } /** * Check whether a given type is of type "boost::optional" * Usage: * myBool = is_optional<decltype(myVar)>::value; * myBool = is_optional<MY_TYPE>::value; * * @param type Template param: The type to check. * * @return bool (use '::value' to check result) */ template<typename> struct is_optional : std::false_type {}; template<typename T> struct is_optional<boost::optional<T>> : std::true_type {}; /** * Optional de-referencing: * De-reference boost optional type if such given, returned var * unchanged otherwise. * * @param mixed The variable to de-reference. * * @return mixed */ template<typename T> T deRef(T var) { return var; } template<typename R> R deRef(boost::optional<R> var) { if(var) return *var; else return R(); } } // namespace util } // namespace nix #endif // NIX_UTIL_H <commit_msg>util::convertToKelvin: handle T = int properly<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. /** * @namespace nix::util * @brief Namespace for utility functions. This namespace is not part of the public API. */ #ifndef NIX_UTIL_H #define NIX_UTIL_H #include <string> #include <sstream> #include <iostream> #include <vector> #include <cmath> #include <type_traits> #include <boost/optional.hpp> #include <boost/none_t.hpp> #include <nix/Platform.hpp> #include <nix/Exception.hpp> namespace nix { namespace util { /** * Remove blank spaces from the entire string * * @param str The string to trim (will be modified in-place) */ NIXAPI void deblankString(std::string &str); /** * Remove blank spaces from the entire string * * @param str The string to trim * * @return The trimmed string */ NIXAPI std::string deblankString(const std::string &str); /** * Generates an ID-String. * * @param prefix The prefix to append to the generated id. * @param length The length of the ID. * * @return The generated id string. */ NIXAPI std::string createId(std::string prefix = "", int length = 16); /** * Convert a time value into a string representation. * @todo Maybe its better to use C++11 std::chrono::time_point instead of time_t * * @param time The time to convert. * * @return The sting representation of time. */ NIXAPI std::string timeToStr(time_t time); /** * Convert a string representation of a date into a time value. * * @param time The string representation of a date. * * @return The time value that is represented by the time parameter. */ NIXAPI time_t strToTime(const std::string &time); /** * Convert a time value into a string representation. * @todo Maybe its better to use C++11 std::chrono::time_point instead of time_t * * @return The default time. */ NIXAPI time_t getTime(); /* * * */ NIXAPI std::string unitSanitizer(const std::string &unit); /** * Converts minutes and hours to seconds. * * @param unit the original unit (i.e. h for hour, or min for minutes) * @param value the original value * @return the value in converted to seconds */ template <typename T> NIXAPI T convertToSeconds(const std::string &unit, T value) { T seconds; if (unit == "min") { seconds = value * 60; } else if (unit == "h") { std::string new_unit = "min"; seconds = convertToSeconds(new_unit, value * 60); } else if (unit == "s") { seconds = value; } else { std::cerr << "[nix::util::convertToSeconds] Warning: given unit is not supported!" << std::endl; seconds = value; } return seconds; } /** * Converts temperatures given in degrees Celsius of Fahren to Kelvin. * * @param unit the original unit {"F", "°F", "C", "°C"} * @param value the original value * @return the temperature in Kelvin */ template<typename T> NIXAPI T convertToKelvin(const std::string &unit, T value) { T temperature; if (unit == "°C" || unit == "C") { temperature = value + 273.15; } else if (unit == "°F" || unit == "F") { double temp = (value - 32) * 5.0/9 + 273.15; temperature = std::is_integral<T>::value ? std::round(temp) : temp; } else if (unit == "°K" || unit == "K") { temperature = value; } else { std::cerr << "[nix::util::convertToKelvin] Warning: given unit is not supported" << std::endl; temperature = value; } return temperature; } /** * Checks if the passed string represents a valid SI unit. * * @param unit a string that is supposed to represent an SI unit. * @return bool true or false */ NIXAPI bool isSIUnit(const std::string &unit); /** * Checks if the passed string is a valid combination of SI units. * For example mV^2*Hz^-1. Method accepts only the * notation. * * @param unit a string that should be tested * @return bool */ NIXAPI bool isCompoundSIUnit(const std::string &unit); /** * Get the scaling between two SI units that are identified by the two strings. * * @param originUnit the original unit * @param destinationUnit the one into which a scaling should be done * * @return A double with the appropriate scaling * @throw Runtime Exception when units cannot be converted into each other by mere scaling */ NIXAPI double getSIScaling(const std::string &originUnit, const std::string &destinationUnit); /** * Splits an SI unit into prefix, unit and the power components. * @param fullUnit * @param prefix * @param unit * @param power */ NIXAPI void splitUnit(const std::string &fullUnit, std::string &prefix, std::string &unit, std::string &power); /** * Splits a SI unit compound into its atomic parts. * * @param compoundUnit string representing an SI unit that consists of many atomic units * @param atomicUnits vector<string> that takes the atomic units */ NIXAPI void splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits); /** * Convert a number into a string representation. * * @param number The number to convert * * @return The string representation of number */ template<typename T> std::string numToStr(T number) { std::stringstream s; s << number; return s.str(); } /** * Convert a string representing a number into a number. * * @param str The string to convert. * * @return The number that was represented by the string. */ template<typename T> T strToNum(const std::string &str) { std::stringstream s(str); T number; return s >> number ? number : 0; } /** * Check whether a given type is of type "boost::optional" * Usage: * myBool = is_optional<decltype(myVar)>::value; * myBool = is_optional<MY_TYPE>::value; * * @param type Template param: The type to check. * * @return bool (use '::value' to check result) */ template<typename> struct is_optional : std::false_type {}; template<typename T> struct is_optional<boost::optional<T>> : std::true_type {}; /** * Optional de-referencing: * De-reference boost optional type if such given, returned var * unchanged otherwise. * * @param mixed The variable to de-reference. * * @return mixed */ template<typename T> T deRef(T var) { return var; } template<typename R> R deRef(boost::optional<R> var) { if(var) return *var; else return R(); } } // namespace util } // namespace nix #endif // NIX_UTIL_H <|endoftext|>
<commit_before>/* * Copyright 2010, * François Bleibel, * Olivier Stasse, * * CNRS/AIST * * This file is part of sot-core. * sot-core 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 3 of * the License, or (at your option) any later version. * sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __SOT_TIMER_HH #define __SOT_TIMER_HH /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* Classes standards. */ #include <list> /* Classe std::list */ #ifndef WIN32 #include <sys/time.h> #else /*WIN32*/ // When including Winsock2.h, the MAL must be included first #include <dynamic-graph/linear-algebra.h> #include <sot/core/utils-windows.hh> #include <Winsock2.h> #endif /*WIN32*/ /* SOT */ #include <dynamic-graph/entity.h> #include <dynamic-graph/all-signals.h> #include <sot/core/debug.hh> /* --------------------------------------------------------------------- */ /* --- API ------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ #if defined (WIN32) # if defined (timer_EXPORTS) # define Timer_EXPORT __declspec(dllexport) # else # define Timer_EXPORT __declspec(dllimport) # endif #else # define Timer_EXPORT #endif /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ namespace dg = dynamicgraph; template< class T > class Timer_EXPORT Timer :public dg::Entity { public: static const std::string CLASS_NAME; virtual const std::string& getClassName( void ) const { return CLASS_NAME; } protected: struct timeval t0,t1; double dt; public: /* --- CONSTRUCTION --- */ Timer( const std::string& name ); public: /* --- DISPLAY --- */ virtual void display( std::ostream& os ) const; Timer_EXPORT friend std::ostream& operator<< ( std::ostream& os,const Timer<T>& timer ) { timer.display(os); return os; } public: /* --- SIGNALS --- */ dg::SignalPtr<T,int> sigSIN; dg::SignalTimeDependent<T,int> sigSOUT; dg::Signal<double,int> timerSOUT; protected: /* --- SIGNAL FUNCTIONS --- */ void plug( dg::Signal<T,int> &sig ) { sigSIN = &sig; dt=0.; } T& compute( T& t,const int& time ) { sotDEBUGIN(15); gettimeofday(&t0,NULL); sotDEBUG(15) << "t0: "<< t0.tv_sec << " - " << t0.tv_usec << std::endl; t = sigSIN( time ); gettimeofday(&t1,NULL); dt = ( (t1.tv_sec-t0.tv_sec) * 1000. + (t1.tv_usec-t0.tv_usec+0.) / 1000. ); sotDEBUG(15) << "t1: "<< t1.tv_sec << " - " << t1.tv_usec << std::endl; timerSOUT = dt; timerSOUT.setTime (time); sotDEBUGOUT(15); return t; } double& getDt( double& res,const int& /*time*/ ) { res=dt; return res; } public: /* --- COMMANDS --- */ virtual void commandLine( const std::string& cmdLine,std::istringstream& cmdArgs, std::ostream& os ); }; void cmdChrono( const std::string& cmd, std::istringstream& args, std::ostream& os ); /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --- CONSTRUCTION ---------------------------------------------------- */ template< class T > Timer<T>:: Timer( const std::string& name ) :Entity(name) ,t0(),t1() ,dt(0.) ,sigSIN( NULL,"Timer("+name+")::input(T)::sin" ) ,sigSOUT( boost::bind(&Timer::compute,this,_1,_2), sigSIN, "Timer("+name+")::output(T)::sout" ) ,timerSOUT( "Timer("+name+")::output(double)::timer" ) { sotDEBUGIN(15); timerSOUT.setFunction( boost::bind(&Timer::getDt,this,_1,_2) ); signalRegistration( sigSIN<<sigSOUT<<timerSOUT ); sotDEBUGOUT(15); } /* --- DISPLAY --------------------------------------------------------- */ template< class T > void Timer<T>:: display( std::ostream& os ) const { os << "Timer <"<< sigSIN << "> : " << dt << "ms." << std::endl; } /* --- COMMAND --------------------------------------------------------- */ template< class T > void Timer<T>:: commandLine( const std::string& cmdLine,std::istringstream& cmdArgs, std::ostream& os ) { sotDEBUGIN(15); if( cmdLine == "help") { os << "Timer: "<<std::endl; Entity::commandLine( cmdLine,cmdArgs,os ); } else Entity::commandLine( cmdLine,cmdArgs,os ); sotDEBUGOUT(15); } #endif /* #ifndef __SOT_SOT_HH */ <commit_msg>Add ability to use clock instead of gettimeofday in entity Timer<commit_after>/* * Copyright 2010, * François Bleibel, * Olivier Stasse, * * CNRS/AIST * * This file is part of sot-core. * sot-core 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 3 of * the License, or (at your option) any later version. * sot-core 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 sot-core. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __SOT_TIMER_HH #define __SOT_TIMER_HH /* --------------------------------------------------------------------- */ /* --- INCLUDE --------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* Classes standards. */ #include <list> /* Classe std::list */ #ifndef WIN32 #include <sys/time.h> #else /*WIN32*/ // When including Winsock2.h, the MAL must be included first #include <dynamic-graph/linear-algebra.h> #include <sot/core/utils-windows.hh> #include <Winsock2.h> #endif /*WIN32*/ /* SOT */ #include <dynamic-graph/entity.h> #include <dynamic-graph/all-signals.h> #include <sot/core/debug.hh> /* --------------------------------------------------------------------- */ /* --- API ------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ #if defined (WIN32) # if defined (timer_EXPORTS) # define Timer_EXPORT __declspec(dllexport) # else # define Timer_EXPORT __declspec(dllimport) # endif #else # define Timer_EXPORT #endif /* --------------------------------------------------------------------- */ /* --- CLASS ----------------------------------------------------------- */ /* --------------------------------------------------------------------- */ namespace dg = dynamicgraph; template< class T > class Timer_EXPORT Timer :public dg::Entity { public: static const std::string CLASS_NAME; virtual const std::string& getClassName( void ) const { return CLASS_NAME; } protected: struct timeval t0,t1; clock_t c0, c1; double dt; public: /* --- CONSTRUCTION --- */ Timer( const std::string& name ); public: /* --- DISPLAY --- */ virtual void display( std::ostream& os ) const; Timer_EXPORT friend std::ostream& operator<< ( std::ostream& os,const Timer<T>& timer ) { timer.display(os); return os; } public: /* --- SIGNALS --- */ dg::SignalPtr<T,int> sigSIN; dg::SignalTimeDependent<T,int> sigSOUT; dg::SignalTimeDependent<T,int> sigClockSOUT; dg::Signal<double,int> timerSOUT; protected: /* --- SIGNAL FUNCTIONS --- */ void plug( dg::Signal<T,int> &sig ) { sigSIN = &sig; dt=0.; } template <bool UseClock> T& compute( T& t,const int& time ) { sotDEBUGIN(15); if (UseClock) { c0 = clock(); sotDEBUG(15) << "t0: "<< c0 << std::endl; } else { gettimeofday(&t0,NULL); sotDEBUG(15) << "t0: "<< t0.tv_sec << " - " << t0.tv_usec << std::endl; } t = sigSIN( time ); if (UseClock) { c1 = clock(); sotDEBUG(15) << "t1: "<< c0 << std::endl; dt = ((double)(c1 - c0) * 1000 ) / CLOCKS_PER_SEC; } else { gettimeofday(&t1,NULL); dt = ( (t1.tv_sec-t0.tv_sec) * 1000. + (t1.tv_usec-t0.tv_usec+0.) / 1000. ); sotDEBUG(15) << "t1: "<< t1.tv_sec << " - " << t1.tv_usec << std::endl; } timerSOUT = dt; timerSOUT.setTime (time); sotDEBUGOUT(15); return t; } double& getDt( double& res,const int& /*time*/ ) { res=dt; return res; } public: /* --- COMMANDS --- */ virtual void commandLine( const std::string& cmdLine,std::istringstream& cmdArgs, std::ostream& os ); }; void cmdChrono( const std::string& cmd, std::istringstream& args, std::ostream& os ); /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */ /* --- CONSTRUCTION ---------------------------------------------------- */ template< class T > Timer<T>:: Timer( const std::string& name ) :Entity(name) ,dt(0.) ,sigSIN( NULL,"Timer("+name+")::input(T)::sin" ) ,sigSOUT( boost::bind(&Timer::compute<false>,this,_1,_2), sigSIN, "Timer("+name+")::output(T)::sout" ) ,sigClockSOUT( boost::bind(&Timer::compute<true>,this,_1,_2), sigSIN, "Timer("+name+")::output(T)::sout" ) ,timerSOUT( "Timer("+name+")::output(double)::timer" ) { sotDEBUGIN(15); timerSOUT.setFunction( boost::bind(&Timer::getDt,this,_1,_2) ); signalRegistration( sigSIN<<sigSOUT<<sigClockSOUT<<timerSOUT ); sotDEBUGOUT(15); } /* --- DISPLAY --------------------------------------------------------- */ template< class T > void Timer<T>:: display( std::ostream& os ) const { os << "Timer <"<< sigSIN << "> : " << dt << "ms." << std::endl; } /* --- COMMAND --------------------------------------------------------- */ template< class T > void Timer<T>:: commandLine( const std::string& cmdLine,std::istringstream& cmdArgs, std::ostream& os ) { sotDEBUGIN(15); if( cmdLine == "help") { os << "Timer: "<<std::endl; Entity::commandLine( cmdLine,cmdArgs,os ); } else Entity::commandLine( cmdLine,cmdArgs,os ); sotDEBUGOUT(15); } #endif /* #ifndef __SOT_SOT_HH */ <|endoftext|>
<commit_before>#include <Mescaline/Audio/Synth.hpp> using namespace Mescaline::Audio; Synth::Synth( Environment& env , const SynthDef& synthDef , const NodeId& id , MescalineSynth* synth , size_t numAudioInputs , AudioInputConnection* audioInputConnections , size_t numAudioOutputs , AudioOutputConnection* audioOutputConnections , sample_t** audioBuffers ) : Node(env, id) , m_synthDef(synthDef) , m_synth(synth) , m_numAudioInputs(numAudioInputs) , m_numAudioOutputs(numAudioOutputs) , m_audioBuffers(audioBuffers) { for (size_t i=0; i < numAudioInputs; i++) { m_audioInputConnections.push_back(audioInputConnections[i]); } for (size_t i=0; i < numAudioOutputs; i++) { m_audioOutputConnections.push_back(audioOutputConnections[i]); } } Synth::~Synth() { // Call destructors } Synth* Synth::construct(Environment& env, const SynthDef& synthDef, const NodeId& id) { const Alignment bufferAlignment(Alignment::SIMDAlignment()); BOOST_ASSERT_MSG( bufferAlignment.isAligned(env.blockSize() * sizeof(sample_t)) , "blockSize must be aligned to Alignment::kSIMDAlignment" ); const size_t numAudioInputs = synthDef.numAudioInputs(); const size_t numAudioOutputs = synthDef.numAudioOutputs(); const size_t blockSize = env.blockSize(); const size_t synthAllocSize = sizeof(Synth) + synthDef.instanceSize(); const size_t audioInputOffset = synthAllocSize; const size_t audioInputAllocSize = numAudioInputs * sizeof(AudioInputConnection); const size_t audioOutputOffset = audioInputOffset + audioInputAllocSize; const size_t audioOutputAllocSize = numAudioOutputs * sizeof(AudioOutputConnection); const size_t audioBufferOffset = audioOutputOffset + audioOutputAllocSize; const size_t audioBufferAllocSize = (numAudioInputs + numAudioOutputs) * sizeof(sample_t*); const size_t bufferDataOffset = bufferAlignment.align(audioBufferOffset + audioBufferAllocSize); const size_t bufferDataAllocSize = (numAudioInputs + numAudioOutputs) * blockSize * sizeof(sample_t); const size_t allocSize = bufferDataOffset + bufferDataAllocSize; char* mem = env.rtMem().allocAligned<char>(bufferAlignment, allocSize); AudioInputConnection* audioInputConnections = (AudioInputConnection*)(mem + audioInputOffset); AudioOutputConnection* audioOutputConnections = (AudioOutputConnection*)(mem + audioOutputOffset); sample_t** audioInputBuffers = (sample_t**)(mem + audioBufferOffset); sample_t** audioOutputBuffers = audioInputBuffers + numAudioInputs; sample_t* inputBufferData = (sample_t*)(mem + bufferDataOffset); sample_t* outputBufferData = inputBufferData + numAudioInputs * blockSize; // Initialize shtuff for (size_t i=0; i < numAudioInputs; i++) { new (audioInputConnections + i) AudioInputConnection(i); audioInputBuffers[i] = inputBufferData + i * blockSize; } for (size_t i=0; i < numAudioOutputs; i++) { new (audioOutputConnections + i) AudioOutputConnection(i); audioOutputBuffers[i] = outputBufferData + i * blockSize; } MescalineSynth* synth = reinterpret_cast<MescalineSynth*>(mem + sizeof(Synth)); synthDef.construct(synth, 0, 0); return new (mem) Synth( env, synthDef, id, synth , numAudioInputs, audioInputConnections , numAudioOutputs, audioOutputConnections , audioInputBuffers ); } void Synth::free() { Node::free<Synth>(this); } template <typename BusId, typename ConnType> struct IfConnectionIndex { IfConnectionIndex(size_t index) : m_index(index) { } bool operator () (const Connection<BusId,ConnType>& conn) { return conn.index() == m_index; } size_t m_index; }; template <typename BusId, typename ConnType> struct SortByBusId { bool operator () (const Connection<BusId,ConnType>& a, const Connection<BusId,ConnType>& b) { return a.busId() < b.busId(); } }; // template <typename BusId, typename ConnType> // AudioInputConnection& conn connectionAt(size_t index) // { // return find_if(m_audioInputConnections.begin(), m_audioInputConnections.end(), IfConnectionIndex(index)); // } void Synth::mapInput(size_t index, const AudioBusId& bus, InputConnectionType type) { AudioInputConnections::iterator conn = find_if( m_audioInputConnections.begin() , m_audioInputConnections.end() , IfConnectionIndex<AudioBusId,InputConnectionType>(index) ); if (conn != m_audioInputConnections.end()) { if (conn->connect(bus, type)) { m_flags.set(kAudioInputConnectionsChanged); } } } void Synth::mapOutput(size_t index, const AudioBusId& bus, OutputConnectionType type) { size_t offset = sampleOffset(); sample_t* buffer = offset > 0 ? environment().rtMem().alloc<sample_t>(offset) : 0; AudioOutputConnections::iterator conn = find_if( m_audioOutputConnections.begin() , m_audioOutputConnections.end() , IfConnectionIndex<AudioBusId,OutputConnectionType>(index) ); if (conn != m_audioOutputConnections.end()) { conn->release(environment()); if (conn->connect(bus, type, offset, buffer)) { m_flags.set(kAudioOutputConnectionsChanged); } } } void Synth::process(size_t numFrames) { // Sort connections by bus id (if necessary) if (m_flags.test(kAudioInputConnectionsChanged)) { m_audioInputConnections.sort(SortByBusId<AudioBusId,InputConnectionType>()); m_flags.reset(kAudioInputConnectionsChanged); } if (m_flags.test(kAudioOutputConnectionsChanged)) { m_audioOutputConnections.sort(SortByBusId<AudioBusId,OutputConnectionType>()); m_flags.reset(kAudioOutputConnectionsChanged); } Environment& env = environment(); sample_t** inputBuffers = m_audioBuffers; sample_t** outputBuffers = m_audioBuffers + numAudioInputs(); for ( AudioInputConnections::iterator it = m_audioInputConnections.begin() ; it != m_audioInputConnections.end() ; it++ ) { it->read(env, numFrames, inputBuffers[it->index()]); } (*m_synth->fProcess)(m_synth, numFrames, inputBuffers, outputBuffers); for ( AudioOutputConnections::iterator it = m_audioOutputConnections.begin() ; it != m_audioOutputConnections.end() ; it++ ) { it->write(env, numFrames, outputBuffers[it->index()]); } } <commit_msg>Add comment about memory alignment<commit_after>#include <Mescaline/Audio/Synth.hpp> using namespace Mescaline::Audio; Synth::Synth( Environment& env , const SynthDef& synthDef , const NodeId& id , MescalineSynth* synth , size_t numAudioInputs , AudioInputConnection* audioInputConnections , size_t numAudioOutputs , AudioOutputConnection* audioOutputConnections , sample_t** audioBuffers ) : Node(env, id) , m_synthDef(synthDef) , m_synth(synth) , m_numAudioInputs(numAudioInputs) , m_numAudioOutputs(numAudioOutputs) , m_audioBuffers(audioBuffers) { for (size_t i=0; i < numAudioInputs; i++) { m_audioInputConnections.push_back(audioInputConnections[i]); } for (size_t i=0; i < numAudioOutputs; i++) { m_audioOutputConnections.push_back(audioOutputConnections[i]); } } Synth::~Synth() { // Call destructors } Synth* Synth::construct(Environment& env, const SynthDef& synthDef, const NodeId& id) { const Alignment bufferAlignment(Alignment::SIMDAlignment()); BOOST_ASSERT_MSG( bufferAlignment.isAligned(env.blockSize() * sizeof(sample_t)) , "blockSize must be aligned to Alignment::kSIMDAlignment" ); const size_t numAudioInputs = synthDef.numAudioInputs(); const size_t numAudioOutputs = synthDef.numAudioOutputs(); const size_t blockSize = env.blockSize(); const size_t synthAllocSize = sizeof(Synth) + synthDef.instanceSize(); const size_t audioInputOffset = synthAllocSize; const size_t audioInputAllocSize = numAudioInputs * sizeof(AudioInputConnection); const size_t audioOutputOffset = audioInputOffset + audioInputAllocSize; const size_t audioOutputAllocSize = numAudioOutputs * sizeof(AudioOutputConnection); const size_t audioBufferOffset = audioOutputOffset + audioOutputAllocSize; const size_t audioBufferAllocSize = (numAudioInputs + numAudioOutputs) * sizeof(sample_t*); const size_t bufferDataOffset = bufferAlignment.align(audioBufferOffset + audioBufferAllocSize); const size_t bufferDataAllocSize = (numAudioInputs + numAudioOutputs) * blockSize * sizeof(sample_t); const size_t allocSize = bufferDataOffset + bufferDataAllocSize; // Need to align the alloc'd memory here so the audio buffer memory turns out aligned, too. char* mem = env.rtMem().allocAligned<char>(bufferAlignment, allocSize); AudioInputConnection* audioInputConnections = (AudioInputConnection*)(mem + audioInputOffset); AudioOutputConnection* audioOutputConnections = (AudioOutputConnection*)(mem + audioOutputOffset); sample_t** audioInputBuffers = (sample_t**)(mem + audioBufferOffset); sample_t** audioOutputBuffers = audioInputBuffers + numAudioInputs; sample_t* inputBufferData = (sample_t*)(mem + bufferDataOffset); sample_t* outputBufferData = inputBufferData + numAudioInputs * blockSize; // Initialize shtuff for (size_t i=0; i < numAudioInputs; i++) { new (audioInputConnections + i) AudioInputConnection(i); audioInputBuffers[i] = inputBufferData + i * blockSize; } for (size_t i=0; i < numAudioOutputs; i++) { new (audioOutputConnections + i) AudioOutputConnection(i); audioOutputBuffers[i] = outputBufferData + i * blockSize; } MescalineSynth* synth = reinterpret_cast<MescalineSynth*>(mem + sizeof(Synth)); synthDef.construct(synth, 0, 0); return new (mem) Synth( env, synthDef, id, synth , numAudioInputs, audioInputConnections , numAudioOutputs, audioOutputConnections , audioInputBuffers ); } void Synth::free() { Node::free<Synth>(this); } template <typename BusId, typename ConnType> struct IfConnectionIndex { IfConnectionIndex(size_t index) : m_index(index) { } bool operator () (const Connection<BusId,ConnType>& conn) { return conn.index() == m_index; } size_t m_index; }; template <typename BusId, typename ConnType> struct SortByBusId { bool operator () (const Connection<BusId,ConnType>& a, const Connection<BusId,ConnType>& b) { return a.busId() < b.busId(); } }; // template <typename BusId, typename ConnType> // AudioInputConnection& conn connectionAt(size_t index) // { // return find_if(m_audioInputConnections.begin(), m_audioInputConnections.end(), IfConnectionIndex(index)); // } void Synth::mapInput(size_t index, const AudioBusId& bus, InputConnectionType type) { AudioInputConnections::iterator conn = find_if( m_audioInputConnections.begin() , m_audioInputConnections.end() , IfConnectionIndex<AudioBusId,InputConnectionType>(index) ); if (conn != m_audioInputConnections.end()) { if (conn->connect(bus, type)) { m_flags.set(kAudioInputConnectionsChanged); } } } void Synth::mapOutput(size_t index, const AudioBusId& bus, OutputConnectionType type) { size_t offset = sampleOffset(); sample_t* buffer = offset > 0 ? environment().rtMem().alloc<sample_t>(offset) : 0; AudioOutputConnections::iterator conn = find_if( m_audioOutputConnections.begin() , m_audioOutputConnections.end() , IfConnectionIndex<AudioBusId,OutputConnectionType>(index) ); if (conn != m_audioOutputConnections.end()) { conn->release(environment()); if (conn->connect(bus, type, offset, buffer)) { m_flags.set(kAudioOutputConnectionsChanged); } } } void Synth::process(size_t numFrames) { // Sort connections by bus id (if necessary) if (m_flags.test(kAudioInputConnectionsChanged)) { m_audioInputConnections.sort(SortByBusId<AudioBusId,InputConnectionType>()); m_flags.reset(kAudioInputConnectionsChanged); } if (m_flags.test(kAudioOutputConnectionsChanged)) { m_audioOutputConnections.sort(SortByBusId<AudioBusId,OutputConnectionType>()); m_flags.reset(kAudioOutputConnectionsChanged); } Environment& env = environment(); sample_t** inputBuffers = m_audioBuffers; sample_t** outputBuffers = m_audioBuffers + numAudioInputs(); for ( AudioInputConnections::iterator it = m_audioInputConnections.begin() ; it != m_audioInputConnections.end() ; it++ ) { it->read(env, numFrames, inputBuffers[it->index()]); } (*m_synth->fProcess)(m_synth, numFrames, inputBuffers, outputBuffers); for ( AudioOutputConnections::iterator it = m_audioOutputConnections.begin() ; it != m_audioOutputConnections.end() ; it++ ) { it->write(env, numFrames, outputBuffers[it->index()]); } } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/StoredValueRef.h" #include "clang/AST/Type.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; bool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = false; // Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::ExecutionContext(llvm::Module* m) : m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { assert(m && "llvm::Module must not be null!"); m_AtExitFuncs.reserve(256); InitializeBuilder(m); } // Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::~ExecutionContext() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // assert(m && "Module cannot be null"); // Note: Engine takes ownership of the module. llvm::EngineBuilder builder(m); std::string errMsg; builder.setErrorStr(&errMsg); builder.setOptLevel(llvm::CodeGenOpt::Less); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); // EngineBuilder uses default c'ted TargetOptions, too: llvm::TargetOptions TargetOpts; TargetOpts.NoFramePointerElim = 1; TargetOpts.JITEmitDebugInfo = 1; builder.setTargetOptions(TargetOpts); m_engine.reset(builder.create()); if (!m_engine) llvm::errs() << "cling::ExecutionContext::InitializeBuilder(): " << errMsg; assert(m_engine && "Cannot create module!"); // install lazy function creators m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } int ExecutionContext::CXAAtExit(void (*func) (void*), void* arg, void* dso, void* clangDecl) { // Register a CXAAtExit function clang::Decl* LastTLD = (clang::Decl*)clangDecl; m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, dso, LastTLD)); return 0; // happiness } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol, " "see previous error message!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "ExecutionContext: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } if (m_LazyFuncCreatorDiagsSuppressed) return 0; return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; if (funcsToFreeUnique.insert(func)) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } ExecutionContext::ExecutionResult ExecutionContext::executeFunction(llvm::StringRef funcname, const clang::ASTContext& Ctx, clang::QualType retType, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below if (!m_CxaAtExitRemapped) { // Rewire atexit: llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); if (atExit && clingAtExit) { void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } } // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: " "could not find function named " << funcname << '\n'; return kExeFunctionNotCompiled; } m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol '" << *i << "' unresolved while linking function '" << funcname << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); StoredValueRef aggregateRet; if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Allocate returnValue: aggregateRet = StoredValueRef::allocate(Ctx, retType, f->getReturnType()); if (returnValue) { *returnValue = aggregateRet; } else { returnValue = &aggregateRet; } args.push_back(returnValue->get().getGV()); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { llvm::GenericValue gvRet = m_engine->runFunction(f, args); // rescue the ret value (which might be aggregate) from the stack *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType)); } else { m_engine->runFunction(f, args); } return kExeSuccess; } ExecutionContext::ExecutionResult ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); if (m_RunningStaticInits) return kExeSuccess; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); if (InitList == 0) return kExeSuccess; m_RunningStaticInits = true; // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { m_engine->getPointerToFunction(F); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::runStaticInitializersOnce: symbol '" << *i << "' unresolved while linking static initializer '" << F->getName() << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); m_RunningStaticInits = false; return kExeUnresolvedSymbols; } m_engine->runFunction(F, std::vector<llvm::GenericValue>()); } } GV->eraseFromParent(); m_RunningStaticInits = false; return kExeSuccess; } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } // 'Unload' the cxa_atexit entities. for (size_t I = 0, E = m_AtExitFuncs.size(); I < E; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[E-I-1]; (*AEE.m_Func)(AEE.m_Arg); } m_AtExitFuncs.clear(); } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::errs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* ExecutionContext::getAddressOfGlobal(llvm::Module* m, const char* symbolName, bool* fromJIT /*=0*/) const { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); if (!gvar) return 0; address = m_engine->getPointerToGlobal(gvar); } return address; } <commit_msg>Fix crash seen in ROOT-5570.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/StoredValueRef.h" #include "clang/AST/Type.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; bool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = false; // Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::ExecutionContext(llvm::Module* m) : m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { assert(m && "llvm::Module must not be null!"); m_AtExitFuncs.reserve(256); InitializeBuilder(m); } // Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::~ExecutionContext() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // assert(m && "Module cannot be null"); // Note: Engine takes ownership of the module. llvm::EngineBuilder builder(m); std::string errMsg; builder.setErrorStr(&errMsg); builder.setOptLevel(llvm::CodeGenOpt::Less); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); // EngineBuilder uses default c'ted TargetOptions, too: llvm::TargetOptions TargetOpts; TargetOpts.NoFramePointerElim = 1; TargetOpts.JITEmitDebugInfo = 1; builder.setTargetOptions(TargetOpts); m_engine.reset(builder.create()); if (!m_engine) llvm::errs() << "cling::ExecutionContext::InitializeBuilder(): " << errMsg; assert(m_engine && "Cannot create module!"); // install lazy function creators m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } int ExecutionContext::CXAAtExit(void (*func) (void*), void* arg, void* dso, void* clangDecl) { // Register a CXAAtExit function clang::Decl* LastTLD = (clang::Decl*)clangDecl; m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, dso, LastTLD)); return 0; // happiness } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol, " "see previous error message!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "ExecutionContext: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } if (m_LazyFuncCreatorDiagsSuppressed) return 0; return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; if (!func) continue; if (funcsToFreeUnique.insert(func)) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } ExecutionContext::ExecutionResult ExecutionContext::executeFunction(llvm::StringRef funcname, const clang::ASTContext& Ctx, clang::QualType retType, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below if (!m_CxaAtExitRemapped) { // Rewire atexit: llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); if (atExit && clingAtExit) { void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } } // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: " "could not find function named " << funcname << '\n'; return kExeFunctionNotCompiled; } m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol '" << *i << "' unresolved while linking function '" << funcname << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); StoredValueRef aggregateRet; if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Allocate returnValue: aggregateRet = StoredValueRef::allocate(Ctx, retType, f->getReturnType()); if (returnValue) { *returnValue = aggregateRet; } else { returnValue = &aggregateRet; } args.push_back(returnValue->get().getGV()); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { llvm::GenericValue gvRet = m_engine->runFunction(f, args); // rescue the ret value (which might be aggregate) from the stack *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType)); } else { m_engine->runFunction(f, args); } return kExeSuccess; } ExecutionContext::ExecutionResult ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); if (m_RunningStaticInits) return kExeSuccess; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); if (InitList == 0) return kExeSuccess; m_RunningStaticInits = true; // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { m_engine->getPointerToFunction(F); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::runStaticInitializersOnce: symbol '" << *i << "' unresolved while linking static initializer '" << F->getName() << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); m_RunningStaticInits = false; return kExeUnresolvedSymbols; } m_engine->runFunction(F, std::vector<llvm::GenericValue>()); } } GV->eraseFromParent(); m_RunningStaticInits = false; return kExeSuccess; } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } // 'Unload' the cxa_atexit entities. for (size_t I = 0, E = m_AtExitFuncs.size(); I < E; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[E-I-1]; (*AEE.m_Func)(AEE.m_Arg); } m_AtExitFuncs.clear(); } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::errs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* ExecutionContext::getAddressOfGlobal(llvm::Module* m, const char* symbolName, bool* fromJIT /*=0*/) const { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); if (!gvar) return 0; address = m_engine->getPointerToGlobal(gvar); } return address; } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/StoredValueRef.h" #include "cling/Interpreter/Interpreter.h" // FIXME: Remove when at_exit is ready #include "clang/AST/Type.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; bool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = false; // Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::ExecutionContext(llvm::Module* m) : m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { assert(m && "llvm::Module must not be null!"); m_AtExitFuncs.reserve(256); InitializeBuilder(m); } // Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::~ExecutionContext() {} void ExecutionContext::shuttingDown() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void ExecutionContext::remapCXAAtExit() { assert(!m_CxaAtExitRemapped && "__cxa_at_exit already remapped."); llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); assert(atExit && clingAtExit && "atExit and clingAtExit must exist."); void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // assert(m && "Module cannot be null"); // Note: Engine takes ownership of the module. llvm::EngineBuilder builder(m); std::string errMsg; builder.setErrorStr(&errMsg); builder.setOptLevel(llvm::CodeGenOpt::Less); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); // EngineBuilder uses default c'ted TargetOptions, too: llvm::TargetOptions TargetOpts; TargetOpts.NoFramePointerElim = 1; TargetOpts.JITEmitDebugInfo = 1; builder.setTargetOptions(TargetOpts); m_engine.reset(builder.create()); if (!m_engine) llvm::errs() << "cling::ExecutionContext::InitializeBuilder(): " << errMsg; assert(m_engine && "Cannot create module!"); // install lazy function creators m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } int ExecutionContext::CXAAtExit(void (*func) (void*), void* arg, void* dso, void* clangDecl) { // Register a CXAAtExit function clang::Decl* LastTLD = (clang::Decl*)clangDecl; m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, dso, LastTLD)); return 0; // happiness } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol, " "see previous error message!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "ExecutionContext: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } if (m_LazyFuncCreatorDiagsSuppressed) return 0; return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func)) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } ExecutionContext::ExecutionResult ExecutionContext::executeFunction(llvm::StringRef funcname, const clang::ASTContext& Ctx, clang::QualType retType, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: " "could not find function named " << funcname << '\n'; return kExeFunctionNotCompiled; } m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol '" << *i << "' unresolved while linking function '" << funcname << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. if (ff) funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); StoredValueRef aggregateRet; if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Allocate returnValue: aggregateRet = StoredValueRef::allocate(Ctx, retType, f->getReturnType()); if (returnValue) { *returnValue = aggregateRet; } else { returnValue = &aggregateRet; } args.push_back(returnValue->get().getGV()); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { llvm::GenericValue gvRet = m_engine->runFunction(f, args); // rescue the ret value (which might be aggregate) from the stack *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType)); } else { m_engine->runFunction(f, args); } return kExeSuccess; } ExecutionContext::ExecutionResult ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); if (m_RunningStaticInits) return kExeSuccess; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); if (InitList == 0) return kExeSuccess; m_RunningStaticInits = true; // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { m_engine->getPointerToFunction(F); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::runStaticInitializersOnce: symbol '" << *i << "' unresolved while linking static initializer '" << F->getName() << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); m_RunningStaticInits = false; return kExeUnresolvedSymbols; } m_engine->runFunction(F, std::vector<llvm::GenericValue>()); } } GV->eraseFromParent(); m_RunningStaticInits = false; return kExeSuccess; } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } // 'Unload' the cxa_atexit entities. for (size_t I = 0, E = m_AtExitFuncs.size(); I < E; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[E-I-1]; (*AEE.m_Func)(AEE.m_Arg); } m_AtExitFuncs.clear(); } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::errs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* ExecutionContext::getAddressOfGlobal(llvm::Module* m, const char* symbolName, bool* fromJIT /*=0*/) const { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); if (!gvar) return 0; address = m_engine->getPointerToGlobal(gvar); } return address; } <commit_msg>If __cxa_atexit does not exist in teh module then add it.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "ExecutionContext.h" #include "cling/Interpreter/StoredValueRef.h" #include "cling/Interpreter/Interpreter.h" // FIXME: Remove when at_exit is ready #include "clang/AST/Type.h" #include "llvm/IR/Constants.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace cling; std::set<std::string> ExecutionContext::m_unresolvedSymbols; std::vector<ExecutionContext::LazyFunctionCreatorFunc_t> ExecutionContext::m_lazyFuncCreator; bool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = false; // Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::ExecutionContext(llvm::Module* m) : m_RunningStaticInits(false), m_CxaAtExitRemapped(false) { assert(m && "llvm::Module must not be null!"); m_AtExitFuncs.reserve(256); InitializeBuilder(m); } // Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine ExecutionContext::~ExecutionContext() {} void ExecutionContext::shuttingDown() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void ExecutionContext::remapCXAAtExit() { assert(!m_CxaAtExitRemapped && "__cxa_at_exit already remapped."); llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); assert(clingAtExit && "cling_cxa_atexit must exist."); llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); if (!atExit) { // Inject __cxa_atexit into module llvm::Type* retTy = 0; llvm::Type* voidPtrTy = 0; if (sizeof(int) == 4) { retTy = llvm::Type::getInt32Ty(llvm::getGlobalContext()); voidPtrTy = llvm::Type::getInt32PtrTy(llvm::getGlobalContext()); } else if (sizeof(int) == 8) { retTy = llvm::Type::getInt64Ty(llvm::getGlobalContext()); voidPtrTy = llvm::Type::getInt64PtrTy(llvm::getGlobalContext()); } else { assert(retTy && "Unsupported sizeof(int)!"); retTy = llvm::Type::getInt64Ty(llvm::getGlobalContext()); voidPtrTy = llvm::Type::getInt64PtrTy(llvm::getGlobalContext()); } llvm::SmallVector<llvm::Type*, 3> argTy; argTy.push_back(voidPtrTy); argTy.push_back(voidPtrTy); argTy.push_back(voidPtrTy); llvm::FunctionType* cxaatexitTy = llvm::FunctionType::get(retTy, argTy, false /*varArg*/); llvm::Function* atexitFunc = llvm::Function::Create(cxaatexitTy, llvm::GlobalValue::InternalLinkage, "__cxa_atexit", 0 /*module*/); m_engine->addGlobalMapping(atexitFunc, clingAtExit); } void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } void ExecutionContext::InitializeBuilder(llvm::Module* m) { // // Create an execution engine to use. // assert(m && "Module cannot be null"); // Note: Engine takes ownership of the module. llvm::EngineBuilder builder(m); std::string errMsg; builder.setErrorStr(&errMsg); builder.setOptLevel(llvm::CodeGenOpt::Less); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); // EngineBuilder uses default c'ted TargetOptions, too: llvm::TargetOptions TargetOpts; TargetOpts.NoFramePointerElim = 1; TargetOpts.JITEmitDebugInfo = 1; builder.setTargetOptions(TargetOpts); m_engine.reset(builder.create()); if (!m_engine) llvm::errs() << "cling::ExecutionContext::InitializeBuilder(): " << errMsg; assert(m_engine && "Cannot create module!"); // install lazy function creators m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } int ExecutionContext::CXAAtExit(void (*func) (void*), void* arg, void* dso, void* clangDecl) { // Register a CXAAtExit function clang::Decl* LastTLD = (clang::Decl*)clangDecl; m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, dso, LastTLD)); return 0; // happiness } void unresolvedSymbol() { // throw exception? llvm::errs() << "ExecutionContext: calling unresolved symbol, " "see previous error message!\n"; } void* ExecutionContext::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "ExecutionContext: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* ExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } if (m_LazyFuncCreatorDiagsSuppressed) return 0; return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func)) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } ExecutionContext::ExecutionResult ExecutionContext::executeFunction(llvm::StringRef funcname, const clang::ASTContext& Ctx, clang::QualType retType, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str()); if (!f) { llvm::errs() << "ExecutionContext::executeFunction: " "could not find function named " << funcname << '\n'; return kExeFunctionNotCompiled; } m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::executeFunction: symbol '" << *i << "' unresolved while linking function '" << funcname << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. if (ff) funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } std::vector<llvm::GenericValue> args; bool wantReturn = (returnValue); StoredValueRef aggregateRet; if (f->hasStructRetAttr()) { // Function expects to receive the storage for the returned aggregate as // first argument. Allocate returnValue: aggregateRet = StoredValueRef::allocate(Ctx, retType, f->getReturnType()); if (returnValue) { *returnValue = aggregateRet; } else { returnValue = &aggregateRet; } args.push_back(returnValue->get().getGV()); // will get set as arg0, must not assign. wantReturn = false; } if (wantReturn) { llvm::GenericValue gvRet = m_engine->runFunction(f, args); // rescue the ret value (which might be aggregate) from the stack *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType)); } else { m_engine->runFunction(f, args); } return kExeSuccess; } ExecutionContext::ExecutionResult ExecutionContext::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); if (m_RunningStaticInits) return kExeSuccess; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); if (InitList == 0) return kExeSuccess; m_RunningStaticInits = true; // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { m_engine->getPointerToFunction(F); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "ExecutionContext::runStaticInitializersOnce: symbol '" << *i << "' unresolved while linking static initializer '" << F->getName() << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); m_RunningStaticInits = false; return kExeUnresolvedSymbols; } m_engine->runFunction(F, std::vector<llvm::GenericValue>()); } } GV->eraseFromParent(); m_RunningStaticInits = false; return kExeSuccess; } void ExecutionContext::runStaticDestructorsOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* gdtors = m->getGlobalVariable("llvm.global_dtors", true); if (gdtors) { m_engine->runStaticConstructorsDestructors(true); } // 'Unload' the cxa_atexit entities. for (size_t I = 0, E = m_AtExitFuncs.size(); I < E; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[E-I-1]; (*AEE.m_Func)(AEE.m_Arg); } m_AtExitFuncs.clear(); } int ExecutionContext::verifyModule(llvm::Module* m) { // // Verify generated module. // bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction); if (mod_has_errs) { return 1; } return 0; } void ExecutionContext::printModule(llvm::Module* m) { // // Print module LLVM code in human-readable form. // llvm::PassManager PM; PM.add(llvm::createPrintModulePass(&llvm::errs())); PM.run(*m); } void ExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* ExecutionContext::getAddressOfGlobal(llvm::Module* m, const char* symbolName, bool* fromJIT /*=0*/) const { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); if (!gvar) return 0; address = m_engine->getPointerToGlobal(gvar); } return address; } <|endoftext|>
<commit_before>// Copyright (c) 2010 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 "views/controls/tabbed_pane/native_tabbed_pane_win.h" #include <vssym32.h> #include "app/l10n_util_win.h" #include "app/resource_bundle.h" #include "base/logging.h" #include "base/stl_util-inl.h" #include "gfx/canvas_skia.h" #include "gfx/font.h" #include "gfx/native_theme_win.h" #include "views/controls/tabbed_pane/tabbed_pane.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" namespace views { // A background object that paints the tab panel background which may be // rendered by the system visual styles system. class TabBackground : public Background { public: explicit TabBackground() { // TMT_FILLCOLORHINT returns a color value that supposedly // approximates the texture drawn by PaintTabPanelBackground. SkColor tab_page_color = gfx::NativeTheme::instance()->GetThemeColorWithDefault( gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT, COLOR_3DFACE); SetNativeControlColor(tab_page_color); } virtual ~TabBackground() {} virtual void Paint(gfx::Canvas* canvas, View* view) const { HDC dc = canvas->BeginPlatformPaint(); RECT r = {0, 0, view->width(), view->height()}; gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r); canvas->EndPlatformPaint(); } private: DISALLOW_COPY_AND_ASSIGN(TabBackground); }; // Custom layout manager that takes care of sizing and displaying the tab pages. class TabLayout : public LayoutManager { public: TabLayout() {} // Switches to the tab page identified by the given index. void SwitchToPage(View* host, View* page) { for (int i = 0; i < host->GetChildViewCount(); ++i) { View* child = host->GetChildViewAt(i); // The child might not have been laid out yet. if (child == page) child->SetBounds(gfx::Rect(host->size())); child->SetVisible(child == page); } } private: // LayoutManager overrides: virtual void Layout(View* host) { gfx::Rect bounds(host->size()); for (int i = 0; i < host->GetChildViewCount(); ++i) { View* child = host->GetChildViewAt(i); // We only layout visible children, since it may be expensive. if (child->IsVisible() && child->bounds() != bounds) child->SetBounds(bounds); } } virtual gfx::Size GetPreferredSize(View* host) { // First, query the preferred sizes to determine a good width. int width = 0; for (int i = 0; i < host->GetChildViewCount(); ++i) { View* page = host->GetChildViewAt(i); width = std::max(width, page->GetPreferredSize().width()); } // After we know the width, decide on the height. return gfx::Size(width, GetPreferredHeightForWidth(host, width)); } virtual int GetPreferredHeightForWidth(View* host, int width) { int height = 0; for (int i = 0; i < host->GetChildViewCount(); ++i) { View* page = host->GetChildViewAt(i); height = std::max(height, page->GetHeightForWidth(width)); } return height; } DISALLOW_COPY_AND_ASSIGN(TabLayout); }; //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, public: NativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane) : NativeControlWin(), tabbed_pane_(tabbed_pane), tab_layout_manager_(NULL), content_window_(NULL), selected_index_(-1) { // Associates the actual HWND with the tabbed-pane so the tabbed-pane is // the one considered as having the focus (not the wrapper) when the HWND is // focused directly (with a click for example). set_focus_view(tabbed_pane); } NativeTabbedPaneWin::~NativeTabbedPaneWin() { // We own the tab views, let's delete them. STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end()); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation: void NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) { AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true); } void NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title, View* contents, bool select_if_first_tab) { DCHECK(index <= static_cast<int>(tab_views_.size())); contents->set_parent_owned(false); contents->SetVisible(false); tab_views_.insert(tab_views_.begin() + index, contents); tab_titles_.insert(tab_titles_.begin() + index, title); if (!contents->background()) contents->set_background(new TabBackground); if (tab_views_.size() == 1 && select_if_first_tab) selected_index_ = 0; // Add native tab only if the native control is alreay created. if (content_window_) { AddNativeTab(index, title); // The newly added tab may have made the contents window smaller. ResizeContents(); RootView* content_root = content_window_->GetRootView(); content_root->AddChildView(contents); // Switch to the newly added tab if requested; if (tab_views_.size() == 1 && select_if_first_tab) tab_layout_manager_->SwitchToPage(content_root, contents); } } void NativeTabbedPaneWin::AddNativeTab(int index, const std::wstring &title) { TCITEM tcitem; tcitem.mask = TCIF_TEXT; // If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is // rendered properly on the tabs. if (base::i18n::IsRTL()) { tcitem.mask |= TCIF_RTLREADING; } tcitem.pszText = const_cast<wchar_t*>(title.c_str()); int result = TabCtrl_InsertItem(native_view(), index, &tcitem); DCHECK(result != -1); } View* NativeTabbedPaneWin::RemoveTabAtIndex(int index) { int tab_count = static_cast<int>(tab_views_.size()); DCHECK(index >= 0 && index < tab_count); if (index < (tab_count - 1)) { // Select the next tab. SelectTabAt(index + 1); } else { // We are the last tab, select the previous one. if (index > 0) { SelectTabAt(index - 1); } else if (content_window_) { // That was the last tab. Remove the contents. content_window_->GetRootView()->RemoveAllChildViews(false); } } TabCtrl_DeleteItem(native_view(), index); // The removed tab may have made the contents window bigger. if (content_window_) ResizeContents(); std::vector<View*>::iterator iter = tab_views_.begin() + index; View* removed_tab = *iter; if (content_window_) content_window_->GetRootView()->RemoveChildView(removed_tab); tab_views_.erase(iter); tab_titles_.erase(tab_titles_.begin() + index); return removed_tab; } void NativeTabbedPaneWin::SelectTabAt(int index) { DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size()))); if (native_view()) TabCtrl_SetCurSel(native_view(), index); DoSelectTabAt(index, true); } int NativeTabbedPaneWin::GetTabCount() { return TabCtrl_GetItemCount(native_view()); } int NativeTabbedPaneWin::GetSelectedTabIndex() { return TabCtrl_GetCurSel(native_view()); } View* NativeTabbedPaneWin::GetSelectedTab() { if (selected_index_ < 0) return NULL; return tab_views_[selected_index_]; } View* NativeTabbedPaneWin::GetView() { return this; } void NativeTabbedPaneWin::SetFocus() { // Focus the associated HWND. Focus(); } gfx::Size NativeTabbedPaneWin::GetPreferredSize() { if (!native_view()) return gfx::Size(); gfx::Rect contentSize(content_window_->GetRootView()->GetPreferredSize()); RECT paneSize = { 0, 0, contentSize.width(), contentSize.height() }; TabCtrl_AdjustRect(native_view(), TRUE, &paneSize); return gfx::Size(paneSize.right - paneSize.left, paneSize.bottom - paneSize.top); } gfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const { return native_view(); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, NativeControlWin override: void NativeTabbedPaneWin::CreateNativeControl() { // Create the tab control. // // Note that we don't follow the common convention for NativeControl // subclasses and we don't pass the value returned from // NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is // why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when // we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If // we do that, then the HWND we create for |content_window_| below will // inherit the WS_EX_LAYOUTRTL property and this will result in the contents // being flipped, which is not what we want (because we handle mirroring in // views without the use of Windows' support for mirroring). Therefore, // we initially create our HWND without WS_EX_LAYOUTRTL and we explicitly set // this property our child is created. This way, on RTL locales, our tabs // will be nicely rendered from right to left (by virtue of Windows doing the // right thing with the TabbedPane HWND) and each tab contents will use an // RTL layout correctly (by virtue of the mirroring infrastructure in views // doing the right thing with each View we put in the tab). DWORD style = WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | WS_CLIPCHILDREN; HWND tab_control = ::CreateWindowEx(0, WC_TABCONTROL, L"", style, 0, 0, width(), height(), GetWidget()->GetNativeView(), NULL, NULL, NULL); HFONT font = ResourceBundle::GetSharedInstance(). GetFont(ResourceBundle::BaseFont).hfont(); SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE); // Create the view container which is a child of the TabControl. content_window_ = new WidgetWin(); content_window_->Init(tab_control, gfx::Rect()); // Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above // for why we waited until |content_window_| is created before we set this // property for the tabbed pane's HWND). if (base::i18n::IsRTL()) l10n_util::HWNDSetRTLLayout(tab_control); RootView* root_view = content_window_->GetRootView(); tab_layout_manager_ = new TabLayout(); root_view->SetLayoutManager(tab_layout_manager_); DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT); SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color), GetBValue(sys_color)); root_view->set_background(Background::CreateSolidBackground(color)); content_window_->SetFocusTraversableParentView(this); NativeControlCreated(tab_control); // Add tabs that are already added if any. if (tab_views_.size() > 0) { InitializeTabs(); if (selected_index_ >= 0) DoSelectTabAt(selected_index_, false); } ResizeContents(); } bool NativeTabbedPaneWin::ProcessMessage(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { if (message == WM_NOTIFY && reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) { int selected_tab = TabCtrl_GetCurSel(native_view()); DCHECK(selected_tab != -1); DoSelectTabAt(selected_tab, true); return TRUE; } return NativeControlWin::ProcessMessage(message, w_param, l_param, result); } //////////////////////////////////////////////////////////////////////////////// // View override: void NativeTabbedPaneWin::Layout() { NativeControlWin::Layout(); ResizeContents(); } FocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() { return content_window_; } void NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add, View *parent, View *child) { NativeControlWin::ViewHierarchyChanged(is_add, parent, child); if (is_add && (child == this) && content_window_) { // We have been added to a view hierarchy, update the FocusTraversable // parent. content_window_->SetFocusTraversableParent(GetRootView()); } } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, private: void NativeTabbedPaneWin::InitializeTabs() { for (size_t i = 0; i < tab_titles_.size(); ++i) AddNativeTab(i, tab_titles_[i]); RootView* content_root = content_window_->GetRootView(); for (std::vector<View*>::iterator tab(tab_views_.begin()); tab != tab_views_.end(); ++tab) content_root->AddChildView(*tab); } void NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) { selected_index_ = index; if (content_window_) { RootView* content_root = content_window_->GetRootView(); // Clear the focus if the focused view was on the tab. FocusManager* focus_manager = GetFocusManager(); DCHECK(focus_manager); View* focused_view = focus_manager->GetFocusedView(); if (focused_view && content_root->IsParentOf(focused_view)) focus_manager->ClearFocus(); tab_layout_manager_->SwitchToPage(content_root, tab_views_.at(index)); } if (invoke_listener && tabbed_pane_->listener()) tabbed_pane_->listener()->TabSelectedAt(index); } void NativeTabbedPaneWin::ResizeContents() { CRect content_bounds; if (!GetClientRect(native_view(), &content_bounds)) return; TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds); content_window_->MoveWindow(content_bounds.left, content_bounds.top, content_bounds.Width(), content_bounds.Height(), TRUE); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWrapper, public: // static NativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper( TabbedPane* tabbed_pane) { return new NativeTabbedPaneWin(tabbed_pane); } } // namespace views <commit_msg>Fixes focus placement after using ctrl+tab in dialogs. BUG=48986 TEST=none Review URL: http://codereview.chromium.org/2948010<commit_after>// Copyright (c) 2010 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 "views/controls/tabbed_pane/native_tabbed_pane_win.h" #include <vssym32.h> #include "app/l10n_util_win.h" #include "app/resource_bundle.h" #include "base/logging.h" #include "base/stl_util-inl.h" #include "gfx/canvas_skia.h" #include "gfx/font.h" #include "gfx/native_theme_win.h" #include "views/controls/tabbed_pane/tabbed_pane.h" #include "views/fill_layout.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" namespace views { // A background object that paints the tab panel background which may be // rendered by the system visual styles system. class TabBackground : public Background { public: explicit TabBackground() { // TMT_FILLCOLORHINT returns a color value that supposedly // approximates the texture drawn by PaintTabPanelBackground. SkColor tab_page_color = gfx::NativeTheme::instance()->GetThemeColorWithDefault( gfx::NativeTheme::TAB, TABP_BODY, 0, TMT_FILLCOLORHINT, COLOR_3DFACE); SetNativeControlColor(tab_page_color); } virtual ~TabBackground() {} virtual void Paint(gfx::Canvas* canvas, View* view) const { HDC dc = canvas->BeginPlatformPaint(); RECT r = {0, 0, view->width(), view->height()}; gfx::NativeTheme::instance()->PaintTabPanelBackground(dc, &r); canvas->EndPlatformPaint(); } private: DISALLOW_COPY_AND_ASSIGN(TabBackground); }; // Custom layout manager that takes care of sizing and displaying the tab pages. class TabLayout : public LayoutManager { public: TabLayout() {} // Switches to the tab page identified by the given index. void SwitchToPage(View* host, View* page) { for (int i = 0; i < host->GetChildViewCount(); ++i) { View* child = host->GetChildViewAt(i); // The child might not have been laid out yet. if (child == page) child->SetBounds(gfx::Rect(host->size())); child->SetVisible(child == page); } FocusManager* focus_manager = page->GetFocusManager(); DCHECK(focus_manager); View* focused_view = focus_manager->GetFocusedView(); if (focused_view && host->IsParentOf(focused_view) && !page->IsParentOf(focused_view)) focus_manager->SetFocusedView(page); } private: // LayoutManager overrides: virtual void Layout(View* host) { gfx::Rect bounds(host->size()); for (int i = 0; i < host->GetChildViewCount(); ++i) { View* child = host->GetChildViewAt(i); // We only layout visible children, since it may be expensive. if (child->IsVisible() && child->bounds() != bounds) child->SetBounds(bounds); } } virtual gfx::Size GetPreferredSize(View* host) { // First, query the preferred sizes to determine a good width. int width = 0; for (int i = 0; i < host->GetChildViewCount(); ++i) { View* page = host->GetChildViewAt(i); width = std::max(width, page->GetPreferredSize().width()); } // After we know the width, decide on the height. return gfx::Size(width, GetPreferredHeightForWidth(host, width)); } virtual int GetPreferredHeightForWidth(View* host, int width) { int height = 0; for (int i = 0; i < host->GetChildViewCount(); ++i) { View* page = host->GetChildViewAt(i); height = std::max(height, page->GetHeightForWidth(width)); } return height; } DISALLOW_COPY_AND_ASSIGN(TabLayout); }; //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, public: NativeTabbedPaneWin::NativeTabbedPaneWin(TabbedPane* tabbed_pane) : NativeControlWin(), tabbed_pane_(tabbed_pane), tab_layout_manager_(NULL), content_window_(NULL), selected_index_(-1) { // Associates the actual HWND with the tabbed-pane so the tabbed-pane is // the one considered as having the focus (not the wrapper) when the HWND is // focused directly (with a click for example). set_focus_view(tabbed_pane); } NativeTabbedPaneWin::~NativeTabbedPaneWin() { // We own the tab views, let's delete them. STLDeleteContainerPointers(tab_views_.begin(), tab_views_.end()); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, NativeTabbedPaneWrapper implementation: void NativeTabbedPaneWin::AddTab(const std::wstring& title, View* contents) { AddTabAtIndex(static_cast<int>(tab_views_.size()), title, contents, true); } void NativeTabbedPaneWin::AddTabAtIndex(int index, const std::wstring& title, View* contents, bool select_if_first_tab) { DCHECK(index <= static_cast<int>(tab_views_.size())); contents->set_parent_owned(false); contents->SetVisible(false); tab_views_.insert(tab_views_.begin() + index, contents); tab_titles_.insert(tab_titles_.begin() + index, title); if (!contents->background()) contents->set_background(new TabBackground); if (tab_views_.size() == 1 && select_if_first_tab) selected_index_ = 0; // Add native tab only if the native control is alreay created. if (content_window_) { AddNativeTab(index, title); // The newly added tab may have made the contents window smaller. ResizeContents(); RootView* content_root = content_window_->GetRootView(); content_root->AddChildView(contents); // Switch to the newly added tab if requested; if (tab_views_.size() == 1 && select_if_first_tab) tab_layout_manager_->SwitchToPage(content_root, contents); } } void NativeTabbedPaneWin::AddNativeTab(int index, const std::wstring &title) { TCITEM tcitem; tcitem.mask = TCIF_TEXT; // If the locale is RTL, we set the TCIF_RTLREADING so that BiDi text is // rendered properly on the tabs. if (base::i18n::IsRTL()) { tcitem.mask |= TCIF_RTLREADING; } tcitem.pszText = const_cast<wchar_t*>(title.c_str()); int result = TabCtrl_InsertItem(native_view(), index, &tcitem); DCHECK(result != -1); } View* NativeTabbedPaneWin::RemoveTabAtIndex(int index) { int tab_count = static_cast<int>(tab_views_.size()); DCHECK(index >= 0 && index < tab_count); if (index < (tab_count - 1)) { // Select the next tab. SelectTabAt(index + 1); } else { // We are the last tab, select the previous one. if (index > 0) { SelectTabAt(index - 1); } else if (content_window_) { // That was the last tab. Remove the contents. content_window_->GetRootView()->RemoveAllChildViews(false); } } TabCtrl_DeleteItem(native_view(), index); // The removed tab may have made the contents window bigger. if (content_window_) ResizeContents(); std::vector<View*>::iterator iter = tab_views_.begin() + index; View* removed_tab = *iter; if (content_window_) content_window_->GetRootView()->RemoveChildView(removed_tab); tab_views_.erase(iter); tab_titles_.erase(tab_titles_.begin() + index); return removed_tab; } void NativeTabbedPaneWin::SelectTabAt(int index) { DCHECK((index >= 0) && (index < static_cast<int>(tab_views_.size()))); if (native_view()) TabCtrl_SetCurSel(native_view(), index); DoSelectTabAt(index, true); } int NativeTabbedPaneWin::GetTabCount() { return TabCtrl_GetItemCount(native_view()); } int NativeTabbedPaneWin::GetSelectedTabIndex() { return TabCtrl_GetCurSel(native_view()); } View* NativeTabbedPaneWin::GetSelectedTab() { if (selected_index_ < 0) return NULL; return tab_views_[selected_index_]; } View* NativeTabbedPaneWin::GetView() { return this; } void NativeTabbedPaneWin::SetFocus() { // Focus the associated HWND. Focus(); } gfx::Size NativeTabbedPaneWin::GetPreferredSize() { if (!native_view()) return gfx::Size(); gfx::Rect contentSize(content_window_->GetRootView()->GetPreferredSize()); RECT paneSize = { 0, 0, contentSize.width(), contentSize.height() }; TabCtrl_AdjustRect(native_view(), TRUE, &paneSize); return gfx::Size(paneSize.right - paneSize.left, paneSize.bottom - paneSize.top); } gfx::NativeView NativeTabbedPaneWin::GetTestingHandle() const { return native_view(); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, NativeControlWin override: void NativeTabbedPaneWin::CreateNativeControl() { // Create the tab control. // // Note that we don't follow the common convention for NativeControl // subclasses and we don't pass the value returned from // NativeControl::GetAdditionalExStyle() as the dwExStyle parameter. Here is // why: on RTL locales, if we pass NativeControl::GetAdditionalExStyle() when // we basically tell Windows to create our HWND with the WS_EX_LAYOUTRTL. If // we do that, then the HWND we create for |content_window_| below will // inherit the WS_EX_LAYOUTRTL property and this will result in the contents // being flipped, which is not what we want (because we handle mirroring in // views without the use of Windows' support for mirroring). Therefore, // we initially create our HWND without WS_EX_LAYOUTRTL and we explicitly set // this property our child is created. This way, on RTL locales, our tabs // will be nicely rendered from right to left (by virtue of Windows doing the // right thing with the TabbedPane HWND) and each tab contents will use an // RTL layout correctly (by virtue of the mirroring infrastructure in views // doing the right thing with each View we put in the tab). DWORD style = WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE | WS_CLIPCHILDREN; HWND tab_control = ::CreateWindowEx(0, WC_TABCONTROL, L"", style, 0, 0, width(), height(), GetWidget()->GetNativeView(), NULL, NULL, NULL); HFONT font = ResourceBundle::GetSharedInstance(). GetFont(ResourceBundle::BaseFont).hfont(); SendMessage(tab_control, WM_SETFONT, reinterpret_cast<WPARAM>(font), FALSE); // Create the view container which is a child of the TabControl. content_window_ = new WidgetWin(); content_window_->Init(tab_control, gfx::Rect()); // Explicitly setting the WS_EX_LAYOUTRTL property for the HWND (see above // for why we waited until |content_window_| is created before we set this // property for the tabbed pane's HWND). if (base::i18n::IsRTL()) l10n_util::HWNDSetRTLLayout(tab_control); RootView* root_view = content_window_->GetRootView(); tab_layout_manager_ = new TabLayout(); root_view->SetLayoutManager(tab_layout_manager_); DWORD sys_color = ::GetSysColor(COLOR_3DHILIGHT); SkColor color = SkColorSetRGB(GetRValue(sys_color), GetGValue(sys_color), GetBValue(sys_color)); root_view->set_background(Background::CreateSolidBackground(color)); content_window_->SetFocusTraversableParentView(this); NativeControlCreated(tab_control); // Add tabs that are already added if any. if (tab_views_.size() > 0) { InitializeTabs(); if (selected_index_ >= 0) DoSelectTabAt(selected_index_, false); } ResizeContents(); } bool NativeTabbedPaneWin::ProcessMessage(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { if (message == WM_NOTIFY && reinterpret_cast<LPNMHDR>(l_param)->code == TCN_SELCHANGE) { int selected_tab = TabCtrl_GetCurSel(native_view()); DCHECK(selected_tab != -1); DoSelectTabAt(selected_tab, true); return TRUE; } return NativeControlWin::ProcessMessage(message, w_param, l_param, result); } //////////////////////////////////////////////////////////////////////////////// // View override: void NativeTabbedPaneWin::Layout() { NativeControlWin::Layout(); ResizeContents(); } FocusTraversable* NativeTabbedPaneWin::GetFocusTraversable() { return content_window_; } void NativeTabbedPaneWin::ViewHierarchyChanged(bool is_add, View *parent, View *child) { NativeControlWin::ViewHierarchyChanged(is_add, parent, child); if (is_add && (child == this) && content_window_) { // We have been added to a view hierarchy, update the FocusTraversable // parent. content_window_->SetFocusTraversableParent(GetRootView()); } } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWin, private: void NativeTabbedPaneWin::InitializeTabs() { for (size_t i = 0; i < tab_titles_.size(); ++i) AddNativeTab(i, tab_titles_[i]); RootView* content_root = content_window_->GetRootView(); for (std::vector<View*>::iterator tab(tab_views_.begin()); tab != tab_views_.end(); ++tab) content_root->AddChildView(*tab); } void NativeTabbedPaneWin::DoSelectTabAt(int index, boolean invoke_listener) { selected_index_ = index; if (content_window_) { RootView* content_root = content_window_->GetRootView(); tab_layout_manager_->SwitchToPage(content_root, tab_views_.at(index)); } if (invoke_listener && tabbed_pane_->listener()) tabbed_pane_->listener()->TabSelectedAt(index); } void NativeTabbedPaneWin::ResizeContents() { CRect content_bounds; if (!GetClientRect(native_view(), &content_bounds)) return; TabCtrl_AdjustRect(native_view(), FALSE, &content_bounds); content_window_->MoveWindow(content_bounds.left, content_bounds.top, content_bounds.Width(), content_bounds.Height(), TRUE); } //////////////////////////////////////////////////////////////////////////////// // NativeTabbedPaneWrapper, public: // static NativeTabbedPaneWrapper* NativeTabbedPaneWrapper::CreateNativeWrapper( TabbedPane* tabbed_pane) { return new NativeTabbedPaneWin(tabbed_pane); } } // namespace views <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling -Xclang -verify // XFAIL: * // The test exposes a weakness in the declaration extraction of types. As // reported in issue ROOT-5248. class MyClass; //expected-note {{candidate found by name lookup is 'MyClass'}} extern MyClass* my; class MyClass { //expected-note {{candidate found by name lookup is 'MyClass'}} public: MyClass* getMyClass() { return 0; } } cl; // The next line should work without complaints! MyClass* my = cl.getMyClass(); //expected-error {{reference to 'MyClass' is ambiguous}} <commit_msg>Make it fail!<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling -Xclang -verify // XFAIL: * // The test exposes a weakness in the declaration extraction of types. As // reported in issue ROOT-5248. class MyClass; extern MyClass* my; class MyClass { public: MyClass* getMyClass() { return 0; } } cl; // The next line should work without complaints! MyClass* my = cl.getMyClass(); <|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_SEQUENCES_SET_HPP #define BOOST_BRIGAND_SEQUENCES_SET_HPP #include <brigand/types/type.hpp> #include <brigand/sequences/append.hpp> #include <brigand/sequences/list.hpp> #include <brigand/sequences/erase.hpp> #include <brigand/sequences/insert.hpp> #include <brigand/sequences/contains.hpp> namespace brigand { namespace detail { template<class... Ts> struct make_set; // Visual Studio helper template<class U, class K> struct set_erase_pred_impl { using type = list<U>; }; template<class K> struct set_erase_pred_impl<K,K> { using type = list<>; }; template <class... T> struct set_impl { template <typename K, typename = decltype(static_cast<type_<K>*>(static_cast<make_set<T...>*>(nullptr)))> static brigand::true_type contains(type_<K>); template <typename K> static brigand::false_type contains(K); template <typename K, typename = decltype(static_cast<type_<K>*>(static_cast<make_set<T...>*>(nullptr)))> static brigand::true_type has_key(type_<K>); template <typename K> static brigand::false_type has_key(K); template <class K> static append<set_impl<>, typename set_erase_pred_impl<T, K>::type...> erase(type_<K>); template<class K, class = decltype(static_cast<type_<K>*>(static_cast<make_set<T...>*>(nullptr)))> static set_impl insert(type_<K>); template<class K> static set_impl<T..., typename K::type> insert(K); }; // if you have a "class already a base" error message, it means you have defined a set with the same key present more // than once, which is an error template<class... Ts> struct make_set : type_<Ts>... { using type = set_impl<Ts...>; }; } template <typename... T> using set_wrapper = typename detail::make_set<T...>::type; template <typename L> using as_set = wrap<L, set_wrapper>; template<class... Ts> using set = typename detail::make_set<Ts...>::type; } #endif <commit_msg>Delete set.hpp<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/shared/mss_const.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @mss_const.H /// @This file contains constants for the memory team. /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_CONST_H_ #define _MSS_CONST_H_ #include <cstdint> namespace mss { enum sizes { PORTS_PER_MCS = 2, PORTS_PER_MCBIST = 4, MC_PER_MODULE = 2, MCBIST_PER_MC = 1, MAX_DIMM_PER_PORT = 2, MAX_RANK_PER_DIMM = 4, RANK_MID_POINT = 4, ///< Which rank number indicates the switch to the other DIMM DEFAULT_POLL_LIMIT = 10, ///< the number of poll attempts in the event we can't calculate another MAX_NUM_IMP = 4, ///< number of impedances valid per slew type MAX_NUM_CAL_SLEW_RATES = 4, ///< 3V/ns, 4V/ns, 5V/ns, 6V/n MAX_SLEW_VALUE = 15, ///< 4 bit value MAX_SUPPORTED_FREQUENCIES = 1, ///< Number of supported frequencies. Right now it's only 2400 BYTES_PER_GB = 1000000000, ///< Multiplier to go from GB to B T_PER_MT = 1000000, ///< Multiplier to go from MT/s to T/s // All need to be attributes - BRS // 48:51, 0b1100, (def_is_sim); # BIG_STEP = 12 (changed from default for SIM) // 48:51, 0b0000, any; # BIG_STEP = 0 SWyatt // #48:51, 0b0010, any; # BIG_STEP = 2 (default) // 52:54, 0b000, any; # SMALL_STEP = 0 (default) SWyatt //#52:54, 0b001, any; # SMALL_STEP = 1 (!! recommend setting to 0) // 55:60, 0b101010, any; # WR_PRE_DLY = 42 WR_LVL_BIG_STEP = 0b1100, WR_LVL_SMALL_STEP = 0b000, WR_LVL_PRE_DLY = 0b101010, WR_LVL_NUM_VALID_SAMPLES = 0x5, // THIS IS LIKELY INCORRECT - Should be defined in the DDR4 write centering protocol BRS // This field must be set to the larger of the two values in number of memory clock cycles. // FW_RD_WR = max(tWTR + 11, AL + tRTP + 3) WR_CNTR_FW_RD_WR = 0x11 + 4, WR_CNTR_FW_WR_RD = 0x0, // Attribute? BRS COARSE_CAL_STEP_SIZE = 0x4, CONSEQ_PASS = 0x8, }; enum times { CONVERT_PS_IN_A_NS = 1000, ///< 1000 pico in an nano CONVERT_PS_IN_A_US = 1000000, ///< 1000000 picos in a micro DELAY_1NS = 1, DELAY_10NS = 10 , ///< general purpose 10 ns delay for HW mode DELAY_100NS = 100, ///< general purpose 100 ns delay for HW mode DELAY_1US = 1000, ///< general purpose 1 usec delay for HW mode DELAY_100US = 100000, ///< general purpose 100 usec delay for HW mode DELAY_1MS = 1000000, ///< general purpose 1 ms delay for HW mode // From the DDR4spec 2400 speed - need to be changed to read attributes. BRS tWLO = 10, tWLOE = 2, SEC_IN_HOUR = 60 * 60, ///< seconds in an hour, used for scrub times BG_SCRUB_IN_HOURS = 12, CMD_TIMEBASE = 8192, ///< Represents the timebase multiplier for the MCBIST inter cmd gap }; enum states { LOW = 0, HIGH = 1, START = 1, STOP = 0, START_N = 0, STOP_N = 1, ON = 1, OFF = 0, ON_N = 0, OFF_N = 1, YES = 1, NO = 0, YES_N = 0, NO_N = 1, INVALID = 0xFF, // This needs to be an attribute I think - BRS. Used as a boolean. CAL_ABORT_ON_ERROR = 1, }; // Static consts describing the bits used in the cal_step_enable attribute // These are bit positions. 0 is the left most bit. enum cal_steps { EXT_ZQCAL = 0, WR_LEVEL = 1, DQS_ALIGN = 2, RDCLK_ALIGN = 3, READ_CTR = 4, READ_CTR_2D_VREF = 5, WRITE_CTR = 6, WRITE_CTR_2D_VREF = 7, COARSE_WR = 8, COARSE_RD = 9, }; // Static consts for DDR4 voltages used in p9_mss_volt enum voltages : uint64_t { DDR4_NOMINAL_VOLTAGE = 1200, DDR4_VPP_VOLTAGE = 2500, }; namespace mcbist { enum data_mode { // MCBIST test data modes FIXED_DATA_MODE = 0b000, RAND_FWD_MODE = 0b001, RAND_REV_MODE = 0b010, RAND_FWD_MAINT = 0b011, RAND_REV_MAINT = 0b100, DATA_EQ_ADDR = 0b101, ROTATE_LEFT_MODE = 0b110, ROTATE_RIGHT_MODE = 0b111, }; // 0:3 Operation Type enum op_type { WRITE = 0b0000, // fast, with no concurrent traffic READ = 0b0001, // fast, with no concurrent traffic READ_WRITE = 0b0010, WRITE_READ = 0b0011, READ_WRITE_READ = 0b0100, READ_WRITE_WRITE = 0b0101, RAND_SEQ = 0b0110, READ_READ_WRITE = 0b1000, SCRUB_RRWR = 0b1001, STEER_RW = 0b1010, ALTER = 0b1011, // (W) DISPLAY = 0b1100, // (R, slow) CCS_EXECUTE = 0b1111, // if bits 9:11 (Data Mode bits) = 000 (bits 4:8 used to specify which subtest to go to) // Refresh only cmd if bits 9:11 (Data Mode bits) /= 000 GOTO_SUBTEST_N = 0b0111, }; enum test_type { USER_MODE = 0, CENSHMOO = 1, SUREFAIL = 2, MEMWRITE = 3, MEMREAD = 4, CBR_REFRESH = 5, MCBIST_SHORT = 6, SHORT_SEQ = 7, DELTA_I = 8, DELTA_I_LOOP = 9, SHORT_RAND = 10, LONG1 = 11, BUS_TAT = 12, SIMPLE_FIX = 13, SIMPLE_RAND = 14, SIMPLE_RAND_2W = 15, SIMPLE_RAND_FIXD = 16, SIMPLE_RA_RD_WR = 17, SIMPLE_RA_RD_R = 18, SIMPLE_RA_FD_R = 19, SIMPLE_RA_FD_R_INF = 20, SIMPLE_SA_FD_R = 21, SIMPLE_RA_FD_W = 22, INFINITE = 23, WR_ONLY = 24, W_ONLY = 25, R_ONLY = 26, W_ONLY_RAND = 27, R_ONLY_RAND = 28, R_ONLY_MULTI = 29, SHORT = 30, SIMPLE_RAND_BARI = 31, W_R_INFINITE = 32, W_R_RAND_INFINITE = 33, R_INFINITE1 = 34, R_INFINITE_RF = 35, MARCH = 36, SIMPLE_FIX_RF = 37, SHMOO_STRESS = 38, SIMPLE_RAND_RA = 39, SIMPLE_FIX_RA = 40, SIMPLE_FIX_RF_RA = 41, TEST_RR = 42, TEST_RF = 43, W_ONLY_INFINITE_RAND = 44, MCB_2D_CUP_SEQ = 45, MCB_2D_CUP_RAND = 46, SHMOO_STRESS_INFINITE = 47, HYNIX_1_COL = 48, RMWFIX = 49, RMWFIX_I = 50, W_INFINITE = 51, R_INFINITE = 52, }; } // namespace mcbist enum class shmoo_edge : std::size_t { LEFT, RIGHT }; } // namespace mss #endif <commit_msg>Added access_delay_regs functionality to accessors<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/shared/mss_const.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @mss_const.H /// @This file contains constants for the memory team. /// // *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com> // *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_CONST_H_ #define _MSS_CONST_H_ #include <cstdint> namespace mss { enum sizes { PORTS_PER_MCS = 2, PORTS_PER_MCBIST = 4, MC_PER_MODULE = 2, MCBIST_PER_MC = 1, MAX_DIMM_PER_PORT = 2, MAX_RANK_PER_DIMM = 4, MAX_PRIMARY_RANKS_PER_PORT = 4, RANK_MID_POINT = 4, ///< Which rank number indicates the switch to the other DIMM DEFAULT_POLL_LIMIT = 10, ///< the number of poll attempts in the event we can't calculate another MAX_NUM_IMP = 4, ///< number of impedances valid per slew type MAX_NUM_CAL_SLEW_RATES = 4, ///< 3V/ns, 4V/ns, 5V/ns, 6V/n MAX_SLEW_VALUE = 15, ///< 4 bit value MAX_SUPPORTED_FREQUENCIES = 1, ///< Number of supported frequencies. Right now it's only 2400 BYTES_PER_GB = 1000000000, ///< Multiplier to go from GB to B T_PER_MT = 1000000, ///< Multiplier to go from MT/s to T/s // All need to be attributes - BRS // 48:51, 0b1100, (def_is_sim); # BIG_STEP = 12 (changed from default for SIM) // 48:51, 0b0000, any; # BIG_STEP = 0 SWyatt // #48:51, 0b0010, any; # BIG_STEP = 2 (default) // 52:54, 0b000, any; # SMALL_STEP = 0 (default) SWyatt //#52:54, 0b001, any; # SMALL_STEP = 1 (!! recommend setting to 0) // 55:60, 0b101010, any; # WR_PRE_DLY = 42 WR_LVL_BIG_STEP = 0b1100, WR_LVL_SMALL_STEP = 0b000, WR_LVL_PRE_DLY = 0b101010, WR_LVL_NUM_VALID_SAMPLES = 0x5, // THIS IS LIKELY INCORRECT - Should be defined in the DDR4 write centering protocol BRS // This field must be set to the larger of the two values in number of memory clock cycles. // FW_RD_WR = max(tWTR + 11, AL + tRTP + 3) WR_CNTR_FW_RD_WR = 0x11 + 4, WR_CNTR_FW_WR_RD = 0x0, // Attribute? BRS COARSE_CAL_STEP_SIZE = 0x4, CONSEQ_PASS = 0x8, }; enum times { CONVERT_PS_IN_A_NS = 1000, ///< 1000 pico in an nano CONVERT_PS_IN_A_US = 1000000, ///< 1000000 picos in a micro DELAY_1NS = 1, DELAY_10NS = 10 , ///< general purpose 10 ns delay for HW mode DELAY_100NS = 100, ///< general purpose 100 ns delay for HW mode DELAY_1US = 1000, ///< general purpose 1 usec delay for HW mode DELAY_100US = 100000, ///< general purpose 100 usec delay for HW mode DELAY_1MS = 1000000, ///< general purpose 1 ms delay for HW mode // From the DDR4spec 2400 speed - need to be changed to read attributes. BRS tWLO = 10, tWLOE = 2, SEC_IN_HOUR = 60 * 60, ///< seconds in an hour, used for scrub times BG_SCRUB_IN_HOURS = 12, CMD_TIMEBASE = 8192, ///< Represents the timebase multiplier for the MCBIST inter cmd gap }; enum states { LOW = 0, HIGH = 1, START = 1, STOP = 0, START_N = 0, STOP_N = 1, ON = 1, OFF = 0, ON_N = 0, OFF_N = 1, YES = 1, NO = 0, YES_N = 0, NO_N = 1, INVALID = 0xFF, // This needs to be an attribute I think - BRS. Used as a boolean. CAL_ABORT_ON_ERROR = 1, }; // Static consts describing the bits used in the cal_step_enable attribute // These are bit positions. 0 is the left most bit. enum cal_steps { EXT_ZQCAL = 0, WR_LEVEL = 1, DQS_ALIGN = 2, RDCLK_ALIGN = 3, READ_CTR = 4, READ_CTR_2D_VREF = 5, WRITE_CTR = 6, WRITE_CTR_2D_VREF = 7, COARSE_WR = 8, COARSE_RD = 9, }; // Static consts for DDR4 voltages used in p9_mss_volt enum voltages : uint64_t { DDR4_NOMINAL_VOLTAGE = 1200, DDR4_VPP_VOLTAGE = 2500, }; namespace mcbist { enum data_mode { // MCBIST test data modes FIXED_DATA_MODE = 0b000, RAND_FWD_MODE = 0b001, RAND_REV_MODE = 0b010, RAND_FWD_MAINT = 0b011, RAND_REV_MAINT = 0b100, DATA_EQ_ADDR = 0b101, ROTATE_LEFT_MODE = 0b110, ROTATE_RIGHT_MODE = 0b111, }; // 0:3 Operation Type enum op_type { WRITE = 0b0000, // fast, with no concurrent traffic READ = 0b0001, // fast, with no concurrent traffic READ_WRITE = 0b0010, WRITE_READ = 0b0011, READ_WRITE_READ = 0b0100, READ_WRITE_WRITE = 0b0101, RAND_SEQ = 0b0110, READ_READ_WRITE = 0b1000, SCRUB_RRWR = 0b1001, STEER_RW = 0b1010, ALTER = 0b1011, // (W) DISPLAY = 0b1100, // (R, slow) CCS_EXECUTE = 0b1111, // if bits 9:11 (Data Mode bits) = 000 (bits 4:8 used to specify which subtest to go to) // Refresh only cmd if bits 9:11 (Data Mode bits) /= 000 GOTO_SUBTEST_N = 0b0111, }; enum test_type { USER_MODE = 0, CENSHMOO = 1, SUREFAIL = 2, MEMWRITE = 3, MEMREAD = 4, CBR_REFRESH = 5, MCBIST_SHORT = 6, SHORT_SEQ = 7, DELTA_I = 8, DELTA_I_LOOP = 9, SHORT_RAND = 10, LONG1 = 11, BUS_TAT = 12, SIMPLE_FIX = 13, SIMPLE_RAND = 14, SIMPLE_RAND_2W = 15, SIMPLE_RAND_FIXD = 16, SIMPLE_RA_RD_WR = 17, SIMPLE_RA_RD_R = 18, SIMPLE_RA_FD_R = 19, SIMPLE_RA_FD_R_INF = 20, SIMPLE_SA_FD_R = 21, SIMPLE_RA_FD_W = 22, INFINITE = 23, WR_ONLY = 24, W_ONLY = 25, R_ONLY = 26, W_ONLY_RAND = 27, R_ONLY_RAND = 28, R_ONLY_MULTI = 29, SHORT = 30, SIMPLE_RAND_BARI = 31, W_R_INFINITE = 32, W_R_RAND_INFINITE = 33, R_INFINITE1 = 34, R_INFINITE_RF = 35, MARCH = 36, SIMPLE_FIX_RF = 37, SHMOO_STRESS = 38, SIMPLE_RAND_RA = 39, SIMPLE_FIX_RA = 40, SIMPLE_FIX_RF_RA = 41, TEST_RR = 42, TEST_RF = 43, W_ONLY_INFINITE_RAND = 44, MCB_2D_CUP_SEQ = 45, MCB_2D_CUP_RAND = 46, SHMOO_STRESS_INFINITE = 47, HYNIX_1_COL = 48, RMWFIX = 49, RMWFIX_I = 50, W_INFINITE = 51, R_INFINITE = 52, }; } // namespace mcbist enum class shmoo_edge : std::size_t { LEFT, RIGHT }; } // namespace mss #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/sbe/p9_get_sbe_msg_register.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p9_get_sbe_msg_register.C /// /// @brief Returns the SBE message register //------------------------------------------------------------------------------ // *HWP HW Owner : Santosh Puranik <santosh.puranik@in.ibm.com> // *HWP FW Owner : Dhruvaraj Subhash Chandran <dhruvaraj@in.ibm.com> // *HWP Team : SBE // *HWP Level : 2 // *HWP Consumed by : SE, Hostboot, Cronus //------------------------------------------------------------------------------ #include "p9_get_sbe_msg_register.H" #include "p9_perv_scom_addresses.H" fapi2::ReturnCode p9_get_sbe_msg_register(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_chip, sbeMsgReg_t& o_sbeReg) { fapi2::buffer<uint32_t> l_reg; FAPI_DBG("Entering ..."); FAPI_TRY(fapi2::getCfamRegister(i_chip, PERV_SB_MSG_FSI, l_reg)); o_sbeReg.reg = l_reg; FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <commit_msg>HWP L3 Delivery<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/sbe/p9_get_sbe_msg_register.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// @file p9_get_sbe_msg_register.C /// /// @brief Returns the SBE message register //------------------------------------------------------------------------------ // *HWP HW Owner : Santosh Puranik <santosh.puranik@in.ibm.com> // *HWP FW Owner : Dhruvaraj Subhash Chandran <dhruvaraj@in.ibm.com> // *HWP Team : SBE // *HWP Level : 3 // *HWP Consumed by : SE, Hostboot, Cronus //------------------------------------------------------------------------------ #include "p9_get_sbe_msg_register.H" #include "p9_perv_scom_addresses.H" fapi2::ReturnCode p9_get_sbe_msg_register(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_chip, sbeMsgReg_t& o_sbeReg) { fapi2::buffer<uint32_t> l_reg; FAPI_DBG("Entering ..."); FAPI_TRY(fapi2::getCfamRegister(i_chip, PERV_SB_MSG_FSI, l_reg)); o_sbeReg.reg = l_reg; FAPI_DBG("Exiting ..."); fapi_try_exit: return fapi2::current_err; } <|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/search_engines/search_terms_data.h" #include "base/logging.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/google/google_url_tracker.h" #include "googleurl/src/gurl.h" #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) #include "chrome/browser/rlz/rlz.h" #include "chrome/installer/util/google_update_settings.h" #endif SearchTermsData::SearchTermsData() { } SearchTermsData::~SearchTermsData() { } std::string SearchTermsData::GoogleBaseSuggestURLValue() const { // The suggest base URL we want at the end is something like // "http://clients1.google.TLD/complete/". The key bit we want from the // original Google base URL is the TLD. // Start with the Google base URL. const GURL base_url(GoogleBaseURLValue()); DCHECK(base_url.is_valid()); // Change "www." to "clients1." in the hostname. If no "www." was found, just // prepend "clients1.". const std::string base_host(base_url.host()); GURL::Replacements repl; const std::string suggest_host("clients1." + (base_host.compare(0, 4, "www.") ? base_host : base_host.substr(4))); repl.SetHostStr(suggest_host); // Replace any existing path with "/complete/". static const std::string suggest_path("/complete/"); repl.SetPathStr(suggest_path); // Clear the query and ref. repl.ClearQuery(); repl.ClearRef(); return base_url.ReplaceComponents(repl).spec(); } // static std::string* UIThreadSearchTermsData::google_base_url_ = NULL; UIThreadSearchTermsData::UIThreadSearchTermsData() { // GoogleURLTracker::GoogleURL() DCHECKs this also, but adding it here helps // us catch bad behavior at a more common place in this code. DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); } std::string UIThreadSearchTermsData::GoogleBaseURLValue() const { DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); return google_base_url_ ? (*google_base_url_) : GoogleURLTracker::GoogleURL().spec(); } std::string UIThreadSearchTermsData::GetApplicationLocale() const { DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); return g_browser_process->GetApplicationLocale(); } #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) string16 UIThreadSearchTermsData::GetRlzParameterValue() const { DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); string16 rlz_string; // For organic brandcodes do not use rlz at all. Empty brandcode usually // means a chromium install. This is ok. string16 brand; if (GoogleUpdateSettings::GetBrand(&brand) && !brand.empty() && !GoogleUpdateSettings::IsOrganic(brand)) { // This call will return false the first time(s) it is called until the // value has been cached. This normally would mean that at most one omnibox // search might not send the RLZ data but this is not really a problem. RLZTracker::GetAccessPointRlz(rlz_lib::CHROME_OMNIBOX, &rlz_string); } return rlz_string; } #endif // static void UIThreadSearchTermsData::SetGoogleBaseURL(std::string* google_base_url) { delete google_base_url_; google_base_url_ = google_base_url; } <commit_msg>Remove unneeded include statement.<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/search_engines/search_terms_data.h" #include "base/logging.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/google/google_url_tracker.h" #include "googleurl/src/gurl.h" #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) #include "chrome/browser/rlz/rlz.h" #include "chrome/installer/util/google_update_settings.h" #endif SearchTermsData::SearchTermsData() { } SearchTermsData::~SearchTermsData() { } std::string SearchTermsData::GoogleBaseSuggestURLValue() const { // The suggest base URL we want at the end is something like // "http://clients1.google.TLD/complete/". The key bit we want from the // original Google base URL is the TLD. // Start with the Google base URL. const GURL base_url(GoogleBaseURLValue()); DCHECK(base_url.is_valid()); // Change "www." to "clients1." in the hostname. If no "www." was found, just // prepend "clients1.". const std::string base_host(base_url.host()); GURL::Replacements repl; const std::string suggest_host("clients1." + (base_host.compare(0, 4, "www.") ? base_host : base_host.substr(4))); repl.SetHostStr(suggest_host); // Replace any existing path with "/complete/". static const std::string suggest_path("/complete/"); repl.SetPathStr(suggest_path); // Clear the query and ref. repl.ClearQuery(); repl.ClearRef(); return base_url.ReplaceComponents(repl).spec(); } // static std::string* UIThreadSearchTermsData::google_base_url_ = NULL; UIThreadSearchTermsData::UIThreadSearchTermsData() { // GoogleURLTracker::GoogleURL() DCHECKs this also, but adding it here helps // us catch bad behavior at a more common place in this code. DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); } std::string UIThreadSearchTermsData::GoogleBaseURLValue() const { DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); return google_base_url_ ? (*google_base_url_) : GoogleURLTracker::GoogleURL().spec(); } std::string UIThreadSearchTermsData::GetApplicationLocale() const { DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); return g_browser_process->GetApplicationLocale(); } #if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD) string16 UIThreadSearchTermsData::GetRlzParameterValue() const { DCHECK(!BrowserThread::IsWellKnownThread(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); string16 rlz_string; // For organic brandcodes do not use rlz at all. Empty brandcode usually // means a chromium install. This is ok. string16 brand; if (GoogleUpdateSettings::GetBrand(&brand) && !brand.empty() && !GoogleUpdateSettings::IsOrganic(brand)) { // This call will return false the first time(s) it is called until the // value has been cached. This normally would mean that at most one omnibox // search might not send the RLZ data but this is not really a problem. RLZTracker::GetAccessPointRlz(rlz_lib::CHROME_OMNIBOX, &rlz_string); } return rlz_string; } #endif // static void UIThreadSearchTermsData::SetGoogleBaseURL(std::string* google_base_url) { delete google_base_url_; google_base_url_ = google_base_url; } <|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/tab_contents/thumbnail_generator.h" #include <algorithm> #include "base/histogram.h" #include "base/time.h" #include "chrome/browser/renderer_host/backing_store.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/common/notification_service.h" #include "chrome/common/property_bag.h" #include "skia/ext/image_operations.h" #include "skia/ext/platform_canvas.h" #include "third_party/skia/include/core/SkBitmap.h" // Overview // -------- // This class provides current thumbnails for tabs. The simplest operation is // when a request for a thumbnail comes in, to grab the backing store and make // a smaller version of that. // // A complication happens because we don't always have nice backing stores for // all tabs (there is a cache of several tabs we'll keep backing stores for). // To get thumbnails for tabs with expired backing stores, we listen for // backing stores that are being thrown out, and generate thumbnails before // that happens. We attach them to the RenderWidgetHost via the property bag // so we can retrieve them later. When a tab has a live backing store again, // we throw away the thumbnail since it's now out-of-date. // // Another complication is performance. If the user brings up a tab switcher, we // don't want to get all 5 cached backing stores since it is a very large amount // of data. As a result, we generate thumbnails for tabs that are hidden even // if the backing store is still valid. This means we'll have to do a maximum // of generating thumbnails for the visible tabs at any point. // // The last performance consideration is when the user switches tabs quickly. // This can happen by doing Control-PageUp/Down or juct clicking quickly on // many different tabs (like when you're looking for one). We don't want to // slow this down by making thumbnails for each tab as it's hidden. Therefore, // we have a timer so that we don't invalidate thumbnails for tabs that are // only shown briefly (which would cause the thumbnail to be regenerated when // the tab is hidden). namespace { static const int kThumbnailWidth = 294; static const int kThumbnailHeight = 204; // Indicates the time that the RWH must be visible for us to update the // thumbnail on it. If the user holds down control enter, there will be a lot // of backing stores created and destroyed. WE don't want to interfere with // that. // // Any operation that happens within this time of being shown is ignored. // This means we won't throw the thumbnail away when the backing store is // painted in this time. static const int kVisibilitySlopMS = 3000; static const char kThumbnailHistogramName[] = "Thumbnail.ComputeMS"; struct WidgetThumbnail { SkBitmap thumbnail; // Indicates the last time the RWH was shown and hidden. base::TimeTicks last_shown; base::TimeTicks last_hidden; }; PropertyAccessor<WidgetThumbnail>* GetThumbnailAccessor() { static PropertyAccessor<WidgetThumbnail> accessor; return &accessor; } // Returns the existing WidgetThumbnail for a RVH, or creates a new one and // returns that if none exists. WidgetThumbnail* GetDataForHost(RenderWidgetHost* host) { WidgetThumbnail* wt = GetThumbnailAccessor()->GetProperty( host->property_bag()); if (wt) return wt; GetThumbnailAccessor()->SetProperty(host->property_bag(), WidgetThumbnail()); return GetThumbnailAccessor()->GetProperty(host->property_bag()); } #if defined(OS_WIN) // PlatformDevices/Canvases can't be copied like a regular SkBitmap (at least // on Windows). So the second parameter is the canvas to draw into. It should // be sized to the size of the backing store. void GetBitmapForBackingStore(BackingStore* backing_store, skia::PlatformCanvas* canvas) { HDC dc = canvas->beginPlatformPaint(); BitBlt(dc, 0, 0, backing_store->size().width(), backing_store->size().height(), backing_store->hdc(), 0, 0, SRCCOPY); canvas->endPlatformPaint(); } #endif // Creates a downsampled thumbnail for the given backing store. The returned // bitmap will be isNull if there was an error creating it. SkBitmap GetThumbnailForBackingStore(BackingStore* backing_store) { base::TimeTicks begin_compute_thumbnail = base::TimeTicks::Now(); SkBitmap result; // TODO(brettw) write this for other platforms. If you enable this, be sure // to also enable the unit tests for the same platform in // thumbnail_generator_unittest.cc #if defined(OS_WIN) // Get the bitmap as a Skia object so we can resample it. This is a large // allocation and we can tolerate failure here, so give up if the allocation // fails. skia::PlatformCanvas temp_canvas; if (!temp_canvas.initialize(backing_store->size().width(), backing_store->size().height(), true)) return result; GetBitmapForBackingStore(backing_store, &temp_canvas); // Get the bitmap out of the canvas and resample it. It would be nice if this // whole Windows-specific block could be put into a function, but the memory // management wouldn't work out because the bitmap is a PlatformDevice which // can't actually be copied. const SkBitmap& bmp = temp_canvas.getTopPlatformDevice().accessBitmap(false); #elif defined(OS_LINUX) SkBitmap bmp = backing_store->PaintRectToBitmap( gfx::Rect(0, 0, backing_store->size().width(), backing_store->size().height())); #elif defined(OS_MACOSX) SkBitmap bmp; NOTIMPLEMENTED(); #endif result = skia::ImageOperations::DownsampleByTwoUntilSize( bmp, kThumbnailWidth, kThumbnailHeight); #if defined(OS_WIN) // This is a bit subtle. SkBitmaps are refcounted, but the magic ones in // PlatformCanvas on Windows can't be ssigned to SkBitmap with proper // refcounting. If the bitmap doesn't change, then the downsampler will // return the input bitmap, which will be the reference to the weird // PlatformCanvas one insetad of a regular one. To get a regular refcounted // bitmap, we need to copy it. if (bmp.width() == result.width() && bmp.height() == result.height()) bmp.copyTo(&result, SkBitmap::kARGB_8888_Config); #endif HISTOGRAM_TIMES(kThumbnailHistogramName, base::TimeTicks::Now() - begin_compute_thumbnail); return result; } } // namespace ThumbnailGenerator::ThumbnailGenerator() : no_timeout_(false) { // The BrowserProcessImpl creates this non-lazily. If you add nontrivial // stuff here, be sure to convert it to being lazily created. // // We don't register for notifications here since BrowserProcessImpl creates // us before the NotificationService is. } ThumbnailGenerator::~ThumbnailGenerator() { } void ThumbnailGenerator::StartThumbnailing() { if (registrar_.IsEmpty()) { // Even though we deal in RenderWidgetHosts, we only care about its // subclass, RenderViewHost when it is in a tab. We don't make thumbnails // for RenderViewHosts that aren't in tabs, or RenderWidgetHosts that // aren't views like select popups. registrar_.Add(this, NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB, NotificationService::AllSources()); registrar_.Add(this, NotificationType::RENDER_WIDGET_VISIBILITY_CHANGED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); } } SkBitmap ThumbnailGenerator::GetThumbnailForRenderer( RenderWidgetHost* renderer) const { // Return a cached one if we have it and it's still valid. This will only be // valid when there used to be a backing store, but there isn't now. WidgetThumbnail* wt = GetDataForHost(renderer); if (!wt->thumbnail.isNull() && (no_timeout_ || base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) < wt->last_shown)) return wt->thumbnail; BackingStore* backing_store = renderer->GetBackingStore(false); if (!backing_store) return SkBitmap(); // Save this thumbnail in case we need to use it again soon. It will be // invalidated on the next paint. wt->thumbnail = GetThumbnailForBackingStore(backing_store); return wt->thumbnail; } void ThumbnailGenerator::WidgetWillDestroyBackingStore( RenderWidgetHost* widget, BackingStore* backing_store) { // Since the backing store is going away, we need to save it as a thumbnail. WidgetThumbnail* wt = GetDataForHost(widget); // If there is already a thumbnail on the RWH that's visible, it means that // not enough time has elapsed since being shown, and we can ignore generating // a new one. if (!wt->thumbnail.isNull()) return; // Save a scaled-down image of the page in case we're asked for the thumbnail // when there is no RenderViewHost. If this fails, we don't want to overwrite // an existing thumbnail. SkBitmap new_thumbnail = GetThumbnailForBackingStore(backing_store); if (!new_thumbnail.isNull()) wt->thumbnail = new_thumbnail; } void ThumbnailGenerator::WidgetDidUpdateBackingStore( RenderWidgetHost* widget) { // Clear the current thumbnail since it's no longer valid. WidgetThumbnail* wt = GetThumbnailAccessor()->GetProperty( widget->property_bag()); if (!wt) return; // Nothing to do. // If this operation is within the time slop after being shown, keep the // existing thumbnail. if (no_timeout_ || base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) < wt->last_shown) return; // TODO(brettw) schedule thumbnail generation for this renderer in // case we don't get a paint for it after the time slop, but it's // still visible. // Clear the thumbnail, since it's now out of date. wt->thumbnail = SkBitmap(); } void ThumbnailGenerator::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB: { // Install our observer for all new RVHs. RenderViewHost* renderer = Details<RenderViewHost>(details).ptr(); renderer->set_painting_observer(this); break; } case NotificationType::RENDER_WIDGET_VISIBILITY_CHANGED: if (*Details<bool>(details).ptr()) WidgetShown(Source<RenderWidgetHost>(source).ptr()); else WidgetHidden(Source<RenderWidgetHost>(source).ptr()); break; case NotificationType::RENDER_WIDGET_HOST_DESTROYED: WidgetDestroyed(Source<RenderWidgetHost>(source).ptr()); break; default: NOTREACHED(); } } void ThumbnailGenerator::WidgetShown(RenderWidgetHost* widget) { WidgetThumbnail* wt = GetDataForHost(widget); wt->last_shown = base::TimeTicks::Now(); // If there is no thumbnail (like we're displaying a background tab for the // first time), then we don't have do to invalidate the existing one. if (wt->thumbnail.isNull()) return; std::vector<RenderWidgetHost*>::iterator found = std::find(shown_hosts_.begin(), shown_hosts_.end(), widget); if (found != shown_hosts_.end()) { NOTREACHED() << "Showing a RWH we already think is shown"; shown_hosts_.erase(found); } shown_hosts_.push_back(widget); // Keep the old thumbnail for a small amount of time after the tab has been // shown. This is so in case it's hidden quickly again, we don't waste any // work regenerating it. if (timer_.IsRunning()) return; timer_.Start(base::TimeDelta::FromMilliseconds( no_timeout_ ? 0 : kVisibilitySlopMS), this, &ThumbnailGenerator::ShownDelayHandler); } void ThumbnailGenerator::WidgetHidden(RenderWidgetHost* widget) { WidgetThumbnail* wt = GetDataForHost(widget); wt->last_hidden = base::TimeTicks::Now(); // If the tab is on the list of ones to invalidate the thumbnail, we need to // remove it. EraseHostFromShownList(widget); // There may still be a valid cached thumbnail on the RWH, so we don't need to // make a new one. if (!wt->thumbnail.isNull()) return; wt->thumbnail = GetThumbnailForRenderer(widget); } void ThumbnailGenerator::WidgetDestroyed(RenderWidgetHost* widget) { EraseHostFromShownList(widget); } void ThumbnailGenerator::ShownDelayHandler() { base::TimeTicks threshold = base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS); // Check the list of all pending RWHs (normally only one) to see if any of // their times have expired. for (size_t i = 0; i < shown_hosts_.size(); i++) { WidgetThumbnail* wt = GetDataForHost(shown_hosts_[i]); if (no_timeout_ || wt->last_shown <= threshold) { // This thumbnail has expired, delete it. wt->thumbnail = SkBitmap(); shown_hosts_.erase(shown_hosts_.begin() + i); i--; } } // We need to schedule another run if there are still items in the list to // process. We use half the timeout for these re-runs to catch the items // that were added since the timer was run the first time. if (!shown_hosts_.empty()) { DCHECK(!no_timeout_); timer_.Start(base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) / 2, this, &ThumbnailGenerator::ShownDelayHandler); } } void ThumbnailGenerator::EraseHostFromShownList(RenderWidgetHost* widget) { std::vector<RenderWidgetHost*>::iterator found = std::find(shown_hosts_.begin(), shown_hosts_.end(), widget); if (found != shown_hosts_.end()) shown_hosts_.erase(found); } <commit_msg>Fix a bug generating thumbnails. We would only use a stashed thumbnail when it hadn't expired (5 seconds), even if there was no backing store. We now use the stashed one no matter what if there is no backing store to create a new one.<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/tab_contents/thumbnail_generator.h" #include <algorithm> #include "base/histogram.h" #include "base/time.h" #include "chrome/browser/renderer_host/backing_store.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/common/notification_service.h" #include "chrome/common/property_bag.h" #include "skia/ext/image_operations.h" #include "skia/ext/platform_canvas.h" #include "third_party/skia/include/core/SkBitmap.h" // Overview // -------- // This class provides current thumbnails for tabs. The simplest operation is // when a request for a thumbnail comes in, to grab the backing store and make // a smaller version of that. // // A complication happens because we don't always have nice backing stores for // all tabs (there is a cache of several tabs we'll keep backing stores for). // To get thumbnails for tabs with expired backing stores, we listen for // backing stores that are being thrown out, and generate thumbnails before // that happens. We attach them to the RenderWidgetHost via the property bag // so we can retrieve them later. When a tab has a live backing store again, // we throw away the thumbnail since it's now out-of-date. // // Another complication is performance. If the user brings up a tab switcher, we // don't want to get all 5 cached backing stores since it is a very large amount // of data. As a result, we generate thumbnails for tabs that are hidden even // if the backing store is still valid. This means we'll have to do a maximum // of generating thumbnails for the visible tabs at any point. // // The last performance consideration is when the user switches tabs quickly. // This can happen by doing Control-PageUp/Down or juct clicking quickly on // many different tabs (like when you're looking for one). We don't want to // slow this down by making thumbnails for each tab as it's hidden. Therefore, // we have a timer so that we don't invalidate thumbnails for tabs that are // only shown briefly (which would cause the thumbnail to be regenerated when // the tab is hidden). namespace { static const int kThumbnailWidth = 294; static const int kThumbnailHeight = 204; // Indicates the time that the RWH must be visible for us to update the // thumbnail on it. If the user holds down control enter, there will be a lot // of backing stores created and destroyed. WE don't want to interfere with // that. // // Any operation that happens within this time of being shown is ignored. // This means we won't throw the thumbnail away when the backing store is // painted in this time. static const int kVisibilitySlopMS = 3000; static const char kThumbnailHistogramName[] = "Thumbnail.ComputeMS"; struct WidgetThumbnail { SkBitmap thumbnail; // Indicates the last time the RWH was shown and hidden. base::TimeTicks last_shown; base::TimeTicks last_hidden; }; PropertyAccessor<WidgetThumbnail>* GetThumbnailAccessor() { static PropertyAccessor<WidgetThumbnail> accessor; return &accessor; } // Returns the existing WidgetThumbnail for a RVH, or creates a new one and // returns that if none exists. WidgetThumbnail* GetDataForHost(RenderWidgetHost* host) { WidgetThumbnail* wt = GetThumbnailAccessor()->GetProperty( host->property_bag()); if (wt) return wt; GetThumbnailAccessor()->SetProperty(host->property_bag(), WidgetThumbnail()); return GetThumbnailAccessor()->GetProperty(host->property_bag()); } #if defined(OS_WIN) // PlatformDevices/Canvases can't be copied like a regular SkBitmap (at least // on Windows). So the second parameter is the canvas to draw into. It should // be sized to the size of the backing store. void GetBitmapForBackingStore(BackingStore* backing_store, skia::PlatformCanvas* canvas) { HDC dc = canvas->beginPlatformPaint(); BitBlt(dc, 0, 0, backing_store->size().width(), backing_store->size().height(), backing_store->hdc(), 0, 0, SRCCOPY); canvas->endPlatformPaint(); } #endif // Creates a downsampled thumbnail for the given backing store. The returned // bitmap will be isNull if there was an error creating it. SkBitmap GetThumbnailForBackingStore(BackingStore* backing_store) { base::TimeTicks begin_compute_thumbnail = base::TimeTicks::Now(); SkBitmap result; // TODO(brettw) write this for other platforms. If you enable this, be sure // to also enable the unit tests for the same platform in // thumbnail_generator_unittest.cc #if defined(OS_WIN) // Get the bitmap as a Skia object so we can resample it. This is a large // allocation and we can tolerate failure here, so give up if the allocation // fails. skia::PlatformCanvas temp_canvas; if (!temp_canvas.initialize(backing_store->size().width(), backing_store->size().height(), true)) return result; GetBitmapForBackingStore(backing_store, &temp_canvas); // Get the bitmap out of the canvas and resample it. It would be nice if this // whole Windows-specific block could be put into a function, but the memory // management wouldn't work out because the bitmap is a PlatformDevice which // can't actually be copied. const SkBitmap& bmp = temp_canvas.getTopPlatformDevice().accessBitmap(false); #elif defined(OS_LINUX) SkBitmap bmp = backing_store->PaintRectToBitmap( gfx::Rect(0, 0, backing_store->size().width(), backing_store->size().height())); #elif defined(OS_MACOSX) SkBitmap bmp; NOTIMPLEMENTED(); #endif result = skia::ImageOperations::DownsampleByTwoUntilSize( bmp, kThumbnailWidth, kThumbnailHeight); #if defined(OS_WIN) // This is a bit subtle. SkBitmaps are refcounted, but the magic ones in // PlatformCanvas on Windows can't be ssigned to SkBitmap with proper // refcounting. If the bitmap doesn't change, then the downsampler will // return the input bitmap, which will be the reference to the weird // PlatformCanvas one insetad of a regular one. To get a regular refcounted // bitmap, we need to copy it. if (bmp.width() == result.width() && bmp.height() == result.height()) bmp.copyTo(&result, SkBitmap::kARGB_8888_Config); #endif HISTOGRAM_TIMES(kThumbnailHistogramName, base::TimeTicks::Now() - begin_compute_thumbnail); return result; } } // namespace ThumbnailGenerator::ThumbnailGenerator() : no_timeout_(false) { // The BrowserProcessImpl creates this non-lazily. If you add nontrivial // stuff here, be sure to convert it to being lazily created. // // We don't register for notifications here since BrowserProcessImpl creates // us before the NotificationService is. } ThumbnailGenerator::~ThumbnailGenerator() { } void ThumbnailGenerator::StartThumbnailing() { if (registrar_.IsEmpty()) { // Even though we deal in RenderWidgetHosts, we only care about its // subclass, RenderViewHost when it is in a tab. We don't make thumbnails // for RenderViewHosts that aren't in tabs, or RenderWidgetHosts that // aren't views like select popups. registrar_.Add(this, NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB, NotificationService::AllSources()); registrar_.Add(this, NotificationType::RENDER_WIDGET_VISIBILITY_CHANGED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DESTROYED, NotificationService::AllSources()); } } SkBitmap ThumbnailGenerator::GetThumbnailForRenderer( RenderWidgetHost* renderer) const { WidgetThumbnail* wt = GetDataForHost(renderer); BackingStore* backing_store = renderer->GetBackingStore(false); if (!backing_store) { // When we have no backing store, there's no choice in what to use. We // have to return either the existing thumbnail or the empty one if there // isn't a saved one. return wt->thumbnail; } // Now that we have a backing store, we have a choice to use it to make // a new thumbnail, or use a previously stashed one if we have it. // // Return the previously-computed one if we have it and it hasn't expired. if (!wt->thumbnail.isNull() && (no_timeout_ || base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) < wt->last_shown)) return wt->thumbnail; // Save this thumbnail in case we need to use it again soon. It will be // invalidated on the next paint. wt->thumbnail = GetThumbnailForBackingStore(backing_store); return wt->thumbnail; } void ThumbnailGenerator::WidgetWillDestroyBackingStore( RenderWidgetHost* widget, BackingStore* backing_store) { // Since the backing store is going away, we need to save it as a thumbnail. WidgetThumbnail* wt = GetDataForHost(widget); // If there is already a thumbnail on the RWH that's visible, it means that // not enough time has elapsed since being shown, and we can ignore generating // a new one. if (!wt->thumbnail.isNull()) return; // Save a scaled-down image of the page in case we're asked for the thumbnail // when there is no RenderViewHost. If this fails, we don't want to overwrite // an existing thumbnail. SkBitmap new_thumbnail = GetThumbnailForBackingStore(backing_store); if (!new_thumbnail.isNull()) wt->thumbnail = new_thumbnail; } void ThumbnailGenerator::WidgetDidUpdateBackingStore( RenderWidgetHost* widget) { // Clear the current thumbnail since it's no longer valid. WidgetThumbnail* wt = GetThumbnailAccessor()->GetProperty( widget->property_bag()); if (!wt) return; // Nothing to do. // If this operation is within the time slop after being shown, keep the // existing thumbnail. if (no_timeout_ || base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) < wt->last_shown) return; // TODO(brettw) schedule thumbnail generation for this renderer in // case we don't get a paint for it after the time slop, but it's // still visible. // Clear the thumbnail, since it's now out of date. wt->thumbnail = SkBitmap(); } void ThumbnailGenerator::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::RENDER_VIEW_HOST_CREATED_FOR_TAB: { // Install our observer for all new RVHs. RenderViewHost* renderer = Details<RenderViewHost>(details).ptr(); renderer->set_painting_observer(this); break; } case NotificationType::RENDER_WIDGET_VISIBILITY_CHANGED: if (*Details<bool>(details).ptr()) WidgetShown(Source<RenderWidgetHost>(source).ptr()); else WidgetHidden(Source<RenderWidgetHost>(source).ptr()); break; case NotificationType::RENDER_WIDGET_HOST_DESTROYED: WidgetDestroyed(Source<RenderWidgetHost>(source).ptr()); break; default: NOTREACHED(); } } void ThumbnailGenerator::WidgetShown(RenderWidgetHost* widget) { WidgetThumbnail* wt = GetDataForHost(widget); wt->last_shown = base::TimeTicks::Now(); // If there is no thumbnail (like we're displaying a background tab for the // first time), then we don't have do to invalidate the existing one. if (wt->thumbnail.isNull()) return; std::vector<RenderWidgetHost*>::iterator found = std::find(shown_hosts_.begin(), shown_hosts_.end(), widget); if (found != shown_hosts_.end()) { NOTREACHED() << "Showing a RWH we already think is shown"; shown_hosts_.erase(found); } shown_hosts_.push_back(widget); // Keep the old thumbnail for a small amount of time after the tab has been // shown. This is so in case it's hidden quickly again, we don't waste any // work regenerating it. if (timer_.IsRunning()) return; timer_.Start(base::TimeDelta::FromMilliseconds( no_timeout_ ? 0 : kVisibilitySlopMS), this, &ThumbnailGenerator::ShownDelayHandler); } void ThumbnailGenerator::WidgetHidden(RenderWidgetHost* widget) { WidgetThumbnail* wt = GetDataForHost(widget); wt->last_hidden = base::TimeTicks::Now(); // If the tab is on the list of ones to invalidate the thumbnail, we need to // remove it. EraseHostFromShownList(widget); // There may still be a valid cached thumbnail on the RWH, so we don't need to // make a new one. if (!wt->thumbnail.isNull()) return; wt->thumbnail = GetThumbnailForRenderer(widget); } void ThumbnailGenerator::WidgetDestroyed(RenderWidgetHost* widget) { EraseHostFromShownList(widget); } void ThumbnailGenerator::ShownDelayHandler() { base::TimeTicks threshold = base::TimeTicks::Now() - base::TimeDelta::FromMilliseconds(kVisibilitySlopMS); // Check the list of all pending RWHs (normally only one) to see if any of // their times have expired. for (size_t i = 0; i < shown_hosts_.size(); i++) { WidgetThumbnail* wt = GetDataForHost(shown_hosts_[i]); if (no_timeout_ || wt->last_shown <= threshold) { // This thumbnail has expired, delete it. wt->thumbnail = SkBitmap(); shown_hosts_.erase(shown_hosts_.begin() + i); i--; } } // We need to schedule another run if there are still items in the list to // process. We use half the timeout for these re-runs to catch the items // that were added since the timer was run the first time. if (!shown_hosts_.empty()) { DCHECK(!no_timeout_); timer_.Start(base::TimeDelta::FromMilliseconds(kVisibilitySlopMS) / 2, this, &ThumbnailGenerator::ShownDelayHandler); } } void ThumbnailGenerator::EraseHostFromShownList(RenderWidgetHost* widget) { std::vector<RenderWidgetHost*>::iterator found = std::find(shown_hosts_.begin(), shown_hosts_.end(), widget); if (found != shown_hosts_.end()) shown_hosts_.erase(found); } <|endoftext|>
<commit_before>/* Copyright 2017 The Apollo 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 "modules/map/hdmap/adapter/xml_parser/signals_xml_parser.h" #include <iomanip> #include <vector> #include <string> #include "modules/map/hdmap/adapter/xml_parser/util_xml_parser.h" #include "glog/logging.h" namespace apollo { namespace hdmap { namespace adapter { Status SignalsXmlParser::parse_traffic_lights( const tinyxml2::XMLElement& xml_node, std::vector<TrafficLightInternal>* traffic_lights) { CHECK_NOTNULL(traffic_lights); auto signal_node = xml_node.FirstChildElement("signal"); while (signal_node) { std::string object_type; std::string object_id; int checker = UtilXmlParser::query_string_attribute(*signal_node, "type", &object_type); checker += UtilXmlParser::query_string_attribute(*signal_node, "id", &object_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse signal type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } if (object_type == "trafficLight") { PbSignal traffic_light; traffic_light.mutable_id()->set_id(object_id); std::string layout_type; int checker = UtilXmlParser::query_string_attribute( *signal_node, "layoutType", &layout_type); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse signal layout type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbSignalType signal_layout_type; to_pb_signal_type(layout_type, &signal_layout_type); traffic_light.set_type(signal_layout_type); PbPolygon* polygon = traffic_light.mutable_boundary(); auto outline_node = signal_node->FirstChildElement("outline"); RETURN_IF_ERROR(UtilXmlParser::parse_outline(*outline_node, polygon)); auto sub_node = signal_node->FirstChildElement("subSignal"); if (sub_node == nullptr) { std::string err_msg = "Error parse sub signal."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } while (sub_node) { std::string sub_signal_id; std::string sub_signal_xml_type; checker = UtilXmlParser::query_string_attribute(*sub_node, "type", &sub_signal_xml_type); checker += UtilXmlParser::query_string_attribute(*sub_node, "id", &sub_signal_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse sub signal layout type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbSubSignal* sub_signal = traffic_light.add_subsignal(); PbSubSignalType sub_signal_type; to_pb_subsignal_type(sub_signal_xml_type, &sub_signal_type); sub_signal->mutable_id()->set_id(sub_signal_id); sub_signal->set_type(sub_signal_type); PbPoint3D* pt = sub_signal->mutable_location(); RETURN_IF_ERROR(UtilXmlParser::parse_point(*sub_node, pt)); sub_node = sub_node->NextSiblingElement("subSignal"); } TrafficLightInternal trafficlight_internal; trafficlight_internal.id = object_id; trafficlight_internal.traffic_light = traffic_light; sub_node = signal_node->FirstChildElement("stopline"); if (sub_node) { sub_node = sub_node->FirstChildElement("objectReference"); while (sub_node) { std::string stop_line_id; int checker = UtilXmlParser::query_string_attribute( *sub_node, "id", &stop_line_id); assert(checker == tinyxml2::XML_SUCCESS); trafficlight_internal.stop_line_ids.insert(stop_line_id); sub_node = sub_node->NextSiblingElement("objectReference"); } } traffic_lights->emplace_back(trafficlight_internal); } signal_node = signal_node->NextSiblingElement("signal"); } return Status::OK(); } Status SignalsXmlParser::to_pb_signal_type(const std::string& xml_type, PbSignalType* signal_type) { CHECK_NOTNULL(signal_type); std::string upper_str = UtilXmlParser::to_upper(xml_type); if (upper_str == "UNKNOWN") { *signal_type = ::apollo::hdmap::Signal::UNKNOWN; } else if (upper_str == "MIX2HORIZONTAL") { *signal_type = ::apollo::hdmap::Signal::MIX_2_HORIZONTAL; } else if (upper_str == "MIX2VERTICAL") { *signal_type = ::apollo::hdmap::Signal::MIX_2_VERTICAL; } else if (upper_str == "MIX3HORIZONTAL") { *signal_type = ::apollo::hdmap::Signal::MIX_3_HORIZONTAL; } else if (upper_str == "MIX3VERTICAL") { *signal_type = ::apollo::hdmap::Signal::MIX_3_VERTICAL; } else if (upper_str == "SINGLE") { *signal_type = ::apollo::hdmap::Signal::SINGLE; } else { std::string err_msg = "Error or unsupport signal layout type"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } Status SignalsXmlParser::to_pb_subsignal_type(const std::string& xml_type, PbSubSignalType* sub_signal_type) { CHECK_NOTNULL(sub_signal_type); std::string upper_str = UtilXmlParser::to_upper(xml_type); if (upper_str == "UNKNOWN") { *sub_signal_type = ::apollo::hdmap::Subsignal::UNKNOWN; } else if (upper_str == "CIRCLE") { *sub_signal_type = ::apollo::hdmap::Subsignal::CIRCLE; } else if (upper_str == "ARROWLEFT") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_LEFT; } else if (upper_str == "ARROWFORWARD") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_FORWARD; } else if (upper_str == "ARROWRIGHT") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_RIGHT; } else if (upper_str == "ARROWLEFTANDFORWARD") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_LEFT_AND_FORWARD; } else if (upper_str == "ARROWRIGHTANDFORWARD") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_RIGHT_AND_FORWARD; } else if (upper_str == "ARROWUTURN") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_U_TURN; } else { std::string err_msg = "Error or unsupport sub signal type"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } Status SignalsXmlParser::parse_stop_signs(const tinyxml2::XMLElement& xml_node, std::vector<StopSignInternal>* stop_signs) { CHECK_NOTNULL(stop_signs); auto signal_node = xml_node.FirstChildElement("signal"); while (signal_node) { std::string object_type; std::string object_id; int checker = UtilXmlParser::query_string_attribute(*signal_node, "type", &object_type); checker += UtilXmlParser::query_string_attribute(*signal_node, "id", &object_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse signal type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } if (object_type == "stopSign") { PbStopSign stop_sign; stop_sign.mutable_id()->set_id(object_id); StopSignInternal stop_sign_internal; stop_sign_internal.stop_sign = stop_sign; auto sub_node = signal_node->FirstChildElement("stopline"); if (sub_node) { sub_node = sub_node->FirstChildElement("objectReference"); while (sub_node) { std::string stop_line_id; UtilXmlParser::query_string_attribute( *sub_node, "id", &stop_line_id); CHECK(checker == tinyxml2::XML_SUCCESS); stop_sign_internal.stop_line_ids.insert(stop_line_id); sub_node = sub_node->NextSiblingElement("objectReference"); } } stop_signs->emplace_back(stop_sign_internal); } signal_node = signal_node->NextSiblingElement("signal"); } return Status::OK(); } Status SignalsXmlParser::parse_yield_signs(const tinyxml2::XMLElement& xml_node, std::vector<YieldSignInternal>* yield_signs) { CHECK_NOTNULL(yield_signs); auto signal_node = xml_node.FirstChildElement("signal"); while (signal_node) { std::string object_type; std::string object_id; int checker = UtilXmlParser::query_string_attribute(*signal_node, "type", &object_type); checker += UtilXmlParser::query_string_attribute(*signal_node, "id", &object_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse signal type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } if (object_type == "yieldSign") { PbYieldSign yield_sign; yield_sign.mutable_id()->set_id(object_id); YieldSignInternal yield_sign_internal; yield_sign_internal.id = object_id; yield_sign_internal.yield_sign = yield_sign; auto sub_node = signal_node->FirstChildElement("stopline"); if (sub_node) { sub_node = sub_node->FirstChildElement("objectReference"); while (sub_node) { std::string stop_line_id; int checker = UtilXmlParser::query_string_attribute( *sub_node, "id", &stop_line_id); CHECK(checker == tinyxml2::XML_SUCCESS); yield_sign_internal.stop_line_ids.insert(stop_line_id); sub_node = sub_node->NextSiblingElement("objectReference"); } } yield_signs->emplace_back(yield_sign_internal); } signal_node = signal_node->NextSiblingElement("signal"); } return Status::OK(); } } // namespace adapter } // namespace hdmap } // namespace apollo <commit_msg>map: fix compile warning in -c opt mode.<commit_after>/* Copyright 2017 The Apollo 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 "modules/map/hdmap/adapter/xml_parser/signals_xml_parser.h" #include <iomanip> #include <vector> #include <string> #include "modules/map/hdmap/adapter/xml_parser/util_xml_parser.h" #include "glog/logging.h" namespace apollo { namespace hdmap { namespace adapter { Status SignalsXmlParser::parse_traffic_lights( const tinyxml2::XMLElement& xml_node, std::vector<TrafficLightInternal>* traffic_lights) { CHECK_NOTNULL(traffic_lights); auto signal_node = xml_node.FirstChildElement("signal"); while (signal_node) { std::string object_type; std::string object_id; int checker = UtilXmlParser::query_string_attribute(*signal_node, "type", &object_type); checker += UtilXmlParser::query_string_attribute(*signal_node, "id", &object_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse signal type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } if (object_type == "trafficLight") { PbSignal traffic_light; traffic_light.mutable_id()->set_id(object_id); std::string layout_type; int checker = UtilXmlParser::query_string_attribute( *signal_node, "layoutType", &layout_type); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse signal layout type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbSignalType signal_layout_type; to_pb_signal_type(layout_type, &signal_layout_type); traffic_light.set_type(signal_layout_type); PbPolygon* polygon = traffic_light.mutable_boundary(); auto outline_node = signal_node->FirstChildElement("outline"); RETURN_IF_ERROR(UtilXmlParser::parse_outline(*outline_node, polygon)); auto sub_node = signal_node->FirstChildElement("subSignal"); if (sub_node == nullptr) { std::string err_msg = "Error parse sub signal."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } while (sub_node) { std::string sub_signal_id; std::string sub_signal_xml_type; checker = UtilXmlParser::query_string_attribute(*sub_node, "type", &sub_signal_xml_type); checker += UtilXmlParser::query_string_attribute(*sub_node, "id", &sub_signal_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse sub signal layout type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbSubSignal* sub_signal = traffic_light.add_subsignal(); PbSubSignalType sub_signal_type; to_pb_subsignal_type(sub_signal_xml_type, &sub_signal_type); sub_signal->mutable_id()->set_id(sub_signal_id); sub_signal->set_type(sub_signal_type); PbPoint3D* pt = sub_signal->mutable_location(); RETURN_IF_ERROR(UtilXmlParser::parse_point(*sub_node, pt)); sub_node = sub_node->NextSiblingElement("subSignal"); } TrafficLightInternal trafficlight_internal; trafficlight_internal.id = object_id; trafficlight_internal.traffic_light = traffic_light; sub_node = signal_node->FirstChildElement("stopline"); if (sub_node) { sub_node = sub_node->FirstChildElement("objectReference"); while (sub_node) { std::string stop_line_id; int checker = UtilXmlParser::query_string_attribute( *sub_node, "id", &stop_line_id); CHECK(checker == tinyxml2::XML_SUCCESS); trafficlight_internal.stop_line_ids.insert(stop_line_id); sub_node = sub_node->NextSiblingElement("objectReference"); } } traffic_lights->emplace_back(trafficlight_internal); } signal_node = signal_node->NextSiblingElement("signal"); } return Status::OK(); } Status SignalsXmlParser::to_pb_signal_type(const std::string& xml_type, PbSignalType* signal_type) { CHECK_NOTNULL(signal_type); std::string upper_str = UtilXmlParser::to_upper(xml_type); if (upper_str == "UNKNOWN") { *signal_type = ::apollo::hdmap::Signal::UNKNOWN; } else if (upper_str == "MIX2HORIZONTAL") { *signal_type = ::apollo::hdmap::Signal::MIX_2_HORIZONTAL; } else if (upper_str == "MIX2VERTICAL") { *signal_type = ::apollo::hdmap::Signal::MIX_2_VERTICAL; } else if (upper_str == "MIX3HORIZONTAL") { *signal_type = ::apollo::hdmap::Signal::MIX_3_HORIZONTAL; } else if (upper_str == "MIX3VERTICAL") { *signal_type = ::apollo::hdmap::Signal::MIX_3_VERTICAL; } else if (upper_str == "SINGLE") { *signal_type = ::apollo::hdmap::Signal::SINGLE; } else { std::string err_msg = "Error or unsupport signal layout type"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } Status SignalsXmlParser::to_pb_subsignal_type(const std::string& xml_type, PbSubSignalType* sub_signal_type) { CHECK_NOTNULL(sub_signal_type); std::string upper_str = UtilXmlParser::to_upper(xml_type); if (upper_str == "UNKNOWN") { *sub_signal_type = ::apollo::hdmap::Subsignal::UNKNOWN; } else if (upper_str == "CIRCLE") { *sub_signal_type = ::apollo::hdmap::Subsignal::CIRCLE; } else if (upper_str == "ARROWLEFT") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_LEFT; } else if (upper_str == "ARROWFORWARD") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_FORWARD; } else if (upper_str == "ARROWRIGHT") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_RIGHT; } else if (upper_str == "ARROWLEFTANDFORWARD") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_LEFT_AND_FORWARD; } else if (upper_str == "ARROWRIGHTANDFORWARD") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_RIGHT_AND_FORWARD; } else if (upper_str == "ARROWUTURN") { *sub_signal_type = ::apollo::hdmap::Subsignal::ARROW_U_TURN; } else { std::string err_msg = "Error or unsupport sub signal type"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } Status SignalsXmlParser::parse_stop_signs(const tinyxml2::XMLElement& xml_node, std::vector<StopSignInternal>* stop_signs) { CHECK_NOTNULL(stop_signs); auto signal_node = xml_node.FirstChildElement("signal"); while (signal_node) { std::string object_type; std::string object_id; int checker = UtilXmlParser::query_string_attribute(*signal_node, "type", &object_type); checker += UtilXmlParser::query_string_attribute(*signal_node, "id", &object_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse signal type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } if (object_type == "stopSign") { PbStopSign stop_sign; stop_sign.mutable_id()->set_id(object_id); StopSignInternal stop_sign_internal; stop_sign_internal.stop_sign = stop_sign; auto sub_node = signal_node->FirstChildElement("stopline"); if (sub_node) { sub_node = sub_node->FirstChildElement("objectReference"); while (sub_node) { std::string stop_line_id; UtilXmlParser::query_string_attribute( *sub_node, "id", &stop_line_id); CHECK(checker == tinyxml2::XML_SUCCESS); stop_sign_internal.stop_line_ids.insert(stop_line_id); sub_node = sub_node->NextSiblingElement("objectReference"); } } stop_signs->emplace_back(stop_sign_internal); } signal_node = signal_node->NextSiblingElement("signal"); } return Status::OK(); } Status SignalsXmlParser::parse_yield_signs(const tinyxml2::XMLElement& xml_node, std::vector<YieldSignInternal>* yield_signs) { CHECK_NOTNULL(yield_signs); auto signal_node = xml_node.FirstChildElement("signal"); while (signal_node) { std::string object_type; std::string object_id; int checker = UtilXmlParser::query_string_attribute(*signal_node, "type", &object_type); checker += UtilXmlParser::query_string_attribute(*signal_node, "id", &object_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse signal type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } if (object_type == "yieldSign") { PbYieldSign yield_sign; yield_sign.mutable_id()->set_id(object_id); YieldSignInternal yield_sign_internal; yield_sign_internal.id = object_id; yield_sign_internal.yield_sign = yield_sign; auto sub_node = signal_node->FirstChildElement("stopline"); if (sub_node) { sub_node = sub_node->FirstChildElement("objectReference"); while (sub_node) { std::string stop_line_id; int checker = UtilXmlParser::query_string_attribute( *sub_node, "id", &stop_line_id); CHECK(checker == tinyxml2::XML_SUCCESS); yield_sign_internal.stop_line_ids.insert(stop_line_id); sub_node = sub_node->NextSiblingElement("objectReference"); } } yield_signs->emplace_back(yield_sign_internal); } signal_node = signal_node->NextSiblingElement("signal"); } return Status::OK(); } } // namespace adapter } // namespace hdmap } // namespace apollo <|endoftext|>
<commit_before><commit_msg>Make it compile<commit_after><|endoftext|>
<commit_before># pragma once # include <Siv3D.hpp> # include "AscMessageManager.hpp" namespace asc { using namespace s3d; class Novel { private: std::unique_ptr<MessageManager> m_messageManager; public: Novel() : m_messageManager(std::make_unique<MessageManager>()) {} virtual ~Novel() = default; void start(int32 seekPoint) { switch (seekPoint) { case 0: m_messageManager->setName(L"0: O"); m_messageManager->setText(L"͈sځB\n͓s"); break; case 1: m_messageManager->setName(L"1: O"); m_messageManager->setText(L"PseLXg"); break; default: m_messageManager->setText(L"eLXĝݍXV"); break; } m_messageManager->start(); } void update() { m_messageManager->update(); } void draw() const { m_messageManager->draw(); } }; }<commit_msg>Add m_scenarioCommands in AscNovel<commit_after># pragma once # include <Siv3D.hpp> # include "AscMessageManager.hpp" # include "AscScenarioCommand.hpp" # include "AscScenarioCommands.hpp" namespace asc { using namespace s3d; class Novel { private: std::unique_ptr<MessageManager> m_messageManager; Array<std::unique_ptr<ScenarioCommand>> m_scenarioCommands; public: Novel() : m_messageManager(std::make_unique<MessageManager>()) { m_scenarioCommands.push_back(std::make_unique<WriteText>(m_messageManager.get(), L"0: Write Text")); m_scenarioCommands.push_back(std::make_unique<WriteText>(m_messageManager.get(), L"1: Write Text")); m_scenarioCommands.push_back(std::make_unique<WriteText>(m_messageManager.get(), L"2: Write Text")); } virtual ~Novel() = default; void start(int32 seekPoint) { m_scenarioCommands[seekPoint]->execute(); } void update() { m_messageManager->update(); } void draw() const { m_messageManager->draw(); } }; }<|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include <algorithm> #include <seastar/core/thread.hh> #include <seastar/tests/test-utils.hh> #include "utils/logalloc.hh" #include "utils/managed_ref.hh" #include "utils/managed_bytes.hh" #include "log.hh" [[gnu::unused]] static auto x = [] { logging::logger_registry().set_all_loggers_level(logging::log_level::debug); return 0; }(); using namespace logalloc; SEASTAR_TEST_CASE(test_compaction) { return seastar::async([] { region reg; with_allocator(reg.allocator(), [] { std::vector<managed_ref<int>> _allocated; // Allocate several segments for (int i = 0; i < 32 * 1024 * 4; i++) { _allocated.push_back(make_managed<int>()); } // Free 1/3 randomly std::random_shuffle(_allocated.begin(), _allocated.end()); auto it = _allocated.begin(); size_t nr_freed = _allocated.size() / 3; for (size_t i = 0; i < nr_freed; ++i) { *it++ = {}; } // Try to reclaim size_t target = sizeof(managed<int>) * nr_freed; BOOST_REQUIRE(shard_tracker().reclaim(target) >= target); }); }); } SEASTAR_TEST_CASE(test_compaction_with_multiple_regions) { return seastar::async([] { region reg1; region reg2; std::vector<managed_ref<int>> allocated1; std::vector<managed_ref<int>> allocated2; int count = 32 * 1024 * 4; with_allocator(reg1.allocator(), [&] { for (int i = 0; i < count; i++) { allocated1.push_back(make_managed<int>()); } }); with_allocator(reg2.allocator(), [&] { for (int i = 0; i < count; i++) { allocated2.push_back(make_managed<int>()); } }); size_t quarter = shard_tracker().occupancy().total_space() / 4; // Can't reclaim anything yet BOOST_REQUIRE(shard_tracker().reclaim(quarter) == 0); // Free 60% from the second pool // Shuffle, so that we don't free whole segments back to the pool // and there's nothing to reclaim. std::random_shuffle(allocated2.begin(), allocated2.end()); with_allocator(reg2.allocator(), [&] { auto it = allocated2.begin(); for (size_t i = 0; i < (count * 0.6); ++i) { *it++ = {}; } }); BOOST_REQUIRE(shard_tracker().reclaim(quarter) >= quarter); BOOST_REQUIRE(shard_tracker().reclaim(quarter) < quarter); // Free 60% from the first pool std::random_shuffle(allocated1.begin(), allocated1.end()); with_allocator(reg1.allocator(), [&] { auto it = allocated1.begin(); for (size_t i = 0; i < (count * 0.6); ++i) { *it++ = {}; } }); BOOST_REQUIRE(shard_tracker().reclaim(quarter) >= quarter); BOOST_REQUIRE(shard_tracker().reclaim(quarter) < quarter); with_allocator(reg2.allocator(), [&] () mutable { allocated2.clear(); }); with_allocator(reg1.allocator(), [&] () mutable { allocated1.clear(); }); }); } SEASTAR_TEST_CASE(test_mixed_type_compaction) { return seastar::async([] { static bool a_moved = false; static bool b_moved = false; static bool c_moved = false; static bool a_destroyed = false; static bool b_destroyed = false; static bool c_destroyed = false; struct A { uint8_t v = 0xca; A() = default; A(A&&) noexcept { a_moved = true; } ~A() { BOOST_REQUIRE(v == 0xca); a_destroyed = true; } }; struct B { uint16_t v = 0xcafe; B() = default; B(B&&) noexcept { b_moved = true; } ~B() { BOOST_REQUIRE(v == 0xcafe); b_destroyed = true; } }; struct C { uint64_t v = 0xcafebabe; C() = default; C(C&&) noexcept { c_moved = true; } ~C() { BOOST_REQUIRE(v == 0xcafebabe); c_destroyed = true; } }; region reg; with_allocator(reg.allocator(), [&] { { std::vector<int*> objs; auto p1 = make_managed<A>(); int junk_count = 10; for (int i = 0; i < junk_count; i++) { objs.push_back(reg.allocator().construct<int>(i)); } auto p2 = make_managed<B>(); for (int i = 0; i < junk_count; i++) { objs.push_back(reg.allocator().construct<int>(i)); } auto p3 = make_managed<C>(); for (auto&& p : objs) { reg.allocator().destroy(p); } reg.full_compaction(); BOOST_REQUIRE(a_moved); BOOST_REQUIRE(b_moved); BOOST_REQUIRE(c_moved); BOOST_REQUIRE(a_destroyed); BOOST_REQUIRE(b_destroyed); BOOST_REQUIRE(c_destroyed); a_destroyed = false; b_destroyed = false; c_destroyed = false; } BOOST_REQUIRE(a_destroyed); BOOST_REQUIRE(b_destroyed); BOOST_REQUIRE(c_destroyed); }); }); } SEASTAR_TEST_CASE(test_blob) { return seastar::async([] { region reg; with_allocator(reg.allocator(), [&] { auto src = bytes("123456"); managed_bytes b(src); BOOST_REQUIRE(bytes_view(b) == src); reg.full_compaction(); BOOST_REQUIRE(bytes_view(b) == src); }); }); } <commit_msg>tests: lsa: Add test for region merging<commit_after>/* * Copyright 2015 Cloudius Systems */ #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include <algorithm> #include <seastar/core/thread.hh> #include <seastar/tests/test-utils.hh> #include "utils/logalloc.hh" #include "utils/managed_ref.hh" #include "utils/managed_bytes.hh" #include "log.hh" [[gnu::unused]] static auto x = [] { logging::logger_registry().set_all_loggers_level(logging::log_level::debug); return 0; }(); using namespace logalloc; SEASTAR_TEST_CASE(test_compaction) { return seastar::async([] { region reg; with_allocator(reg.allocator(), [] { std::vector<managed_ref<int>> _allocated; // Allocate several segments for (int i = 0; i < 32 * 1024 * 4; i++) { _allocated.push_back(make_managed<int>()); } // Free 1/3 randomly std::random_shuffle(_allocated.begin(), _allocated.end()); auto it = _allocated.begin(); size_t nr_freed = _allocated.size() / 3; for (size_t i = 0; i < nr_freed; ++i) { *it++ = {}; } // Try to reclaim size_t target = sizeof(managed<int>) * nr_freed; BOOST_REQUIRE(shard_tracker().reclaim(target) >= target); }); }); } SEASTAR_TEST_CASE(test_compaction_with_multiple_regions) { return seastar::async([] { region reg1; region reg2; std::vector<managed_ref<int>> allocated1; std::vector<managed_ref<int>> allocated2; int count = 32 * 1024 * 4; with_allocator(reg1.allocator(), [&] { for (int i = 0; i < count; i++) { allocated1.push_back(make_managed<int>()); } }); with_allocator(reg2.allocator(), [&] { for (int i = 0; i < count; i++) { allocated2.push_back(make_managed<int>()); } }); size_t quarter = shard_tracker().occupancy().total_space() / 4; // Can't reclaim anything yet BOOST_REQUIRE(shard_tracker().reclaim(quarter) == 0); // Free 60% from the second pool // Shuffle, so that we don't free whole segments back to the pool // and there's nothing to reclaim. std::random_shuffle(allocated2.begin(), allocated2.end()); with_allocator(reg2.allocator(), [&] { auto it = allocated2.begin(); for (size_t i = 0; i < (count * 0.6); ++i) { *it++ = {}; } }); BOOST_REQUIRE(shard_tracker().reclaim(quarter) >= quarter); BOOST_REQUIRE(shard_tracker().reclaim(quarter) < quarter); // Free 60% from the first pool std::random_shuffle(allocated1.begin(), allocated1.end()); with_allocator(reg1.allocator(), [&] { auto it = allocated1.begin(); for (size_t i = 0; i < (count * 0.6); ++i) { *it++ = {}; } }); BOOST_REQUIRE(shard_tracker().reclaim(quarter) >= quarter); BOOST_REQUIRE(shard_tracker().reclaim(quarter) < quarter); with_allocator(reg2.allocator(), [&] () mutable { allocated2.clear(); }); with_allocator(reg1.allocator(), [&] () mutable { allocated1.clear(); }); }); } SEASTAR_TEST_CASE(test_mixed_type_compaction) { return seastar::async([] { static bool a_moved = false; static bool b_moved = false; static bool c_moved = false; static bool a_destroyed = false; static bool b_destroyed = false; static bool c_destroyed = false; struct A { uint8_t v = 0xca; A() = default; A(A&&) noexcept { a_moved = true; } ~A() { BOOST_REQUIRE(v == 0xca); a_destroyed = true; } }; struct B { uint16_t v = 0xcafe; B() = default; B(B&&) noexcept { b_moved = true; } ~B() { BOOST_REQUIRE(v == 0xcafe); b_destroyed = true; } }; struct C { uint64_t v = 0xcafebabe; C() = default; C(C&&) noexcept { c_moved = true; } ~C() { BOOST_REQUIRE(v == 0xcafebabe); c_destroyed = true; } }; region reg; with_allocator(reg.allocator(), [&] { { std::vector<int*> objs; auto p1 = make_managed<A>(); int junk_count = 10; for (int i = 0; i < junk_count; i++) { objs.push_back(reg.allocator().construct<int>(i)); } auto p2 = make_managed<B>(); for (int i = 0; i < junk_count; i++) { objs.push_back(reg.allocator().construct<int>(i)); } auto p3 = make_managed<C>(); for (auto&& p : objs) { reg.allocator().destroy(p); } reg.full_compaction(); BOOST_REQUIRE(a_moved); BOOST_REQUIRE(b_moved); BOOST_REQUIRE(c_moved); BOOST_REQUIRE(a_destroyed); BOOST_REQUIRE(b_destroyed); BOOST_REQUIRE(c_destroyed); a_destroyed = false; b_destroyed = false; c_destroyed = false; } BOOST_REQUIRE(a_destroyed); BOOST_REQUIRE(b_destroyed); BOOST_REQUIRE(c_destroyed); }); }); } SEASTAR_TEST_CASE(test_blob) { return seastar::async([] { region reg; with_allocator(reg.allocator(), [&] { auto src = bytes("123456"); managed_bytes b(src); BOOST_REQUIRE(bytes_view(b) == src); reg.full_compaction(); BOOST_REQUIRE(bytes_view(b) == src); }); }); } SEASTAR_TEST_CASE(test_merging) { return seastar::async([] { region reg1; region reg2; reg1.merge(reg2); managed_ref<int> r1; with_allocator(reg1.allocator(), [&] { r1 = make_managed<int>(); }); reg2.merge(reg1); with_allocator(reg2.allocator(), [&] { r1 = {}; }); std::vector<managed_ref<int>> refs; with_allocator(reg1.allocator(), [&] { for (int i = 0; i < 10000; ++i) { refs.emplace_back(make_managed<int>()); } }); reg2.merge(reg1); with_allocator(reg2.allocator(), [&] { refs.clear(); }); }); } <|endoftext|>
<commit_before>#include "dataraptor.h" #include "routing.h" #include "routing/raptor_utils.h" namespace navitia { namespace routing { void dataRAPTOR::load(const type::PT_Data &data) { Label label; label.dt = DateTimeUtils::inf; label.boarding = nullptr; label.type = boarding_type::uninitialized; labels_const.assign(data.journey_pattern_points.size(), label); label.dt = DateTimeUtils::min; labels_const_reverse.assign(data.journey_pattern_points.size(), label); foot_path_forward.clear(); foot_path_backward.clear(); footpath_index_backward.clear(); footpath_index_forward.clear(); footpath_rp_backward.clear(); footpath_rp_forward.clear(); std::vector<std::map<navitia::type::idx_t, const navitia::type::StopPointConnection*> > footpath_temp_forward, footpath_temp_backward; footpath_temp_forward.resize(data.stop_points.size()); footpath_temp_backward.resize(data.stop_points.size()); //Construction des connexions entre journey_patternpoints //(sert pour les prolongements de service ainsi que les correpondances garanties for(const type::JourneyPatternPointConnection* jppc : data.journey_pattern_point_connections) { footpath_rp_forward.insert(std::make_pair(jppc->departure->idx, jppc)); footpath_rp_backward.insert(std::make_pair(jppc->destination->idx, jppc)); } //Construction de la liste des marche à pied à partir des connexions renseignées for(const type::StopPointConnection* connection : data.stop_point_connections) { footpath_temp_forward[connection->departure->idx][connection->destination->idx] = connection; footpath_temp_backward[connection->departure->idx][connection->destination->idx] = connection; } //On rajoute des connexions entre les stops points d'un même stop area si elles n'existent pas footpath_index_forward.resize(data.stop_points.size()); footpath_index_backward.resize(data.stop_points.size()); for(const type::StopPoint* sp : data.stop_points) { footpath_index_forward[sp->idx].first = foot_path_forward.size(); footpath_index_backward[sp->idx].first = foot_path_backward.size(); int size_forward = 0, size_backward = 0; for(auto conn : footpath_temp_forward[sp->idx]) { foot_path_forward.push_back(conn.second); ++size_forward; } for(auto conn : footpath_temp_backward[sp->idx]) { foot_path_backward.push_back(conn.second); ++size_backward; } footpath_index_forward[sp->idx].second = size_forward; footpath_index_backward[sp->idx].second = size_backward; } typedef std::unordered_map<navitia::type::idx_t, vector_idx> idx_vector_idx; idx_vector_idx ridx_journey_pattern; arrival_times.clear(); departure_times.clear(); st_idx_forward.clear(); // Nom a changer ce ne sont plus des idx mais des pointeurs st_idx_backward.clear(); // first_stop_time.clear(); for(int i=0; i<=365; ++i) { jp_validity_patterns.push_back(boost::dynamic_bitset<>(data.journey_patterns.size())); } for(const type::JourneyPattern* journey_pattern : data.journey_patterns) { first_stop_time.push_back(arrival_times.size()); nb_trips.push_back(journey_pattern->vehicle_journey_list.size()); // On regroupe ensemble tous les horaires de tous les journey_pattern_point for(unsigned int i=0; i < journey_pattern->journey_pattern_point_list.size(); ++i) { std::vector<type::StopTime*> vec_st; for(const type::VehicleJourney* vj : journey_pattern->vehicle_journey_list) { vec_st.push_back(vj->stop_time_list[i]); } std::sort(vec_st.begin(), vec_st.end(), [&](type::StopTime* st1, type::StopTime* st2)->bool{ uint32_t time1, time2; if(!st1->is_frequency()) time1 = DateTimeUtils::hour(st1->departure_time); else time1 = DateTimeUtils::hour(st1->end_time); if(!st2->is_frequency()) time2 = DateTimeUtils::hour(st2->departure_time); else time2 = DateTimeUtils::hour(st2->end_time); return (time1 == time2 && st1 < st2) || (time1 < time2);}); st_idx_forward.insert(st_idx_forward.end(), vec_st.begin(), vec_st.end()); for(auto st : vec_st) { uint32_t time; if(!st->is_frequency()) time = DateTimeUtils::hour(st->departure_time); else time = DateTimeUtils::hour(st->end_time); departure_times.push_back(time); } std::sort(vec_st.begin(), vec_st.end(), [&](type::StopTime* st1, type::StopTime* st2)->bool{ uint32_t time1, time2; if(!st1->is_frequency()) time1 = DateTimeUtils::hour(st1->arrival_time); else time1 = DateTimeUtils::hour(st1->start_time); if(!st2->is_frequency()) time2 = DateTimeUtils::hour(st2->arrival_time); else time2 = DateTimeUtils::hour(st2->start_time); return (time1 == time2 && st1 > st2) || (time1 > time2);}); st_idx_backward.insert(st_idx_backward.end(), vec_st.begin(), vec_st.end()); for(auto st : vec_st) { uint32_t time; if(!st->is_frequency()) time = DateTimeUtils::hour(st->arrival_time); else time = DateTimeUtils::hour(st->start_time); arrival_times.push_back(time); } } // On dit que le journey pattern est valide en date j s'il y a au moins une circulation à j-1/j+1 for(int i=0; i<=365; ++i) { for(auto vj : journey_pattern->vehicle_journey_list) { if(vj->validity_pattern->check2(i)) { jp_validity_patterns[i].set(journey_pattern->idx); break; } } } } } }} <commit_msg>kraken : sort StopTimes in raptor<commit_after>#include "dataraptor.h" #include "routing.h" #include "routing/raptor_utils.h" namespace navitia { namespace routing { void dataRAPTOR::load(const type::PT_Data &data) { Label label; label.dt = DateTimeUtils::inf; label.boarding = nullptr; label.type = boarding_type::uninitialized; labels_const.assign(data.journey_pattern_points.size(), label); label.dt = DateTimeUtils::min; labels_const_reverse.assign(data.journey_pattern_points.size(), label); foot_path_forward.clear(); foot_path_backward.clear(); footpath_index_backward.clear(); footpath_index_forward.clear(); footpath_rp_backward.clear(); footpath_rp_forward.clear(); std::vector<std::map<navitia::type::idx_t, const navitia::type::StopPointConnection*> > footpath_temp_forward, footpath_temp_backward; footpath_temp_forward.resize(data.stop_points.size()); footpath_temp_backward.resize(data.stop_points.size()); //Construction des connexions entre journey_patternpoints //(sert pour les prolongements de service ainsi que les correpondances garanties for(const type::JourneyPatternPointConnection* jppc : data.journey_pattern_point_connections) { footpath_rp_forward.insert(std::make_pair(jppc->departure->idx, jppc)); footpath_rp_backward.insert(std::make_pair(jppc->destination->idx, jppc)); } //Construction de la liste des marche à pied à partir des connexions renseignées for(const type::StopPointConnection* connection : data.stop_point_connections) { footpath_temp_forward[connection->departure->idx][connection->destination->idx] = connection; footpath_temp_backward[connection->departure->idx][connection->destination->idx] = connection; } //On rajoute des connexions entre les stops points d'un même stop area si elles n'existent pas footpath_index_forward.resize(data.stop_points.size()); footpath_index_backward.resize(data.stop_points.size()); for(const type::StopPoint* sp : data.stop_points) { footpath_index_forward[sp->idx].first = foot_path_forward.size(); footpath_index_backward[sp->idx].first = foot_path_backward.size(); int size_forward = 0, size_backward = 0; for(auto conn : footpath_temp_forward[sp->idx]) { foot_path_forward.push_back(conn.second); ++size_forward; } for(auto conn : footpath_temp_backward[sp->idx]) { foot_path_backward.push_back(conn.second); ++size_backward; } footpath_index_forward[sp->idx].second = size_forward; footpath_index_backward[sp->idx].second = size_backward; } typedef std::unordered_map<navitia::type::idx_t, vector_idx> idx_vector_idx; idx_vector_idx ridx_journey_pattern; arrival_times.clear(); departure_times.clear(); st_idx_forward.clear(); // Nom a changer ce ne sont plus des idx mais des pointeurs st_idx_backward.clear(); // first_stop_time.clear(); for(int i=0; i<=365; ++i) { jp_validity_patterns.push_back(boost::dynamic_bitset<>(data.journey_patterns.size())); } for(const type::JourneyPattern* journey_pattern : data.journey_patterns) { first_stop_time.push_back(arrival_times.size()); nb_trips.push_back(journey_pattern->vehicle_journey_list.size()); // On regroupe ensemble tous les horaires de tous les journey_pattern_point for(unsigned int i=0; i < journey_pattern->journey_pattern_point_list.size(); ++i) { std::vector<type::StopTime*> vec_st; for(const type::VehicleJourney* vj : journey_pattern->vehicle_journey_list) { vec_st.push_back(vj->stop_time_list[i]); } std::sort(vec_st.begin(), vec_st.end(), [&](type::StopTime* st1, type::StopTime* st2)->bool{ uint32_t time1, time2; if(!st1->is_frequency()) time1 = DateTimeUtils::hour(st1->departure_time); else time1 = DateTimeUtils::hour(st1->end_time); if(!st2->is_frequency()) time2 = DateTimeUtils::hour(st2->departure_time); else time2 = DateTimeUtils::hour(st2->end_time); if(time1 == time2) { auto st1_first = st1->vehicle_journey->stop_time_list.front(); auto st2_first = st2->vehicle_journey->stop_time_list.front(); if(st1_first->departure_time == st2_first->departure_time) { return st1_first->vehicle_journey->idx < st2_first->vehicle_journey->idx; } return st1_first->departure_time < st2_first->departure_time; } return time1 < time2;}); st_idx_forward.insert(st_idx_forward.end(), vec_st.begin(), vec_st.end()); for(auto st : vec_st) { uint32_t time; if(!st->is_frequency()) time = DateTimeUtils::hour(st->departure_time); else time = DateTimeUtils::hour(st->end_time); departure_times.push_back(time); } std::sort(vec_st.begin(), vec_st.end(), [&](type::StopTime* st1, type::StopTime* st2)->bool{ uint32_t time1, time2; if(!st1->is_frequency()) time1 = DateTimeUtils::hour(st1->arrival_time); else time1 = DateTimeUtils::hour(st1->start_time); if(!st2->is_frequency()) time2 = DateTimeUtils::hour(st2->arrival_time); else time2 = DateTimeUtils::hour(st2->start_time); if(time1 == time2) { auto st1_first = st1->vehicle_journey->stop_time_list.front(); auto st2_first = st2->vehicle_journey->stop_time_list.front(); if(st1_first->arrival_time == st2_first->arrival_time) { return st1_first->vehicle_journey->idx > st2_first->vehicle_journey->idx; } return st1_first->arrival_time > st2_first->arrival_time; } return time1 > time2;}); st_idx_backward.insert(st_idx_backward.end(), vec_st.begin(), vec_st.end()); for(auto st : vec_st) { uint32_t time; if(!st->is_frequency()) time = DateTimeUtils::hour(st->arrival_time); else time = DateTimeUtils::hour(st->start_time); arrival_times.push_back(time); } } // On dit que le journey pattern est valide en date j s'il y a au moins une circulation à j-1/j+1 for(int i=0; i<=365; ++i) { for(auto vj : journey_pattern->vehicle_journey_list) { if(vj->validity_pattern->check2(i)) { jp_validity_patterns[i].set(journey_pattern->idx); break; } } } } } }} <|endoftext|>
<commit_before><commit_msg>Added debug from the plane! --kkd<commit_after><|endoftext|>
<commit_before><commit_msg>Fixed some MSVC incompatibilities. +++<commit_after><|endoftext|>
<commit_before>#include "gmock/gmock.h" #include "Game.h" #include "Human.h" using namespace testing; using namespace std; TEST(AGame, GetWhoPlaysFirst) { Human PlayerOne; Human PlayerTwo; Game game(PlayerOne, PlayerTwo); GenericPlayer &player = game.whoPlaysFirst(); GenericPlayer &playerOne = game.getPlayerOne(); ASSERT_THAT(player.getCallSign(),playerOne.getCallSign()); } TEST(AGame, Opponent) { Human PlayerOne; Human PlayerTwo; Game game(PlayerOne, PlayerTwo); GenericPlayer &playerOne = game.getPlayerOne(); GenericPlayer &opponent = game.opponent(playerOne); EXPECT_THAT(playerOne.getCallSign(), PlayerOptions::X); ASSERT_THAT(opponent.getCallSign(),PlayerOptions::O); } <commit_msg>Fixed indentation<commit_after>#include "gmock/gmock.h" #include "Game.h" #include "Human.h" using namespace testing; using namespace std; TEST(AGame, GetWhoPlaysFirst) { Human PlayerOne; Human PlayerTwo; Game game(PlayerOne, PlayerTwo); GenericPlayer &player = game.whoPlaysFirst(); GenericPlayer &playerOne = game.getPlayerOne(); ASSERT_THAT(player.getCallSign(),playerOne.getCallSign()); } TEST(AGame, Opponent) { Human PlayerOne; Human PlayerTwo; Game game(PlayerOne, PlayerTwo); GenericPlayer &playerOne = game.getPlayerOne(); GenericPlayer &opponent = game.opponent(playerOne); EXPECT_THAT(playerOne.getCallSign(), PlayerOptions::X); ASSERT_THAT(opponent.getCallSign(),PlayerOptions::O); } <|endoftext|>
<commit_before><commit_msg>Fix dropping of mailto: Urls. Needs an up-to-date kdelibs. BUG: 164328<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dlgedmod.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2004-10-04 19:41:05 $ * * 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 _BASCTL_DLGEDMOD_HXX #define _BASCTL_DLGEDMOD_HXX #ifndef _SVDMODEL_HXX #include <svx/svdmodel.hxx> #endif //============================================================================ // DlgEdModel //============================================================================ class DlgEdPage; class Window; class SfxObjectShell; class DlgEdModel : public SdrModel { friend class DlgEdPage; private: SfxObjectShell* pObjectShell; DlgEdModel( const DlgEdModel& ); void operator=(const DlgEdModel& rSrcModel); FASTBOOL operator==(const DlgEdModel& rCmpModel) const; public: TYPEINFO(); DlgEdModel(SfxItemPool* pPool=NULL, SfxObjectShell* pPers=NULL ); DlgEdModel(const String& rPath, SfxItemPool* pPool=NULL, SfxObjectShell* pPers=NULL ); DlgEdModel(SfxItemPool* pPool, SfxObjectShell* pPers, FASTBOOL bUseExtColorTable ); DlgEdModel(const String& rPath, SfxItemPool* pPool, SfxObjectShell* pPers, FASTBOOL bUseExtColorTable ); virtual ~DlgEdModel(); virtual void DlgEdModelChanged( FASTBOOL bChanged = TRUE ); SfxObjectShell* GetObjectShell() const { return pObjectShell; } void SetObjectShell( SfxObjectShell* pShell ) { pObjectShell = pShell; } virtual SdrPage* AllocPage(FASTBOOL bMasterPage); virtual Window* GetCurDocViewWin(); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.3.122); FILE MERGED 2005/09/05 13:56:03 rt 1.3.122.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlgedmod.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:20:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _BASCTL_DLGEDMOD_HXX #define _BASCTL_DLGEDMOD_HXX #ifndef _SVDMODEL_HXX #include <svx/svdmodel.hxx> #endif //============================================================================ // DlgEdModel //============================================================================ class DlgEdPage; class Window; class SfxObjectShell; class DlgEdModel : public SdrModel { friend class DlgEdPage; private: SfxObjectShell* pObjectShell; DlgEdModel( const DlgEdModel& ); void operator=(const DlgEdModel& rSrcModel); FASTBOOL operator==(const DlgEdModel& rCmpModel) const; public: TYPEINFO(); DlgEdModel(SfxItemPool* pPool=NULL, SfxObjectShell* pPers=NULL ); DlgEdModel(const String& rPath, SfxItemPool* pPool=NULL, SfxObjectShell* pPers=NULL ); DlgEdModel(SfxItemPool* pPool, SfxObjectShell* pPers, FASTBOOL bUseExtColorTable ); DlgEdModel(const String& rPath, SfxItemPool* pPool, SfxObjectShell* pPers, FASTBOOL bUseExtColorTable ); virtual ~DlgEdModel(); virtual void DlgEdModelChanged( FASTBOOL bChanged = TRUE ); SfxObjectShell* GetObjectShell() const { return pObjectShell; } void SetObjectShell( SfxObjectShell* pShell ) { pObjectShell = pShell; } virtual SdrPage* AllocPage(FASTBOOL bMasterPage); virtual Window* GetCurDocViewWin(); }; #endif <|endoftext|>
<commit_before>/* * cam_openssag.cpp * PHD Guiding * * Created by Craig Stark. * Copyright (c) 2009 Craig Stark. * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs 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 "phd.h" #ifdef OPENSSAG #include "camera.h" #include "image_math.h" #include "cam_openssag.h" #include <openssag.h> using namespace OpenSSAG; Camera_OpenSSAGClass::Camera_OpenSSAGClass() { Connected = FALSE; Name=_T("StarShoot Autoguider (OpenSSAG)"); FullSize = wxSize(1280,1024); // Current size of a full frame m_hasGuideOutput = true; // Do we have an ST4 port? HasGainControl = true; // Can we adjust gain? PixelSize = 5.2; ssag = new SSAG(); } bool Camera_OpenSSAGClass::Connect() { /* if (pFrame->mount_menu->IsChecked(SCOPE_CAMERA)) { ScopeConnected = SCOPE_CAMERA; pFrame->SetStatusText(_T("Scope"),4); } */ if (!ssag->Connect()) { wxMessageBox(_T("Could not connect to StarShoot Autoguider"), _("Error")); return true; } Connected = true; // Set global flag for being connected return false; } bool Camera_OpenSSAGClass::ST4PulseGuideScope(int direction, int duration) { switch (direction) { case WEST: ssag->Guide(guide_west, duration); break; case NORTH: ssag->Guide(guide_north, duration); break; case SOUTH: ssag->Guide(guide_south, duration); break; case EAST: ssag->Guide(guide_east, duration); break; default: return true; // bad direction passed in } wxMilliSleep(duration + 10); return false; } bool Camera_OpenSSAGClass::Disconnect() { Connected = false; ssag->Disconnect(); return false; } bool Camera_OpenSSAGClass::Capture(int duration, usImage& img, wxRect subframe, bool recon) { int xsize = FullSize.GetWidth(); int ysize = FullSize.GetHeight(); if (img.Init(FullSize)) { wxMessageBox(_T("Memory allocation error during capture"),_("Error"),wxOK | wxICON_ERROR); Disconnect(); return true; } ssag->SetGain((int)(GuideCameraGain / 24)); struct raw_image *raw = ssag->Expose(duration); for (unsigned int i = 0; i < raw->width * raw->height; i++) { img.ImageData[i] = (int)raw->data[i]; } ssag->FreeRawImage(raw); if (recon) SubtractDark(img); return false; } #endif // Apple-only <commit_msg>OSX: connect SSAG in background (so it is interruptible if it hangs)<commit_after>/* * cam_openssag.cpp * PHD Guiding * * Created by Craig Stark. * Copyright (c) 2009 Craig Stark. * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs 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 "phd.h" #ifdef OPENSSAG #include "camera.h" #include "image_math.h" #include "cam_openssag.h" #include <openssag.h> using namespace OpenSSAG; Camera_OpenSSAGClass::Camera_OpenSSAGClass() { Connected = FALSE; Name=_T("StarShoot Autoguider (OpenSSAG)"); FullSize = wxSize(1280,1024); // Current size of a full frame m_hasGuideOutput = true; // Do we have an ST4 port? HasGainControl = true; // Can we adjust gain? PixelSize = 5.2; ssag = new SSAG(); } bool Camera_OpenSSAGClass::Connect() { struct ConnectInBg : public ConnectCameraInBg { SSAG *ssag; ConnectInBg(SSAG *ssag_) : ssag(ssag_) { } bool Entry() { bool err = !ssag->Connect(); return err; } }; if (ConnectInBg(ssag).Run()) { wxMessageBox(_T("Could not connect to StarShoot Autoguider"), _("Error")); return true; } Connected = true; // Set global flag for being connected return false; } bool Camera_OpenSSAGClass::ST4PulseGuideScope(int direction, int duration) { switch (direction) { case WEST: ssag->Guide(guide_west, duration); break; case NORTH: ssag->Guide(guide_north, duration); break; case SOUTH: ssag->Guide(guide_south, duration); break; case EAST: ssag->Guide(guide_east, duration); break; default: return true; // bad direction passed in } wxMilliSleep(duration + 10); return false; } bool Camera_OpenSSAGClass::Disconnect() { Connected = false; ssag->Disconnect(); return false; } bool Camera_OpenSSAGClass::Capture(int duration, usImage& img, wxRect subframe, bool recon) { int xsize = FullSize.GetWidth(); int ysize = FullSize.GetHeight(); if (img.Init(FullSize)) { wxMessageBox(_T("Memory allocation error during capture"),_("Error"),wxOK | wxICON_ERROR); Disconnect(); return true; } ssag->SetGain((int)(GuideCameraGain / 24)); struct raw_image *raw = ssag->Expose(duration); for (unsigned int i = 0; i < raw->width * raw->height; i++) { img.ImageData[i] = (int)raw->data[i]; } ssag->FreeRawImage(raw); if (recon) SubtractDark(img); return false; } #endif // Apple-only <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: docsh.hxx,v $ * * $Revision: 1.36 $ * * last change: $Author: obo $ $Date: 2006-10-11 08:47:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SWDOCSH_HXX #define _SWDOCSH_HXX #ifndef _TIMER_HXX //autogen #include <vcl/timer.hxx> #endif #ifndef _SFX_OBJFAC_HXX //autogen #include <sfx2/docfac.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef SW_SWDLL_HXX #include <swdll.hxx> #endif #ifndef _SHELLID_HXX #include <shellid.hxx> #endif #include <svtools/lstner.hxx> class SwDoc; class SfxDocumentInfoDialog; class SfxStyleSheetBasePool; class FontList; class SwView; class SwWrtShell; class SwFEShell; class Reader; class SwReader; class SwCrsrShell; class SwSrcView; class SwPaM; class SwgReaderOption; class SwOLEObj; class IDocumentDeviceAccess; class IDocumentSettingAccess; class IDocumentTimerAccess; class SW_DLLPUBLIC SwDocShell: public SfxObjectShell, public SfxListener { SwDoc* pDoc; // Document SfxStyleSheetBasePool* pBasePool; // Durchreiche fuer Formate FontList* pFontList; // aktuelle FontListe // Nix geht ohne die WrtShell (historische Gruende) // RuekwaertsPointer auf die View (historische Gruende) // Dieser gilt solange bis im Activate ein neuer gesetzt wird // oder dieser im Dtor der View geloescht wird // SwView* pView; SwWrtShell* pWrtShell; Timer aFinishedTimer; // Timer fuers ueberpriefen der // Grafik-Links. Sind alle da, // dann ist Doc voll. geladen //SvPersistRef xOLEChildList; // fuers RemoveOLEObjects comphelper::EmbeddedObjectContainer* pOLEChildList; sal_Int16 nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode bool bInUpdateFontList; //prevent nested calls of UpdateFontList // Methoden fuer den Zugriff aufs Doc SW_DLLPRIVATE void AddLink(); SW_DLLPRIVATE void RemoveLink(); // Hint abfangen fuer DocInfo SW_DLLPRIVATE virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); // FileIO SW_DLLPRIVATE virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual sal_Bool Load( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool LoadFrom( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool ConvertFrom( SfxMedium &rMedium ); SW_DLLPRIVATE virtual sal_Bool ConvertTo( SfxMedium &rMedium ); SW_DLLPRIVATE virtual sal_Bool SaveAs( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual USHORT PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE ); // DocInfo dem Doc melden // SW_DLLPRIVATE virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog( Window *pParent, const SfxItemSet &); // OLE-Geraffel SW_DLLPRIVATE virtual void Draw( OutputDevice*, const JobSetup&, USHORT); // Methoden fuer StyleSheets SW_DLLPRIVATE USHORT Edit( const String &rName, const String& rParent, USHORT nFamily, USHORT nMask, BOOL bNew, BOOL bColumn = FALSE, SwWrtShell* pActShell = 0, BOOL bBasic = FALSE ); SW_DLLPRIVATE USHORT Delete(const String &rName, USHORT nFamily); SW_DLLPRIVATE USHORT ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0, USHORT nMode = 0 ); SW_DLLPRIVATE USHORT DoWaterCan( const String &rName, USHORT nFamily); SW_DLLPRIVATE USHORT UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0); SW_DLLPRIVATE USHORT MakeByExample(const String &rName, USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0); SW_DLLPRIVATE void InitDraw(); SW_DLLPRIVATE void SubInitNew(); // fuer InitNew und HtmlSourceModus SW_DLLPRIVATE void RemoveOLEObjects(); SW_DLLPRIVATE void CalcLayoutForOLEObjects(); SW_DLLPRIVATE void Init_Impl(); SW_DLLPRIVATE DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* ); public: // aber selbst implementieren SFX_DECL_INTERFACE(SW_DOCSHELL) SFX_DECL_OBJECTFACTORY() TYPEINFO(); static SfxInterface *_GetInterface() { return GetStaticInterface(); } //Das Doc wird fuer SO-Datenaustausch benoetigt! SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED); SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD ); ~SwDocShell(); // OLE 2.0-Benachrichtigung DECL_LINK( Ole2ModifiedHdl, void * ); // OLE-Geraffel virtual void SetVisArea( const Rectangle &rRect ); virtual Rectangle GetVisArea( USHORT nAspect ) const; virtual Printer *GetDocumentPrinter(); virtual OutputDevice* GetDocumentRefDev(); virtual void OnDocumentPrinterChanged( Printer * pNewPrinter ); virtual ULONG GetMiscStatus() const; virtual void PrepareReload(); virtual void SetModified( BOOL = TRUE ); // Dispatcher void Execute(SfxRequest &); void ExecStyleSheet(SfxRequest&); void ExecDB(SfxRequest&); void GetState(SfxItemSet &); void StateAlways(SfxItemSet &); void StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 ); // Doc rausreichen aber VORSICHT inline SwDoc* GetDoc() { return pDoc; } IDocumentDeviceAccess* getIDocumentDeviceAccess(); const IDocumentSettingAccess* getIDocumentSettingAccess() const; IDocumentTimerAccess* getIDocumentTimerAccess(); void UpdateFontList(); void UpdateChildWindows(); // DocumentInfo neu setzen BOOL SetDocumentInfo(const SfxDocumentInfo& rInfo); // globaler IO virtual BOOL Save(); // fuer VorlagenPI virtual SfxStyleSheetBasePool* GetStyleSheetPool(); // Fuer Organizer virtual BOOL Insert(SfxObjectShell &rSource, USHORT nSourceIdx1, USHORT nSourceIdx2, USHORT nSourceIdx3, USHORT& nIdx1, USHORT& nIdx2, USHORT& nIdx3, USHORT& nRemovedIdx); virtual BOOL Remove(USHORT nIdx1, USHORT nIdx2 = INDEX_IGNORE, USHORT nIdx3 = INDEX_IGNORE); virtual Bitmap GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode ); // View setzen fuer Aktionen ueber Shell void SetView(SwView* pVw); const SwView *GetView() const { return pView; } SwView *GetView() { return pView; } // Zugriff auf die zur SwView gehoerige SwWrtShell SwWrtShell *GetWrtShell() { return pWrtShell; } const SwWrtShell *GetWrtShell() const { return pWrtShell; } // fuer die Core - die kennt die DocShell aber keine WrtShell! SwFEShell *GetFEShell(); const SwFEShell *GetFEShell() const { return ((SwDocShell*)this)->GetFEShell(); } // Fuer Einfuegen Dokument Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr, SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0); virtual long DdeGetData( const String& rItem, const String& rMimeType, ::com::sun::star::uno::Any & rValue ); virtual long DdeSetData( const String& rItem, const String& rMimeType, const ::com::sun::star::uno::Any & rValue ); virtual ::sfx2::SvLinkSource* DdeCreateLinkSource( const String& rItem ); virtual void FillClass( SvGlobalName * pClassName, sal_uInt32 * pClipFormat, String * pAppName, String * pLongUserName, String * pUserName, sal_Int32 nFileFormat ) const; virtual void LoadStyles( SfxObjectShell& rSource ); void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument ); // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage void FormatPage( const String& rPage, BOOL bColumn = FALSE, SwWrtShell* pActShell = 0 ); // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle // vollstaendig geladen, dann ist das Doc fertig void StartLoadFinishedTimer(); // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen) virtual void CancelTransfers(); // Doc aus Html-Source neu laden void ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView ); sal_Int16 GetUpdateDocMode() const {return nUpdateDocMode;} //Activate wait cursor for all windows of this document //Optionally all dispatcher could be Locked //Usually locking should be done using the class: SwWaitObject! void EnterWait( BOOL bLockDispatcher ); void LeaveWait( BOOL bLockDispatcher ); void ToggleBrowserMode(BOOL bOn, SwView* pView = 0); ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt, BOOL bUnoCall ); void InvalidateModel(); void ReactivateModel(); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > GetEventNames(); // --> FME 2004-08-05 #i20883# Digital Signatures and Encryption virtual sal_uInt16 GetHiddenInformationState( sal_uInt16 nStates ); // <-- // --> FME 2005-02-25 #i42634# Overwrites SfxObjectShell::UpdateLinks // This new function is necessary to trigger update of links in docs // read by the binary filter: virtual void UpdateLinks(); // <-- SW_DLLPRIVATE void CalcAndSetScaleOfOLEObj( SwOLEObj& rOLEObject ); }; #endif <commit_msg>INTEGRATION: CWS swqbf89 (1.36.10); FILE MERGED 2006/11/08 14:21:16 od 1.36.10.1: #i59688# class <SwDocShell> - change semantic and name of method <StartLoadFinishedTimer()> -- loading of linked graphics no longer needed and necessary for the load of document being finished. method name is now <LoadingFinished()><commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: docsh.hxx,v $ * * $Revision: 1.37 $ * * last change: $Author: rt $ $Date: 2006-12-01 14:23:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SWDOCSH_HXX #define _SWDOCSH_HXX #ifndef _TIMER_HXX //autogen #include <vcl/timer.hxx> #endif #ifndef _SFX_OBJFAC_HXX //autogen #include <sfx2/docfac.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef SW_SWDLL_HXX #include <swdll.hxx> #endif #ifndef _SHELLID_HXX #include <shellid.hxx> #endif #include <svtools/lstner.hxx> class SwDoc; class SfxDocumentInfoDialog; class SfxStyleSheetBasePool; class FontList; class SwView; class SwWrtShell; class SwFEShell; class Reader; class SwReader; class SwCrsrShell; class SwSrcView; class SwPaM; class SwgReaderOption; class SwOLEObj; class IDocumentDeviceAccess; class IDocumentSettingAccess; class IDocumentTimerAccess; class SW_DLLPUBLIC SwDocShell: public SfxObjectShell, public SfxListener { SwDoc* pDoc; // Document SfxStyleSheetBasePool* pBasePool; // Durchreiche fuer Formate FontList* pFontList; // aktuelle FontListe // Nix geht ohne die WrtShell (historische Gruende) // RuekwaertsPointer auf die View (historische Gruende) // Dieser gilt solange bis im Activate ein neuer gesetzt wird // oder dieser im Dtor der View geloescht wird // SwView* pView; SwWrtShell* pWrtShell; Timer aFinishedTimer; // Timer fuers ueberpriefen der // Grafik-Links. Sind alle da, // dann ist Doc voll. geladen //SvPersistRef xOLEChildList; // fuers RemoveOLEObjects comphelper::EmbeddedObjectContainer* pOLEChildList; sal_Int16 nUpdateDocMode; // contains the com::sun::star::document::UpdateDocMode bool bInUpdateFontList; //prevent nested calls of UpdateFontList // Methoden fuer den Zugriff aufs Doc SW_DLLPRIVATE void AddLink(); SW_DLLPRIVATE void RemoveLink(); // Hint abfangen fuer DocInfo SW_DLLPRIVATE virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint ); // FileIO SW_DLLPRIVATE virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual sal_Bool Load( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool LoadFrom( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool ConvertFrom( SfxMedium &rMedium ); SW_DLLPRIVATE virtual sal_Bool ConvertTo( SfxMedium &rMedium ); SW_DLLPRIVATE virtual sal_Bool SaveAs( SfxMedium& rMedium ); SW_DLLPRIVATE virtual sal_Bool SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage ); SW_DLLPRIVATE virtual USHORT PrepareClose( BOOL bUI = TRUE, BOOL bForBrowsing = FALSE ); // DocInfo dem Doc melden // SW_DLLPRIVATE virtual SfxDocumentInfoDialog* CreateDocumentInfoDialog( Window *pParent, const SfxItemSet &); // OLE-Geraffel SW_DLLPRIVATE virtual void Draw( OutputDevice*, const JobSetup&, USHORT); // Methoden fuer StyleSheets SW_DLLPRIVATE USHORT Edit( const String &rName, const String& rParent, USHORT nFamily, USHORT nMask, BOOL bNew, BOOL bColumn = FALSE, SwWrtShell* pActShell = 0, BOOL bBasic = FALSE ); SW_DLLPRIVATE USHORT Delete(const String &rName, USHORT nFamily); SW_DLLPRIVATE USHORT ApplyStyles(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0, USHORT nMode = 0 ); SW_DLLPRIVATE USHORT DoWaterCan( const String &rName, USHORT nFamily); SW_DLLPRIVATE USHORT UpdateStyle(const String &rName, USHORT nFamily, SwWrtShell* pShell = 0); SW_DLLPRIVATE USHORT MakeByExample(const String &rName, USHORT nFamily, USHORT nMask, SwWrtShell* pShell = 0); SW_DLLPRIVATE void InitDraw(); SW_DLLPRIVATE void SubInitNew(); // fuer InitNew und HtmlSourceModus SW_DLLPRIVATE void RemoveOLEObjects(); SW_DLLPRIVATE void CalcLayoutForOLEObjects(); SW_DLLPRIVATE void Init_Impl(); SW_DLLPRIVATE DECL_STATIC_LINK( SwDocShell, IsLoadFinished, void* ); public: // aber selbst implementieren SFX_DECL_INTERFACE(SW_DOCSHELL) SFX_DECL_OBJECTFACTORY() TYPEINFO(); static SfxInterface *_GetInterface() { return GetStaticInterface(); } //Das Doc wird fuer SO-Datenaustausch benoetigt! SwDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED); SwDocShell( SwDoc *pDoc, SfxObjectCreateMode eMode = SFX_CREATE_MODE_STANDARD ); ~SwDocShell(); // OLE 2.0-Benachrichtigung DECL_LINK( Ole2ModifiedHdl, void * ); // OLE-Geraffel virtual void SetVisArea( const Rectangle &rRect ); virtual Rectangle GetVisArea( USHORT nAspect ) const; virtual Printer *GetDocumentPrinter(); virtual OutputDevice* GetDocumentRefDev(); virtual void OnDocumentPrinterChanged( Printer * pNewPrinter ); virtual ULONG GetMiscStatus() const; virtual void PrepareReload(); virtual void SetModified( BOOL = TRUE ); // Dispatcher void Execute(SfxRequest &); void ExecStyleSheet(SfxRequest&); void ExecDB(SfxRequest&); void GetState(SfxItemSet &); void StateAlways(SfxItemSet &); void StateStyleSheet(SfxItemSet&, SwWrtShell* pSh = 0 ); // Doc rausreichen aber VORSICHT inline SwDoc* GetDoc() { return pDoc; } IDocumentDeviceAccess* getIDocumentDeviceAccess(); const IDocumentSettingAccess* getIDocumentSettingAccess() const; IDocumentTimerAccess* getIDocumentTimerAccess(); void UpdateFontList(); void UpdateChildWindows(); // DocumentInfo neu setzen BOOL SetDocumentInfo(const SfxDocumentInfo& rInfo); // globaler IO virtual BOOL Save(); // fuer VorlagenPI virtual SfxStyleSheetBasePool* GetStyleSheetPool(); // Fuer Organizer virtual BOOL Insert(SfxObjectShell &rSource, USHORT nSourceIdx1, USHORT nSourceIdx2, USHORT nSourceIdx3, USHORT& nIdx1, USHORT& nIdx2, USHORT& nIdx3, USHORT& nRemovedIdx); virtual BOOL Remove(USHORT nIdx1, USHORT nIdx2 = INDEX_IGNORE, USHORT nIdx3 = INDEX_IGNORE); virtual Bitmap GetStyleFamilyBitmap( SfxStyleFamily eFamily, BmpColorMode eColorMode ); // View setzen fuer Aktionen ueber Shell void SetView(SwView* pVw); const SwView *GetView() const { return pView; } SwView *GetView() { return pView; } // Zugriff auf die zur SwView gehoerige SwWrtShell SwWrtShell *GetWrtShell() { return pWrtShell; } const SwWrtShell *GetWrtShell() const { return pWrtShell; } // fuer die Core - die kennt die DocShell aber keine WrtShell! SwFEShell *GetFEShell(); const SwFEShell *GetFEShell() const { return ((SwDocShell*)this)->GetFEShell(); } // Fuer Einfuegen Dokument Reader* StartConvertFrom(SfxMedium& rMedium, SwReader** ppRdr, SwCrsrShell* pCrsrSh = 0, SwPaM* pPaM = 0); virtual long DdeGetData( const String& rItem, const String& rMimeType, ::com::sun::star::uno::Any & rValue ); virtual long DdeSetData( const String& rItem, const String& rMimeType, const ::com::sun::star::uno::Any & rValue ); virtual ::sfx2::SvLinkSource* DdeCreateLinkSource( const String& rItem ); virtual void FillClass( SvGlobalName * pClassName, sal_uInt32 * pClipFormat, String * pAppName, String * pLongUserName, String * pUserName, sal_Int32 nFileFormat ) const; virtual void LoadStyles( SfxObjectShell& rSource ); void _LoadStyles( SfxObjectShell& rSource, BOOL bPreserveCurrentDocument ); // Seitenvorlagedialog anzeigen, ggf. auf Spaltenpage void FormatPage( const String& rPage, BOOL bColumn = FALSE, SwWrtShell* pActShell = 0 ); // --> OD 2006-11-07 #i59688# // linked graphics are now loaded on demand. // Thus, loading of linked graphics no longer needed and necessary for // the load of document being finished. // // Timer starten fuers ueberpruefen der Grafik-Links. Sind alle // // vollstaendig geladen, dann ist das Doc fertig // void StartLoadFinishedTimer(); void LoadingFinished(); // <-- // eine Uebertragung wird abgebrochen (wird aus dem SFX gerufen) virtual void CancelTransfers(); // Doc aus Html-Source neu laden void ReloadFromHtml( const String& rStreamName, SwSrcView* pSrcView ); sal_Int16 GetUpdateDocMode() const {return nUpdateDocMode;} //Activate wait cursor for all windows of this document //Optionally all dispatcher could be Locked //Usually locking should be done using the class: SwWaitObject! void EnterWait( BOOL bLockDispatcher ); void LeaveWait( BOOL bLockDispatcher ); void ToggleBrowserMode(BOOL bOn, SwView* pView = 0); ULONG LoadStylesFromFile( const String& rURL, SwgReaderOption& rOpt, BOOL bUnoCall ); void InvalidateModel(); void ReactivateModel(); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > GetEventNames(); // --> FME 2004-08-05 #i20883# Digital Signatures and Encryption virtual sal_uInt16 GetHiddenInformationState( sal_uInt16 nStates ); // <-- // --> FME 2005-02-25 #i42634# Overwrites SfxObjectShell::UpdateLinks // This new function is necessary to trigger update of links in docs // read by the binary filter: virtual void UpdateLinks(); // <-- SW_DLLPRIVATE void CalcAndSetScaleOfOLEObj( SwOLEObj& rOLEObject ); }; #endif <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <algorithm> #include <toml/region.hpp> #include <toml/result.hpp> #define TOML11_TEST_LEX_ACCEPT(lxr, tkn, expct) \ do { \ const std::string token (tkn); \ const std::string expected(expct); \ toml::detail::location<std::string> loc(token); \ const auto result = lxr::invoke(loc); \ BOOST_CHECK(result.is_ok()); \ if(result.is_ok()){ \ const auto matched = result.unwrap().str(); \ std::cerr << "matched -> "; \ std::for_each(matched.begin(), matched.end(), [](const char c) { \ std::cerr << std::setw(2) << std::hex << std::setfill('0'); \ std::cerr << "0x" << static_cast<int>(c) << ", "; \ return; \ }); \ std::cerr << std::endl; \ const auto region = result.unwrap(); \ BOOST_CHECK_EQUAL(region.str(), expected); \ BOOST_CHECK_EQUAL(region.str().size(), expected.size()); \ BOOST_CHECK_EQUAL(std::distance(loc.begin(), loc.iter()), region.size()); \ } else { \ std::cerr << "lexer " << lxr::pattern() << " failed with input `"; \ std::cerr << token << "`. expected `" << expected << "`\n"; \ std::cerr << "reason: " << result.unwrap_err() << '\n'; \ } \ } while(false); \ /**/ #define TOML11_TEST_LEX_REJECT(lxr, tkn) \ do { \ const std::string token (tkn); \ toml::detail::location<std::string> loc(token); \ const auto result = lxr::invoke(loc); \ BOOST_CHECK(result.is_err()); \ BOOST_CHECK(loc.begin() == loc.iter()); \ } while(false); /**/ <commit_msg>remove debug message from test code<commit_after>#include <iostream> #include <iomanip> #include <algorithm> #include <toml/region.hpp> #include <toml/result.hpp> #define TOML11_TEST_LEX_ACCEPT(lxr, tkn, expct) \ do { \ const std::string token (tkn); \ const std::string expected(expct); \ toml::detail::location<std::string> loc(token); \ const auto result = lxr::invoke(loc); \ BOOST_CHECK(result.is_ok()); \ if(result.is_ok()){ \ const auto region = result.unwrap(); \ BOOST_CHECK_EQUAL(region.str(), expected); \ BOOST_CHECK_EQUAL(region.str().size(), expected.size()); \ BOOST_CHECK_EQUAL(std::distance(loc.begin(), loc.iter()), region.size()); \ } else { \ std::cerr << "lexer " << lxr::pattern() << " failed with input `"; \ std::cerr << token << "`. expected `" << expected << "`\n"; \ std::cerr << "reason: " << result.unwrap_err() << '\n'; \ } \ } while(false); \ /**/ #define TOML11_TEST_LEX_REJECT(lxr, tkn) \ do { \ const std::string token (tkn); \ toml::detail::location<std::string> loc(token); \ const auto result = lxr::invoke(loc); \ BOOST_CHECK(result.is_err()); \ BOOST_CHECK(loc.begin() == loc.iter()); \ } while(false); /**/ <|endoftext|>
<commit_before>// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(vector<int> &A, vector<int> &B) { // write your code in C++11 // create an empty stack for alive fishes vector<int> C; unsigned int i(0); // go through all fishes to decide whether it is alive while( i<A.size() ) { // when stack is empty, current fish is always alive if( C.empty() ) { // current fish is alive, push back to the stack C.push_back(i); // update current fish to the next one i++; } else { // only when fish at top of the stack goes downstream // and current fish goes upstream, they can meet if( B[ C.back() ]==1 && B[i]==0 ) { // fish at top of the stack is smaller than current fish if( A[ C.back() ]<A[i] ) { // fish at top of the stack is eaten by current fish C.pop_back(); // when stack is empty, keep current fish and start over if( C.empty() ) continue; } else { // current fish is eaten by fish at top of the stack // update current fish to the next one i++; } } // fish at top of the stack never meet current fish // since they either go opposite ways or the same ways in the same speed else { // current fish is alive, push back to the stack C.push_back(i); // update current fish to the next one i++; } } } // all alive fishes remain in the stack return C.size(); } <commit_msg>Update solution.cpp<commit_after>// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(vector<int> &A, vector<int> &B) { // write your code in C++11 // create an empty stack for alive fishes vector<int> C; unsigned int i(0); // go through all fishes to decide whether it is alive while( i<A.size() ) { // when stack is empty, current fish is always alive if( C.empty() ) { // current fish is alive, push back to the stack C.push_back(i); // update current fish to the next one i++; } else { // only when fish at top of the stack goes downstream // and current fish goes upstream, they can meet if( B[ C.back() ]==1 && B[i]==0 ) { // fish at top of the stack is smaller than current fish if( A[ C.back() ]<A[i] ) { // fish at top of the stack is eaten by current fish, pop out of the stack C.pop_back(); // when stack is empty, keep current fish and start over if( C.empty() ) continue; } else { // current fish is eaten by fish at top of the stack // update current fish to the next one i++; } } // fish at top of the stack never meet current fish // since they either go opposite ways or the same ways in the same speed else { // current fish is alive, push back to the stack C.push_back(i); // update current fish to the next one i++; } } } // all alive fishes remain in the stack return C.size(); } <|endoftext|>
<commit_before>// Copyright 2014 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 "mojo/services/view_manager/server_view.h" #include "mojo/services/view_manager/server_view_delegate.h" #include "mojo/services/view_manager/view_coordinate_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/vector2d.h" namespace mojo { namespace service { namespace { class MockServerViewDelegate : public ServerViewDelegate { public: MockServerViewDelegate() {} ~MockServerViewDelegate() override {} private: // ServerViewDelegate: void OnViewDestroyed(const ServerView* view) override {} void OnWillChangeViewHierarchy(const ServerView* view, const ServerView* new_parent, const ServerView* old_parent) override {} void OnViewHierarchyChanged(const ServerView* view, const ServerView* new_parent, const ServerView* old_parent) override {} void OnViewBoundsChanged(const ServerView* view, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) override {} void OnViewSurfaceIdChanged(const ServerView* view) override {} void OnViewReordered(const ServerView* view, const ServerView* relative, OrderDirection direction) override {} void OnWillChangeViewVisibility(const ServerView* view) override {} void OnViewPropertyChanged(const ServerView* view, const std::string& name, const std::vector<uint8_t>* new_data) override {} DISALLOW_COPY_AND_ASSIGN(MockServerViewDelegate); }; } // namespace using ViewCoordinateConversionsTest = testing::Test; TEST_F(ViewCoordinateConversionsTest, ConvertRectBetweenViews) { MockServerViewDelegate d1, d2, d3; ServerView v1(&d1, ViewId()), v2(&d2, ViewId()), v3(&d3, ViewId()); v1.SetBounds(gfx::Rect(1, 2, 100, 100)); v2.SetBounds(gfx::Rect(3, 4, 100, 100)); v3.SetBounds(gfx::Rect(5, 6, 100, 100)); v1.Add(&v2); v2.Add(&v3); EXPECT_EQ(gfx::Rect(2, 1, 8, 9), ConvertRectBetweenViews(&v1, &v3, gfx::Rect(10, 11, 8, 9))); EXPECT_EQ(gfx::Rect(18, 21, 8, 9), ConvertRectBetweenViews(&v3, &v1, gfx::Rect(10, 11, 8, 9))); } } // namespace service } // namespace mojo <commit_msg>Fix renamed override<commit_after>// Copyright 2014 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 "mojo/services/view_manager/server_view.h" #include "mojo/services/view_manager/server_view_delegate.h" #include "mojo/services/view_manager/view_coordinate_conversions.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/vector2d.h" namespace mojo { namespace service { namespace { class MockServerViewDelegate : public ServerViewDelegate { public: MockServerViewDelegate() {} ~MockServerViewDelegate() override {} private: // ServerViewDelegate: void OnViewDestroyed(const ServerView* view) override {} void OnWillChangeViewHierarchy(const ServerView* view, const ServerView* new_parent, const ServerView* old_parent) override {} void OnViewHierarchyChanged(const ServerView* view, const ServerView* new_parent, const ServerView* old_parent) override {} void OnViewBoundsChanged(const ServerView* view, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) override {} void OnViewSurfaceIdChanged(const ServerView* view) override {} void OnViewReordered(const ServerView* view, const ServerView* relative, OrderDirection direction) override {} void OnWillChangeViewVisibility(const ServerView* view) override {} void OnViewSharedPropertyChanged( const ServerView* view, const std::string& name, const std::vector<uint8_t>* new_data) override {} DISALLOW_COPY_AND_ASSIGN(MockServerViewDelegate); }; } // namespace using ViewCoordinateConversionsTest = testing::Test; TEST_F(ViewCoordinateConversionsTest, ConvertRectBetweenViews) { MockServerViewDelegate d1, d2, d3; ServerView v1(&d1, ViewId()), v2(&d2, ViewId()), v3(&d3, ViewId()); v1.SetBounds(gfx::Rect(1, 2, 100, 100)); v2.SetBounds(gfx::Rect(3, 4, 100, 100)); v3.SetBounds(gfx::Rect(5, 6, 100, 100)); v1.Add(&v2); v2.Add(&v3); EXPECT_EQ(gfx::Rect(2, 1, 8, 9), ConvertRectBetweenViews(&v1, &v3, gfx::Rect(10, 11, 8, 9))); EXPECT_EQ(gfx::Rect(18, 21, 8, 9), ConvertRectBetweenViews(&v3, &v1, gfx::Rect(10, 11, 8, 9))); } } // namespace service } // namespace mojo <|endoftext|>
<commit_before>// // ex10_05.cpp // Exercise 10.5 // // Created by pezy on 11/9/14. // Copyright (c) 2014 pezy. All rights reserved. // // @Brief In the call to equal on rosters, what would happen if both rosters held C-style strings, rather than library strings? // @Answer It's the same as `std::string` #include <algorithm> #include <iostream> #include <vector> #include <list> int main() { std::vector<const char *> roster1{"Mooophy", "pezy", "Queequeg"}; std::list<const char *> roster2{"Mooophy", "pezy", "Queequeg", "shbling", "evan617"}; std::cout << std::equal(roster1.cbegin(), roster1.cend(), roster2.cbegin()); } // out // 1 <commit_msg>fixed #227<commit_after>// // ex10_05.cpp // Exercise 10.5 // // Created by pezy on 11/9/14. // Copyright (c) 2014 pezy. All rights reserved. // // @Brief In the call to equal on rosters, what would happen if both rosters held C-style strings, rather than library strings? // @Answer For such case, std::equal is going to compare the address value rather than the string value. // So the result is not the same as std::string. Try to avoid coding this way. // Check #227 for more detail. // #include <iostream> int main(){} <|endoftext|>
<commit_before>// // ex12_23.cpp // Exercise 12.23 // // Created by pezy on 12/30/14. // // Write a program to concatenate two string literals, putting the result in a dynamically allocated array of char. // Write a program to concatenate two library strings that have the same value as the literals used in the first program. #include <iostream> #include <string> #include <string.h> int main() { // dynamically allocated array of char char *concatenate_string = new char[strlen("hello " "world") + 1](); strcat(concatenate_string, "hello "); strcat(concatenate_string, "world"); std::cout << concatenate_string << std::endl; delete [] concatenate_string; // std::string std::string str1{ "hello " }, str2{ "world" }; std::cout << str1 + str2 << std::endl; } <commit_msg>Update ex12_23.cpp<commit_after>// // ex12_23.cpp // Exercise 12.23 // // Created by pezy on 12/30/14. // // Write a program to concatenate two string literals, putting the result in a dynamically allocated array of char. // Write a program to concatenate two library strings that have the same value as the literals used in the first program. #include <iostream> #include <string> #include <string.h> int main() { // dynamically allocated array of char char *concatenate_string = new char[strlen("hello " "world") + 1](); strcat(concatenate_string, "hello "); strcat(concatenate_string, "world"); std::cout << concatenate_string << std::endl; delete [] concatenate_string; // std::string std::string str1{ "hello " }, str2{ "world" }; std::cout << str1 + str2 << std::endl; } <|endoftext|>
<commit_before>#include "SoundManager.h" #include <sndfile.hh> #include "Audio.h" #include <al.h> #include <alc.h> namespace aie { SoundManager* SoundManager::m_instance = nullptr; static int getSampleSize(int format) { int subFormat = format & SF_FORMAT_SUBMASK; switch (subFormat) { case SF_FORMAT_PCM_16: return sizeof(short); case SF_FORMAT_GSM610: return sizeof(short); case SF_FORMAT_DWVW_16: return sizeof(short); case SF_FORMAT_DPCM_16: return sizeof(short); case SF_FORMAT_VORBIS: return sizeof(short); case SF_FORMAT_ALAC_16: return sizeof(short); case SF_FORMAT_PCM_U8: return sizeof(unsigned char); //Untested formats case SF_FORMAT_PCM_24: return sizeof(char[3]); case SF_FORMAT_DWVW_24: return sizeof(char[3]); case SF_FORMAT_ALAC_24: return sizeof(char[3]); case SF_FORMAT_PCM_32: return sizeof(int); case SF_FORMAT_ALAC_32: return sizeof(int); case SF_FORMAT_FLOAT: return sizeof(float); case SF_FORMAT_DOUBLE: return sizeof(double); default: return sizeof(char); } } static int getOpenALFormat(int fileFormat, int channels) { int subFormat = fileFormat & SF_FORMAT_SUBMASK; switch (subFormat) { case SF_FORMAT_PCM_16: case SF_FORMAT_DPCM_16: case SF_FORMAT_ALAC_16: case SF_FORMAT_VORBIS: case SF_FORMAT_GSM610: { if(channels > 1) return AL_FORMAT_STEREO16; return AL_FORMAT_MONO16; } default: { if(channels > 1) return AL_FORMAT_STEREO8; return AL_FORMAT_MONO8; } } } SoundManager::SoundManager() { //Create OpenAL device and setup context. m_openALDevice = alcOpenDevice(nullptr); if (alGetError() != AL_NO_ERROR) { //error printf("Could not initialise OpenAL\n"); } m_openALContext = alcCreateContext(m_openALDevice, nullptr); if (alGetError() != AL_NO_ERROR) { //error printf("Could not initialise OpenAL\n"); } alcMakeContextCurrent(m_openALContext); if (alGetError() != AL_NO_ERROR) { //error printf("Could not initialise OpenAL\n"); } //Create sources and buffers alGenSources(MAX_SOUNDS, m_audioSources); if (alGetError() != AL_NO_ERROR) { //error printf("Could not initialise OpenAL\n"); } m_audioList = nullptr; } SoundManager::~SoundManager() { //Close OpenAL device alcMakeContextCurrent(nullptr); alcDestroyContext(m_openALContext); alcCloseDevice(m_openALDevice); } void SoundManager::update() { Audio* pCurrent = m_audioList; while (pCurrent != nullptr) { int nSourceID = pCurrent->m_sourceID; if (nSourceID >= 0) { if (!getIsPlayingInternal(nSourceID) && !getIsPausedInternal(nSourceID)) { if (pCurrent->m_looping) { playSoundInternal(pCurrent); } else { //Unbind sound from source so other sounds can use it. alSourcei(m_audioSources[nSourceID], AL_BUFFER, 0); pCurrent->m_sourceID = -1; } } } pCurrent = pCurrent->m_next; } } Audio* SoundManager::createSound(const char* filename) { // create Audio instance and add to linked list. return new Audio(filename); } void SoundManager::destroySound(Audio* audio) { // delete audio instance. delete audio; } void SoundManager::initialiseSound(Audio* audio, const char* filename) { SNDFILE *infile; SF_INFO audioInfo; ALuint bufferID; //Open sound file using libsndfile. memset(&audioInfo, 0, sizeof(SF_INFO)); if (!(infile = sf_open(filename, SFM_READ, &audioInfo))) { printf("Not able to open input file %s.\n", filename); puts(sf_strerror(nullptr)); return; } //Allocate enough memory to store the sound data. int sampleSize = getSampleSize(audioInfo.format); int sampleCount = (int)audioInfo.frames * audioInfo.channels; void* pAudioData = malloc(sampleSize * sampleCount); if (pAudioData == nullptr) { printf("Not able to allocate memory for input file %s.\n", filename); sf_close(infile); return; } //Read in the sound data from the file using libsndfile. //sf_read_short() is the recommended function to read data from any file format. //Using sf_read_raw() if the file is PCM 8 because sf_read_short() seems to crash on these formats. //This might be a bug in libsndfile or at least undocumented behavior. if (sampleSize == 1) sf_read_raw(infile, pAudioData, sampleCount); else sf_read_short(infile, (short*)pAudioData, sampleCount); //Create OpenAL buffer and load the sound data into it. int format = getOpenALFormat(audioInfo.format, audioInfo.channels); alGenBuffers(1, &bufferID); alBufferData(bufferID, format, pAudioData, sampleSize * sampleCount, audioInfo.samplerate); //Free memory and close file. free(pAudioData); sf_close(infile); // Create Audio instance and add to linked list. audio->m_bufferID = bufferID; if (m_audioList != nullptr) { audio->m_next = m_audioList->m_next; m_audioList->m_next = audio; } else m_audioList = audio; } void SoundManager::releaseSound(Audio* audio) { if (audio == nullptr) return; //Stop sound if it is playing. stopSoundInternal(audio); //Delete the sound data. alDeleteBuffers(1, &audio->m_bufferID); //Remove from linked list. Audio* pCurrent = m_audioList; Audio* pPrev = nullptr; while (pCurrent != nullptr) { if (pCurrent == audio) break; pPrev = pCurrent; pCurrent = pCurrent->m_next; } if (pPrev != nullptr) pPrev->m_next = pCurrent->m_next; else m_audioList = pCurrent->m_next; } void SoundManager::playSoundInternal(Audio* audio) { if (audio == nullptr) return; //Check if sound has already been bound to a source. if (audio->m_sourceID >= 0) { //If it's not already playing, play it. if (!getIsPlayingInternal(audio->m_sourceID)) { setPitchInternal(audio); setGainInternal(audio); alSourcePlay(m_audioSources[audio->m_sourceID]); } } else { //Sound not already bout to a source so find the next available one. int nSourceID = getAvailableSource(); //Bind sound to source. alSourcei(m_audioSources[nSourceID], AL_BUFFER, audio->m_bufferID); audio->m_sourceID = nSourceID; setPitchInternal(audio); setGainInternal(audio); //Play sound. alSourcePlay(m_audioSources[nSourceID]); } } void SoundManager::stopSoundInternal(Audio* pAudio) { if (pAudio != nullptr && pAudio->m_sourceID >= 0) { //Stop the sound. alSourceStop(m_audioSources[pAudio->m_sourceID]); //Unbind sound from source so other sounds can use it. alSourcei(m_audioSources[pAudio->m_sourceID], AL_BUFFER, 0); pAudio->m_sourceID = -1; } } void SoundManager::pauseSoundInternal(Audio* pAudio) { if (pAudio != nullptr && pAudio->m_sourceID >= 0 && getIsPlayingInternal(pAudio->m_sourceID)) { alSourcePause(m_audioSources[pAudio->m_sourceID]); } } bool SoundManager::getIsPlayingInternal(int nSourceID) { if (nSourceID >= 0) { ALint state; alGetSourcei(m_audioSources[nSourceID], AL_SOURCE_STATE, &state); return (state == AL_PLAYING); } return false; } bool SoundManager::getIsPausedInternal(int nSourceID) { if (nSourceID >= 0) { ALint state; alGetSourcei(m_audioSources[nSourceID], AL_SOURCE_STATE, &state); return (state == AL_PAUSED); } return false; } int SoundManager::getAvailableSource() { for (int i = 0; i < MAX_SOUNDS; ++i) { if (!getIsPlayingInternal(i) && !getIsPausedInternal(i)) return i; } return 0; } void SoundManager::setPitchInternal(Audio* pAudio) { if (pAudio != nullptr && pAudio->m_sourceID >= 0) { alSourcef(m_audioSources[pAudio->m_sourceID], AL_PITCH, pAudio->m_pitch); } } void SoundManager::setGainInternal(Audio* pAudio) { if (pAudio != nullptr && pAudio->m_sourceID >= 0) { alSourcef(m_audioSources[pAudio->m_sourceID], AL_GAIN, pAudio->m_gain); } } } // namespace aie<commit_msg>fixed crash bug in releasing sounds after a sound fails to load<commit_after>#include "SoundManager.h" #include <sndfile.hh> #include "Audio.h" #include <al.h> #include <alc.h> namespace aie { SoundManager* SoundManager::m_instance = nullptr; static int getSampleSize(int format) { int subFormat = format & SF_FORMAT_SUBMASK; switch (subFormat) { case SF_FORMAT_PCM_16: return sizeof(short); case SF_FORMAT_GSM610: return sizeof(short); case SF_FORMAT_DWVW_16: return sizeof(short); case SF_FORMAT_DPCM_16: return sizeof(short); case SF_FORMAT_VORBIS: return sizeof(short); case SF_FORMAT_ALAC_16: return sizeof(short); case SF_FORMAT_PCM_U8: return sizeof(unsigned char); //Untested formats case SF_FORMAT_PCM_24: return sizeof(char[3]); case SF_FORMAT_DWVW_24: return sizeof(char[3]); case SF_FORMAT_ALAC_24: return sizeof(char[3]); case SF_FORMAT_PCM_32: return sizeof(int); case SF_FORMAT_ALAC_32: return sizeof(int); case SF_FORMAT_FLOAT: return sizeof(float); case SF_FORMAT_DOUBLE: return sizeof(double); default: return sizeof(char); } } static int getOpenALFormat(int fileFormat, int channels) { int subFormat = fileFormat & SF_FORMAT_SUBMASK; switch (subFormat) { case SF_FORMAT_PCM_16: case SF_FORMAT_DPCM_16: case SF_FORMAT_ALAC_16: case SF_FORMAT_VORBIS: case SF_FORMAT_GSM610: { if(channels > 1) return AL_FORMAT_STEREO16; return AL_FORMAT_MONO16; } default: { if(channels > 1) return AL_FORMAT_STEREO8; return AL_FORMAT_MONO8; } } } SoundManager::SoundManager() { //Create OpenAL device and setup context. m_openALDevice = alcOpenDevice(nullptr); if (alGetError() != AL_NO_ERROR) { //error printf("Could not initialise OpenAL\n"); } m_openALContext = alcCreateContext(m_openALDevice, nullptr); if (alGetError() != AL_NO_ERROR) { //error printf("Could not initialise OpenAL\n"); } alcMakeContextCurrent(m_openALContext); if (alGetError() != AL_NO_ERROR) { //error printf("Could not initialise OpenAL\n"); } //Create sources and buffers alGenSources(MAX_SOUNDS, m_audioSources); if (alGetError() != AL_NO_ERROR) { //error printf("Could not initialise OpenAL\n"); } m_audioList = nullptr; } SoundManager::~SoundManager() { //Close OpenAL device alcMakeContextCurrent(nullptr); alcDestroyContext(m_openALContext); alcCloseDevice(m_openALDevice); } void SoundManager::update() { Audio* pCurrent = m_audioList; while (pCurrent != nullptr) { int nSourceID = pCurrent->m_sourceID; if (nSourceID >= 0) { if (!getIsPlayingInternal(nSourceID) && !getIsPausedInternal(nSourceID)) { if (pCurrent->m_looping) { playSoundInternal(pCurrent); } else { //Unbind sound from source so other sounds can use it. alSourcei(m_audioSources[nSourceID], AL_BUFFER, 0); pCurrent->m_sourceID = -1; } } } pCurrent = pCurrent->m_next; } } Audio* SoundManager::createSound(const char* filename) { // create Audio instance and add to linked list. return new Audio(filename); } void SoundManager::destroySound(Audio* audio) { // delete audio instance. delete audio; } void SoundManager::initialiseSound(Audio* audio, const char* filename) { SNDFILE *infile; SF_INFO audioInfo; ALuint bufferID; //Open sound file using libsndfile. memset(&audioInfo, 0, sizeof(SF_INFO)); if (!(infile = sf_open(filename, SFM_READ, &audioInfo))) { printf("Not able to open input file %s.\n", filename); puts(sf_strerror(nullptr)); return; } //Allocate enough memory to store the sound data. int sampleSize = getSampleSize(audioInfo.format); int sampleCount = (int)audioInfo.frames * audioInfo.channels; void* pAudioData = malloc(sampleSize * sampleCount); if (pAudioData == nullptr) { printf("Not able to allocate memory for input file %s.\n", filename); sf_close(infile); return; } //Read in the sound data from the file using libsndfile. //sf_read_short() is the recommended function to read data from any file format. //Using sf_read_raw() if the file is PCM 8 because sf_read_short() seems to crash on these formats. //This might be a bug in libsndfile or at least undocumented behavior. if (sampleSize == 1) sf_read_raw(infile, pAudioData, sampleCount); else sf_read_short(infile, (short*)pAudioData, sampleCount); //Create OpenAL buffer and load the sound data into it. int format = getOpenALFormat(audioInfo.format, audioInfo.channels); alGenBuffers(1, &bufferID); alBufferData(bufferID, format, pAudioData, sampleSize * sampleCount, audioInfo.samplerate); //Free memory and close file. free(pAudioData); sf_close(infile); // Create Audio instance and add to linked list. audio->m_bufferID = bufferID; if (m_audioList != nullptr) { audio->m_next = m_audioList->m_next; m_audioList->m_next = audio; } else m_audioList = audio; } void SoundManager::releaseSound(Audio* audio) { if (audio == nullptr) return; //Stop sound if it is playing. stopSoundInternal(audio); //Delete the sound data. alDeleteBuffers(1, &audio->m_bufferID); //Remove from linked list. Audio* pCurrent = m_audioList; Audio* pPrev = nullptr; while (pCurrent != nullptr) { if (pCurrent == audio) break; pPrev = pCurrent; pCurrent = pCurrent->m_next; } if (pCurrent != nullptr) { if (pPrev != nullptr) pPrev->m_next = pCurrent->m_next; else m_audioList = pCurrent->m_next; } } void SoundManager::playSoundInternal(Audio* audio) { if (audio == nullptr) return; //Check if sound has already been bound to a source. if (audio->m_sourceID >= 0) { //If it's not already playing, play it. if (!getIsPlayingInternal(audio->m_sourceID)) { setPitchInternal(audio); setGainInternal(audio); alSourcePlay(m_audioSources[audio->m_sourceID]); } } else { //Sound not already bout to a source so find the next available one. int nSourceID = getAvailableSource(); //Bind sound to source. alSourcei(m_audioSources[nSourceID], AL_BUFFER, audio->m_bufferID); audio->m_sourceID = nSourceID; setPitchInternal(audio); setGainInternal(audio); //Play sound. alSourcePlay(m_audioSources[nSourceID]); } } void SoundManager::stopSoundInternal(Audio* pAudio) { if (pAudio != nullptr && pAudio->m_sourceID >= 0) { //Stop the sound. alSourceStop(m_audioSources[pAudio->m_sourceID]); //Unbind sound from source so other sounds can use it. alSourcei(m_audioSources[pAudio->m_sourceID], AL_BUFFER, 0); pAudio->m_sourceID = -1; } } void SoundManager::pauseSoundInternal(Audio* pAudio) { if (pAudio != nullptr && pAudio->m_sourceID >= 0 && getIsPlayingInternal(pAudio->m_sourceID)) { alSourcePause(m_audioSources[pAudio->m_sourceID]); } } bool SoundManager::getIsPlayingInternal(int nSourceID) { if (nSourceID >= 0) { ALint state; alGetSourcei(m_audioSources[nSourceID], AL_SOURCE_STATE, &state); return (state == AL_PLAYING); } return false; } bool SoundManager::getIsPausedInternal(int nSourceID) { if (nSourceID >= 0) { ALint state; alGetSourcei(m_audioSources[nSourceID], AL_SOURCE_STATE, &state); return (state == AL_PAUSED); } return false; } int SoundManager::getAvailableSource() { for (int i = 0; i < MAX_SOUNDS; ++i) { if (!getIsPlayingInternal(i) && !getIsPausedInternal(i)) return i; } return 0; } void SoundManager::setPitchInternal(Audio* pAudio) { if (pAudio != nullptr && pAudio->m_sourceID >= 0) { alSourcef(m_audioSources[pAudio->m_sourceID], AL_PITCH, pAudio->m_pitch); } } void SoundManager::setGainInternal(Audio* pAudio) { if (pAudio != nullptr && pAudio->m_sourceID >= 0) { alSourcef(m_audioSources[pAudio->m_sourceID], AL_GAIN, pAudio->m_gain); } } } // namespace aie<|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_MAPPER_BLOCK_HH #define DUNE_GDT_MAPPER_BLOCK_HH #include <dune/common/static_assert.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/grid/multiscale/default.hh> #include <dune/gdt/spaces/interface.hh> #include "../../mapper/interface.hh" namespace Dune { namespace GDT { namespace Mapper { template <class LocalSpaceImp> class Block; namespace internal { template <class LocalSpaceType> class BlockTraits { static_assert(std::is_base_of<SpaceInterface<typename LocalSpaceType::Traits>, LocalSpaceType>::value, "LocalSpaceType has to be derived from SpaceInterface!"); public: typedef Block<LocalSpaceType> derived_type; typedef typename LocalSpaceType::MapperType::BackendType BackendType; }; // class BlockTraits } // namespace internal template <class LocalSpaceImp> class Block : public MapperInterface<internal::BlockTraits<LocalSpaceImp>> { typedef MapperInterface<internal::BlockTraits<LocalSpaceImp>> BaseType; public: typedef internal::BlockTraits<LocalSpaceImp> Traits; typedef typename Traits::BackendType BackendType; typedef LocalSpaceImp LocalSpaceType; typedef grid::Multiscale::Default<typename LocalSpaceType::GridViewType::Grid> MsGridType; private: template <class L, class E> class Compute { static_assert(AlwaysFalse<L>::value, "Not implemented for this kind of entity (only codim 0)!"); }; template <class L> class Compute<L, typename MsGridType::EntityType> { typedef typename MsGridType::EntityType Comdim0EntityType; public: static size_t numDofs(const MsGridType& ms_grid, const std::vector<std::shared_ptr<const L>>& local_spaces, const Comdim0EntityType& entity) { const size_t block = find_block_of_(ms_grid, entity); return local_spaces[block]->mapper().numDofs(entity); } static void globalIndices(const MsGridType& ms_grid, const std::vector<std::shared_ptr<const L>>& local_spaces, const std::vector<size_t>& global_start_indices, const Comdim0EntityType& entity, Dune::DynamicVector<size_t>& ret) { const size_t block = find_block_of_(ms_grid, entity); local_spaces[block]->mapper().globalIndices(entity, ret); const size_t num_dofs = local_spaces[block]->mapper().numDofs(entity); assert(ret.size() >= num_dofs); for (size_t ii = 0; ii < num_dofs; ++ii) ret[ii] += global_start_indices[block]; } static size_t mapToGlobal(const MsGridType& ms_grid, const std::vector<std::shared_ptr<const L>>& local_spaces, const std::vector<size_t>& global_start_indices, const Comdim0EntityType& entity, const size_t& localIndex) { const size_t block = find_block_of_(ms_grid, entity); const size_t block_local_index = local_spaces[block]->mapper().mapToGlobal(entity, localIndex); return global_start_indices[block] + block_local_index; } private: static size_t find_block_of_(const MsGridType& ms_grid, const Comdim0EntityType& entity) { const auto global_entity_index = ms_grid.globalGridView()->indexSet().index(entity); const auto result = ms_grid.entityToSubdomainMap()->find(global_entity_index); #ifndef NDEBUG if (result == ms_grid.entityToSubdomainMap()->end()) DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error, "Entity " << global_entity_index << " of the global grid view was not found in the multiscale grid!"); #endif // NDEBUG const size_t subdomain = result->second; #ifndef NDEBUG if (subdomain >= ms_grid.size()) DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error, "The multiscale grid is corrupted!\nIt reports Entity " << global_entity_index << " to be in subdomain " << subdomain << " while only having " << ms_grid.size() << " subdomains!"); #endif // NDEBUG return subdomain; } // ... find_block_of_(...) }; // class Compute< ..., EntityType > public: Block(const std::shared_ptr<const MsGridType> ms_grid, const std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces) : ms_grid_(ms_grid) , local_spaces_(local_spaces) , num_blocks_(local_spaces_.size()) , size_(0) , max_num_dofs_(0) { if (local_spaces_.size() != ms_grid_->size()) DUNE_THROW_COLORFULLY(Stuff::Exceptions::shapes_do_not_match, "You have to provide a local space for each subdomain of the multiscale grid!\n" << " Size of the given multiscale grid: " << ms_grid_->size() << "\n" << " Number of local spaces given: " << local_spaces_.size()); for (size_t bb = 0; bb < num_blocks_; ++bb) { max_num_dofs_ = std::max(max_num_dofs_, local_spaces_[bb]->mapper().maxNumDofs()); global_start_indices_.push_back(size_); size_ += local_spaces_[bb]->mapper().size(); } } // Block(...) size_t numBlocks() const { return num_blocks_; } size_t localSize(const size_t block) const { assert(block < num_blocks_); return local_spaces_[block]->mapper().size(); } size_t mapToGlobal(const size_t block, const size_t localIndex) const { assert(block < num_blocks_); return global_start_indices_[block] + localIndex; } const BackendType& backend() const { return local_spaces_[0]->mapper().backend(); } size_t size() const { return size_; } size_t maxNumDofs() const { return max_num_dofs_; } template <class EntityType> size_t numDofs(const EntityType& entity) const { return Compute<LocalSpaceType, EntityType>::numDofs(*ms_grid_, local_spaces_, entity); } template <class EntityType> void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const { Compute<LocalSpaceType, EntityType>::globalIndices(*ms_grid_, local_spaces_, global_start_indices_, entity, ret); } template <class EntityType> size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const { return Compute<LocalSpaceType, EntityType>::mapToGlobal( *ms_grid_, global_start_indices_, local_spaces_, entity, localIndex); } private: std::shared_ptr<const MsGridType> ms_grid_; std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces_; size_t num_blocks_; size_t size_; size_t max_num_dofs_; std::vector<size_t> global_start_indices_; }; // class Block } // namespace Mapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_MAPPER_BLOCK_HH <commit_msg>[mapper.block] make mapToGlobal() actually compile^^<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_MAPPER_BLOCK_HH #define DUNE_GDT_MAPPER_BLOCK_HH #include <dune/common/static_assert.hh> #include <dune/stuff/common/exceptions.hh> #include <dune/grid/multiscale/default.hh> #include <dune/gdt/spaces/interface.hh> #include "../../mapper/interface.hh" namespace Dune { namespace GDT { namespace Mapper { template <class LocalSpaceImp> class Block; namespace internal { template <class LocalSpaceType> class BlockTraits { static_assert(std::is_base_of<SpaceInterface<typename LocalSpaceType::Traits>, LocalSpaceType>::value, "LocalSpaceType has to be derived from SpaceInterface!"); public: typedef Block<LocalSpaceType> derived_type; typedef typename LocalSpaceType::MapperType::BackendType BackendType; }; // class BlockTraits } // namespace internal template <class LocalSpaceImp> class Block : public MapperInterface<internal::BlockTraits<LocalSpaceImp>> { typedef MapperInterface<internal::BlockTraits<LocalSpaceImp>> BaseType; public: typedef internal::BlockTraits<LocalSpaceImp> Traits; typedef typename Traits::BackendType BackendType; typedef LocalSpaceImp LocalSpaceType; typedef grid::Multiscale::Default<typename LocalSpaceType::GridViewType::Grid> MsGridType; private: template <class L, class E> class Compute { static_assert(AlwaysFalse<L>::value, "Not implemented for this kind of entity (only codim 0)!"); }; template <class L> class Compute<L, typename MsGridType::EntityType> { typedef typename MsGridType::EntityType Comdim0EntityType; public: static size_t numDofs(const MsGridType& ms_grid, const std::vector<std::shared_ptr<const L>>& local_spaces, const Comdim0EntityType& entity) { const size_t block = find_block_of_(ms_grid, entity); return local_spaces[block]->mapper().numDofs(entity); } static void globalIndices(const MsGridType& ms_grid, const std::vector<std::shared_ptr<const L>>& local_spaces, const std::vector<size_t>& global_start_indices, const Comdim0EntityType& entity, Dune::DynamicVector<size_t>& ret) { const size_t block = find_block_of_(ms_grid, entity); local_spaces[block]->mapper().globalIndices(entity, ret); const size_t num_dofs = local_spaces[block]->mapper().numDofs(entity); assert(ret.size() >= num_dofs); for (size_t ii = 0; ii < num_dofs; ++ii) ret[ii] += global_start_indices[block]; } static size_t mapToGlobal(const MsGridType& ms_grid, const std::vector<std::shared_ptr<const L>>& local_spaces, const std::vector<size_t>& global_start_indices, const Comdim0EntityType& entity, const size_t& localIndex) { const size_t block = find_block_of_(ms_grid, entity); const size_t block_local_index = local_spaces[block]->mapper().mapToGlobal(entity, localIndex); return global_start_indices[block] + block_local_index; } private: static size_t find_block_of_(const MsGridType& ms_grid, const Comdim0EntityType& entity) { const auto global_entity_index = ms_grid.globalGridView()->indexSet().index(entity); const auto result = ms_grid.entityToSubdomainMap()->find(global_entity_index); #ifndef NDEBUG if (result == ms_grid.entityToSubdomainMap()->end()) DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error, "Entity " << global_entity_index << " of the global grid view was not found in the multiscale grid!"); #endif // NDEBUG const size_t subdomain = result->second; #ifndef NDEBUG if (subdomain >= ms_grid.size()) DUNE_THROW_COLORFULLY(Stuff::Exceptions::internal_error, "The multiscale grid is corrupted!\nIt reports Entity " << global_entity_index << " to be in subdomain " << subdomain << " while only having " << ms_grid.size() << " subdomains!"); #endif // NDEBUG return subdomain; } // ... find_block_of_(...) }; // class Compute< ..., EntityType > public: Block(const std::shared_ptr<const MsGridType> ms_grid, const std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces) : ms_grid_(ms_grid) , local_spaces_(local_spaces) , num_blocks_(local_spaces_.size()) , size_(0) , max_num_dofs_(0) { if (local_spaces_.size() != ms_grid_->size()) DUNE_THROW_COLORFULLY(Stuff::Exceptions::shapes_do_not_match, "You have to provide a local space for each subdomain of the multiscale grid!\n" << " Size of the given multiscale grid: " << ms_grid_->size() << "\n" << " Number of local spaces given: " << local_spaces_.size()); for (size_t bb = 0; bb < num_blocks_; ++bb) { max_num_dofs_ = std::max(max_num_dofs_, local_spaces_[bb]->mapper().maxNumDofs()); global_start_indices_.push_back(size_); size_ += local_spaces_[bb]->mapper().size(); } } // Block(...) size_t numBlocks() const { return num_blocks_; } size_t localSize(const size_t block) const { assert(block < num_blocks_); return local_spaces_[block]->mapper().size(); } size_t mapToGlobal(const size_t block, const size_t localIndex) const { assert(block < num_blocks_); return global_start_indices_[block] + localIndex; } const BackendType& backend() const { return local_spaces_[0]->mapper().backend(); } size_t size() const { return size_; } size_t maxNumDofs() const { return max_num_dofs_; } template <class EntityType> size_t numDofs(const EntityType& entity) const { return Compute<LocalSpaceType, EntityType>::numDofs(*ms_grid_, local_spaces_, entity); } template <class EntityType> void globalIndices(const EntityType& entity, Dune::DynamicVector<size_t>& ret) const { Compute<LocalSpaceType, EntityType>::globalIndices(*ms_grid_, local_spaces_, global_start_indices_, entity, ret); } template <class EntityType> size_t mapToGlobal(const EntityType& entity, const size_t& localIndex) const { return Compute<LocalSpaceType, EntityType>::mapToGlobal( *ms_grid_, local_spaces_, global_start_indices_, entity, localIndex); } // ... mapToGlobal(...) private: std::shared_ptr<const MsGridType> ms_grid_; std::vector<std::shared_ptr<const LocalSpaceType>> local_spaces_; size_t num_blocks_; size_t size_; size_t max_num_dofs_; std::vector<size_t> global_start_indices_; }; // class Block } // namespace Mapper } // namespace GDT } // namespace Dune #endif // DUNE_GDT_MAPPER_BLOCK_HH <|endoftext|>
<commit_before>/// /// @file cmdoptions.cpp /// @brief Parse command-line options for the primesieve console /// (terminal) application. /// /// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "cmdoptions.hpp" #include <primesieve/calculator.hpp> #include <primesieve/CpuInfo.hpp> #include <primesieve/PrimeSieve.hpp> #include <primesieve/primesieve_error.hpp> #include <cstddef> #include <cstdlib> #include <iostream> #include <map> #include <stdint.h> #include <string> void help(); void version(); using namespace std; using namespace primesieve; namespace { /// Command-line option /// e.g. opt = "--threads", val = "4" struct Option { string str; string opt; string val; template <typename T> T getValue() const { if (val.empty()) throw primesieve_error("missing value for option " + str); return calculator::eval<T>(val); } }; enum OptionID { OPTION_COUNT, OPTION_CPU_INFO, OPTION_HELP, OPTION_NTH_PRIME, OPTION_NO_STATUS, OPTION_NUMBER, OPTION_DISTANCE, OPTION_PRINT, OPTION_QUIET, OPTION_SIZE, OPTION_THREADS, OPTION_TIME, OPTION_VERSION }; /// Command-line options map<string, OptionID> optionMap = { { "-c", OPTION_COUNT }, { "--count", OPTION_COUNT }, { "--cpu-info", OPTION_CPU_INFO }, { "-h", OPTION_HELP }, { "--help", OPTION_HELP }, { "-n", OPTION_NTH_PRIME }, { "--nthprime", OPTION_NTH_PRIME }, { "--nth-prime", OPTION_NTH_PRIME }, { "--no-status", OPTION_NO_STATUS }, { "--number", OPTION_NUMBER }, { "-d", OPTION_DISTANCE }, { "--dist", OPTION_DISTANCE }, { "-p", OPTION_PRINT }, { "--print", OPTION_PRINT }, { "-q", OPTION_QUIET }, { "--quiet", OPTION_QUIET }, { "-s", OPTION_SIZE }, { "--size", OPTION_SIZE }, { "-t", OPTION_THREADS }, { "--threads", OPTION_THREADS }, { "--time", OPTION_TIME }, { "-v", OPTION_VERSION }, { "--version", OPTION_VERSION } }; void optionPrint(Option& opt, CmdOptions& opts) { opts.quiet = true; // by default print primes if (opt.val.empty()) opt.val = "1"; switch (opt.getValue<int>()) { case 1: opts.flags |= PRINT_PRIMES; break; case 2: opts.flags |= PRINT_TWINS; break; case 3: opts.flags |= PRINT_TRIPLETS; break; case 4: opts.flags |= PRINT_QUADRUPLETS; break; case 5: opts.flags |= PRINT_QUINTUPLETS; break; case 6: opts.flags |= PRINT_SEXTUPLETS; break; default: throw primesieve_error("invalid option " + opt.str); } } void optionCount(Option& opt, CmdOptions& opts) { // by default count primes if (opt.val.empty()) opt.val = "1"; int n = opt.getValue<int>(); for (; n > 0; n /= 10) { switch (n % 10) { case 1: opts.flags |= COUNT_PRIMES; break; case 2: opts.flags |= COUNT_TWINS; break; case 3: opts.flags |= COUNT_TRIPLETS; break; case 4: opts.flags |= COUNT_QUADRUPLETS; break; case 5: opts.flags |= COUNT_QUINTUPLETS; break; case 6: opts.flags |= COUNT_SEXTUPLETS; break; default: throw primesieve_error("invalid option " + opt.str); } } } /// e.g. "--thread=4" -> return "--thread" string getOption(const string& str) { size_t pos = str.find_first_of("=0123456789"); if (pos == string::npos) return str; else return str.substr(0, pos); } /// e.g. "--thread=4" -> return "4" string getValue(const string& str) { size_t pos = str.find_first_of("0123456789"); if (pos == string::npos) return string(); else return str.substr(pos); } /// e.g. "--threads=8" /// -> opt.opt = "--threads" /// -> opt.val = "8" /// Option makeOption(const string& str) { Option opt; opt.str = str; opt.opt = getOption(str); opt.val = getValue(str); if (opt.opt.empty() && !opt.val.empty()) opt.opt = "--number"; if (!optionMap.count(opt.opt)) throw primesieve_error("unknown option " + str); return opt; } void optionCpuInfo() { const CpuInfo cpu; if (cpu.hasCpuName()) cout << cpu.cpuName() << endl; else cout << "CPU name: unknown" << endl; if (cpu.hasCpuCores()) cout << "Number of cores: " << cpu.cpuCores() << endl; else cout << "Number of cores: unknown" << endl; if (cpu.hasCpuThreads()) cout << "Number of threads: " << cpu.cpuThreads() << endl; else cout << "Number of threads: unknown" << endl; if (cpu.hasThreadsPerCore()) cout << "Threads per core: " << cpu.threadsPerCore() << endl; else cout << "Threads per core: unknown" << endl; if (cpu.hasL1Cache()) cout << "L1 cache size: " << cpu.l1CacheSize() / (1 << 10) << " KiB" << endl; if (cpu.hasL2Cache()) cout << "L2 cache size: " << cpu.l2CacheSize() / (1 << 10) << " KiB" << endl; if (cpu.hasL3Cache()) cout << "L3 cache size: " << cpu.l3CacheSize() / (double) (1 << 20) << " MiB" << endl; if (cpu.hasL1Cache()) { if (!cpu.hasL1Sharing()) cout << "L1 cache sharing: unknown" << endl; else cout << "L1 cache sharing: " << cpu.l1Sharing() << ((cpu.l1Sharing() > 1) ? " threads" : " thread") << endl; } if (cpu.hasL2Cache()) { if (!cpu.hasL2Sharing()) cout << "L2 cache sharing: unknown" << endl; else cout << "L2 cache sharing: " << cpu.l2Sharing() << ((cpu.l2Sharing() > 1) ? " threads" : " thread") << endl; } if (cpu.hasL3Cache()) { if (!cpu.hasL3Sharing()) cout << "L3 cache sharing: unknown" << endl; else cout << "L3 cache sharing: " << cpu.l3Sharing() << ((cpu.l3Sharing() > 1) ? " threads" : " thread") << endl; } if (!cpu.hasL1Cache() && !cpu.hasL2Cache() && !cpu.hasL3Cache()) { cout << "L1 cache size: unknown" << endl; cout << "L2 cache size: unknown" << endl; cout << "L3 cache size: unknown" << endl; cout << "L1 cache sharing: unknown" << endl; cout << "L2 cache sharing: unknown" << endl; cout << "L3 cache sharing: unknown" << endl; } exit(0); } } // namespace CmdOptions parseOptions(int argc, char* argv[]) { CmdOptions opts; for (int i = 1; i < argc; i++) { Option opt = makeOption(argv[i]); switch (optionMap[opt.opt]) { case OPTION_COUNT: optionCount(opt, opts); break; case OPTION_CPU_INFO: optionCpuInfo(); break; case OPTION_PRINT: optionPrint(opt, opts); break; case OPTION_SIZE: opts.sieveSize = opt.getValue<int>(); break; case OPTION_THREADS: opts.threads = opt.getValue<int>(); break; case OPTION_QUIET: opts.quiet = true; break; case OPTION_NTH_PRIME: opts.nthPrime = true; break; case OPTION_NO_STATUS: opts.status = false; break; case OPTION_TIME: opts.time = true; break; case OPTION_NUMBER: opts.numbers.push_back(opt.getValue<uint64_t>()); break; case OPTION_DISTANCE: opts.numbers.push_back(opt.getValue<uint64_t>() + opts.numbers[0]); break; case OPTION_VERSION: version(); break; case OPTION_HELP: help(); break; } } if (opts.numbers.empty()) throw primesieve_error("missing STOP number"); if (opts.quiet) opts.status = false; else opts.time = true; return opts; } <commit_msg>Fix array out of bounds<commit_after>/// /// @file cmdoptions.cpp /// @brief Parse command-line options for the primesieve console /// (terminal) application. /// /// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "cmdoptions.hpp" #include <primesieve/calculator.hpp> #include <primesieve/CpuInfo.hpp> #include <primesieve/PrimeSieve.hpp> #include <primesieve/primesieve_error.hpp> #include <cstddef> #include <cstdlib> #include <iostream> #include <map> #include <stdint.h> #include <string> void help(); void version(); using namespace std; using namespace primesieve; namespace { /// Command-line option /// e.g. opt = "--threads", val = "4" struct Option { string str; string opt; string val; template <typename T> T getValue() const { if (val.empty()) throw primesieve_error("missing value for option " + str); return calculator::eval<T>(val); } }; enum OptionID { OPTION_COUNT, OPTION_CPU_INFO, OPTION_HELP, OPTION_NTH_PRIME, OPTION_NO_STATUS, OPTION_NUMBER, OPTION_DISTANCE, OPTION_PRINT, OPTION_QUIET, OPTION_SIZE, OPTION_THREADS, OPTION_TIME, OPTION_VERSION }; /// Command-line options map<string, OptionID> optionMap = { { "-c", OPTION_COUNT }, { "--count", OPTION_COUNT }, { "--cpu-info", OPTION_CPU_INFO }, { "-h", OPTION_HELP }, { "--help", OPTION_HELP }, { "-n", OPTION_NTH_PRIME }, { "--nthprime", OPTION_NTH_PRIME }, { "--nth-prime", OPTION_NTH_PRIME }, { "--no-status", OPTION_NO_STATUS }, { "--number", OPTION_NUMBER }, { "-d", OPTION_DISTANCE }, { "--dist", OPTION_DISTANCE }, { "-p", OPTION_PRINT }, { "--print", OPTION_PRINT }, { "-q", OPTION_QUIET }, { "--quiet", OPTION_QUIET }, { "-s", OPTION_SIZE }, { "--size", OPTION_SIZE }, { "-t", OPTION_THREADS }, { "--threads", OPTION_THREADS }, { "--time", OPTION_TIME }, { "-v", OPTION_VERSION }, { "--version", OPTION_VERSION } }; void optionPrint(Option& opt, CmdOptions& opts) { opts.quiet = true; // by default print primes if (opt.val.empty()) opt.val = "1"; switch (opt.getValue<int>()) { case 1: opts.flags |= PRINT_PRIMES; break; case 2: opts.flags |= PRINT_TWINS; break; case 3: opts.flags |= PRINT_TRIPLETS; break; case 4: opts.flags |= PRINT_QUADRUPLETS; break; case 5: opts.flags |= PRINT_QUINTUPLETS; break; case 6: opts.flags |= PRINT_SEXTUPLETS; break; default: throw primesieve_error("invalid option " + opt.str); } } void optionCount(Option& opt, CmdOptions& opts) { // by default count primes if (opt.val.empty()) opt.val = "1"; int n = opt.getValue<int>(); for (; n > 0; n /= 10) { switch (n % 10) { case 1: opts.flags |= COUNT_PRIMES; break; case 2: opts.flags |= COUNT_TWINS; break; case 3: opts.flags |= COUNT_TRIPLETS; break; case 4: opts.flags |= COUNT_QUADRUPLETS; break; case 5: opts.flags |= COUNT_QUINTUPLETS; break; case 6: opts.flags |= COUNT_SEXTUPLETS; break; default: throw primesieve_error("invalid option " + opt.str); } } } void optionDistance(Option& opt, CmdOptions& opts) { uint64_t start = 0; uint64_t val = opt.getValue<uint64_t>(); auto& numbers = opts.numbers; if (!numbers.empty()) start = numbers[0]; numbers.push_back(start + val); } /// e.g. "--thread=4" -> return "--thread" string getOption(const string& str) { size_t pos = str.find_first_of("=0123456789"); if (pos == string::npos) return str; else return str.substr(0, pos); } /// e.g. "--thread=4" -> return "4" string getValue(const string& str) { size_t pos = str.find_first_of("0123456789"); if (pos == string::npos) return string(); else return str.substr(pos); } /// e.g. "--threads=8" /// -> opt.opt = "--threads" /// -> opt.val = "8" /// Option makeOption(const string& str) { Option opt; opt.str = str; opt.opt = getOption(str); opt.val = getValue(str); if (opt.opt.empty() && !opt.val.empty()) opt.opt = "--number"; if (!optionMap.count(opt.opt)) throw primesieve_error("unknown option " + str); return opt; } void optionCpuInfo() { const CpuInfo cpu; if (cpu.hasCpuName()) cout << cpu.cpuName() << endl; else cout << "CPU name: unknown" << endl; if (cpu.hasCpuCores()) cout << "Number of cores: " << cpu.cpuCores() << endl; else cout << "Number of cores: unknown" << endl; if (cpu.hasCpuThreads()) cout << "Number of threads: " << cpu.cpuThreads() << endl; else cout << "Number of threads: unknown" << endl; if (cpu.hasThreadsPerCore()) cout << "Threads per core: " << cpu.threadsPerCore() << endl; else cout << "Threads per core: unknown" << endl; if (cpu.hasL1Cache()) cout << "L1 cache size: " << cpu.l1CacheSize() / (1 << 10) << " KiB" << endl; if (cpu.hasL2Cache()) cout << "L2 cache size: " << cpu.l2CacheSize() / (1 << 10) << " KiB" << endl; if (cpu.hasL3Cache()) cout << "L3 cache size: " << cpu.l3CacheSize() / (double) (1 << 20) << " MiB" << endl; if (cpu.hasL1Cache()) { if (!cpu.hasL1Sharing()) cout << "L1 cache sharing: unknown" << endl; else cout << "L1 cache sharing: " << cpu.l1Sharing() << ((cpu.l1Sharing() > 1) ? " threads" : " thread") << endl; } if (cpu.hasL2Cache()) { if (!cpu.hasL2Sharing()) cout << "L2 cache sharing: unknown" << endl; else cout << "L2 cache sharing: " << cpu.l2Sharing() << ((cpu.l2Sharing() > 1) ? " threads" : " thread") << endl; } if (cpu.hasL3Cache()) { if (!cpu.hasL3Sharing()) cout << "L3 cache sharing: unknown" << endl; else cout << "L3 cache sharing: " << cpu.l3Sharing() << ((cpu.l3Sharing() > 1) ? " threads" : " thread") << endl; } if (!cpu.hasL1Cache() && !cpu.hasL2Cache() && !cpu.hasL3Cache()) { cout << "L1 cache size: unknown" << endl; cout << "L2 cache size: unknown" << endl; cout << "L3 cache size: unknown" << endl; cout << "L1 cache sharing: unknown" << endl; cout << "L2 cache sharing: unknown" << endl; cout << "L3 cache sharing: unknown" << endl; } exit(0); } } // namespace CmdOptions parseOptions(int argc, char* argv[]) { CmdOptions opts; for (int i = 1; i < argc; i++) { Option opt = makeOption(argv[i]); switch (optionMap[opt.opt]) { case OPTION_COUNT: optionCount(opt, opts); break; case OPTION_CPU_INFO: optionCpuInfo(); break; case OPTION_DISTANCE: optionDistance(opt, opts); break; case OPTION_PRINT: optionPrint(opt, opts); break; case OPTION_SIZE: opts.sieveSize = opt.getValue<int>(); break; case OPTION_THREADS: opts.threads = opt.getValue<int>(); break; case OPTION_QUIET: opts.quiet = true; break; case OPTION_NTH_PRIME: opts.nthPrime = true; break; case OPTION_NO_STATUS: opts.status = false; break; case OPTION_TIME: opts.time = true; break; case OPTION_NUMBER: opts.numbers.push_back(opt.getValue<uint64_t>()); break; case OPTION_VERSION: version(); break; case OPTION_HELP: help(); break; } } if (opts.numbers.empty()) throw primesieve_error("missing STOP number"); if (opts.quiet) opts.status = false; else opts.time = true; return opts; } <|endoftext|>
<commit_before>// performance testing for gridding. #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <sys/time.h> extern "C" { #include "griddingSimple_float.h" } #include <static_image.h> #include <image_io.h> static double get_s(void) { struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + 1.0e-6*tv.tv_usec; } /* get_s */ static void testGriddingSimpleConformance(void) { int nBaselines = 10; int nTimesteps = 100; int maxSupportSize = 101; int resultWidthHeight = 2048; int bl, ts, i, j; Image<float> UVWTriples(nBaselines, nTimesteps, 3); Image<float> visibilities(nBaselines, nTimesteps, 8); Image<float> support(nBaselines, maxSupportSize, maxSupportSize, 2); Image<int> supportSize(nBaselines, 1); // looping over baselines and set support sizes, etc. for (bl = 0; bl < nBaselines; bl++) { // setting up support. int supportSizeForBL = maxSupportSize; supportSize(bl) = supportSizeForBL; for (i=0;i<supportSizeForBL; i++) { for (j=0;j<supportSizeForBL; j++) { float value = 0.0; // values are zeroes except if (i==j || i == (supportSizeForBL-j-1)) // both diagonals are ones. value = 1.0; support(bl, i, j, 0) = value; support(bl, i, j, 0) = -value; } } // Setting up UVW triples and visibilities. for (ts = 0; ts < nTimesteps; ts ++) { // Setting up UVW. // U and V are set as pseudorandom to cover all the image. int U = (bl*131+ts*61) % resultWidthHeight; int V = (bl*17+ts*97) % resultWidthHeight; UVWTriples(bl, ts, 0) = (float)U; UVWTriples(bl, ts, 1) = (float)V; UVWTriples(bl, ts, 2) = (float)11; // Setting up visibilities. for (i=0;i<8;i++) { int vis = (bl*101+ts*313 + i*503) % 1000; visibilities(bl, ts, 0) = ((float)vis)/1000.0; } } } // execute the algorithm. Image<float> result(resultWidthHeight, resultWidthHeight, 4, 2); printf("Starting.\n"); double runtime = 0; runtime -= get_s(); int errCode = griddingSimple_float(UVWTriples, visibilities, support, supportSize, result); runtime += get_s(); double flopCount = nBaselines; // we run across all baselines. flopCount *= nTimesteps; // and also across all timesteps. flopCount *= maxSupportSize*maxSupportSize; // for each baseline, timestep pair we perform gridding with square support flopCount *= 8*2; // 4 polarizations, each is complex. We multiply and add. printf("execution error code %d.\n",errCode); printf("time to execute %lf s.\n", runtime); printf("FLOPS %lf.\n", flopCount/runtime); } /* testGriddingSimpleConformance */ int main(int argc, char **argv) { testGriddingSimpleConformance(); return 0; } <commit_msg>Test loop without overdraw<commit_after>// performance testing for gridding. #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <sys/time.h> extern "C" { #include "griddingSimple_float.h" } #include <static_image.h> #include <image_io.h> static double get_s(void) { struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + 1.0e-6*tv.tv_usec; } /* get_s */ static inline int max(int a, int b) { return a < b ? b : a; } static inline int min(int a, int b) { return a > b ? b : a; } static void simpleGriddingLoop(Image<float> &UVWTriples, Image<float> &visibilities, Image<float> &support, Image<int> &supportSize, Image<float> &result) { int bl, ts; int u, v; int uStep = 8, vStep = 32; float *resultBuffer = &result(0,0,0,0); for (u = 0; u < result.extent(0); u++) { for(v = 0; v < result.extent(1); v++) { int pol; for (pol = 0; pol < 4; pol++) { result(u,v,pol,0) = 0.0; result(u,v,pol,1) = 0.0; } } } // cutting image into parts that fit into cache. for (u = 0; u<result.extent(0); u+= uStep) { for (v = 0; v < result.extent(1); v+= vStep) { // then for each that part we walk along all points. for (bl = 0; bl < UVWTriples.extent(0); bl++) { int widthHalf = supportSize(bl)/2; for (ts = 0; ts < UVWTriples.extent(1); ts++) { int U = UVWTriples(bl, ts, 0); if (U + widthHalf < u || U-widthHalf >= u+uStep) continue; int V = UVWTriples(bl, ts, 1); if (V + widthHalf < v || V-widthHalf >= v+vStep) continue; int uInner, vInner; for (uInner = max(u,U-widthHalf); uInner <= min(u+uStep-1, U+widthHalf); uInner++) { for (vInner = max(v,V-widthHalf); vInner <= min(v+vStep-1, V+widthHalf); vInner++) { int x = uInner - (U-widthHalf); int y = vInner - (V-widthHalf); float supR = support(bl, x, y, 0); float supI = support(bl, x, y, 1); int pol; for (pol=0;pol<4;pol++) { result(uInner, vInner, pol, 0) += supR * visibilities(bl, ts, pol*2) ; result(uInner, vInner, pol, 1) += supR * visibilities(bl, ts, pol*2+1) ; } } } } } } } } /* simpleGriddingLoop */ static bool resultsEqual(Image<float> &result1, Image<float> &result2) { int diffCount = 0; for (int u=0;u<result1.extent(0);u++) { for (int v=0;v<result1.extent(1);v++) { for (int pol=0;pol<result1.extent(2);pol++) { for (int i=0;i<result1.extent(3);i++) { bool neq = result1(u,v,pol,i) != result2(u,v,pol,i); if (neq) { printf("difference at (%d, %d, %d, %d), %f != %f.\n",u,v,pol,i,result1(u,v,pol,i), result2(u,v,pol,i)); diffCount ++; if (diffCount > 10) return false; } } } } } return diffCount == 0; } /* resultsEqual */ static void testGriddingSimpleConformance(void) { int nBaselines = 10; int nTimesteps = 10; int maxSupportSize = 101; int resultWidthHeight = 2048; int bl, ts, i, j; Image<float> UVWTriples(nBaselines, nTimesteps, 3); Image<float> visibilities(nBaselines, nTimesteps, 8); Image<float> support(nBaselines, maxSupportSize, maxSupportSize, 2); Image<int> supportSize(nBaselines); // looping over baselines and set support sizes, etc. for (bl = 0; bl < nBaselines; bl++) { // setting up support. int supportSizeForBL = maxSupportSize; supportSize(bl) = supportSizeForBL; for (i=0;i<supportSizeForBL; i++) { for (j=0;j<supportSizeForBL; j++) { float value = 0.0; // values are zeroes except if (i==j || i == (supportSizeForBL-j-1)) // both diagonals are ones. value = 1.0; support(bl, i, j, 0) = value; support(bl, i, j, 0) = -value; } } // Setting up UVW triples and visibilities. for (ts = 0; ts < nTimesteps; ts ++) { // Setting up UVW. // U and V are set as pseudorandom to cover all the image. int U = (bl*131+ts*61) % resultWidthHeight; int V = (bl*17+ts*97) % resultWidthHeight; UVWTriples(bl, ts, 0) = (float)U; UVWTriples(bl, ts, 1) = (float)V; UVWTriples(bl, ts, 2) = (float)11; // Setting up visibilities. for (i=0;i<8;i++) { int vis = (bl*101+ts*313 + i*503) % 1000; visibilities(bl, ts, 0) = ((float)vis)/1000.0; } } } // execute the algorithm. Image<float> result(resultWidthHeight, resultWidthHeight, 4, 2); printf("Starting.\n"); double runtime = 0; runtime -= get_s(); int errCode = griddingSimple_float(UVWTriples, visibilities, support, supportSize, result); runtime += get_s(); double flopCount = nBaselines; // we run across all baselines. flopCount *= nTimesteps; // and also across all timesteps. flopCount *= maxSupportSize*maxSupportSize; // for each baseline, timestep pair we perform gridding with square support flopCount *= 8*2; // 4 polarizations, each is complex. We multiply and add. printf("execution error code %d.\n",errCode); printf("time to execute %lf s.\n", runtime); printf("FLOPS %lf.\n", flopCount/runtime); runtime = 0; Image<float> result2(resultWidthHeight, resultWidthHeight, 4, 2); runtime -= get_s(); simpleGriddingLoop(UVWTriples, visibilities, support, supportSize, result2); runtime += get_s(); if (!resultsEqual(result, result2)) printf("results are different, all bets are off.\n"); printf("time to execute hand made loop %lf s.\n", runtime); printf("FLOPS %lf.\n", flopCount/runtime); } /* testGriddingSimpleConformance */ int main(int argc, char **argv) { testGriddingSimpleConformance(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 <sstream> #include "otbCoordinateToName.h" #include "otbMacro.h" #include "otbUtils.h" #include "otb_tinyxml.h" #include "otbCurlHelper.h" #include "itkMersenneTwisterRandomVariateGenerator.h" namespace otb { /** * Constructor */ CoordinateToName::CoordinateToName() : m_Lon(-1000.0), m_Lat(-1000.0), m_Multithread(false), m_IsValid(false), m_PlaceName(""), m_CountryName("") { /* //Avoid collision between different instance of the class typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGenType; RandomGenType::Pointer randomGen = RandomGenType::GetInstance(); randomGen->SetSeed(reinterpret_cast<long int>(this)); //make sure the seed is unique for this class unsigned int randomNum = randomGen->GetIntegerVariate(); std::stringstream filename; filename << "tmp-coordinateToName-SignayriUt1-"; filename << randomNum; filename << ".xml"; m_TempFileName = filename.str(); */ m_Curl = CurlHelper::New(); m_Threader = itk::MultiThreader::New(); m_UpdateDistance = 0.01; //about 1km at equator } /** * PrintSelf */ void CoordinateToName ::PrintSelf(std::ostream& os, itk::Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << " m_Lon " << m_Lon << std::endl; os << indent << " m_Lat " << m_Lat << std::endl; os << indent << " m_PlaceName " << m_PlaceName << std::endl; } bool CoordinateToName::Evaluate() { if (m_Multithread) { m_Threader->SpawnThread(ThreadFunction, this); } else { DoEvaluate(); } return true; } ITK_THREAD_RETURN_TYPE CoordinateToName::ThreadFunction(void *arg) { struct itk::MultiThreader::ThreadInfoStruct * pInfo = (itk::MultiThreader::ThreadInfoStruct *) (arg); CoordinateToName::Pointer lThis = (CoordinateToName*) (pInfo->UserData); lThis->DoEvaluate(); return ITK_THREAD_RETURN_VALUE; } void CoordinateToName::DoEvaluate() { m_PlaceName = ""; m_CountryName = ""; m_IsValid = false; if (Utils::IsLonLatValid(m_Lon, m_Lat)) { std::ostringstream urlStream; urlStream << "http://api.geonames.org/findNearbyPlaceName?lat="; urlStream << m_Lat; urlStream << "&lng="; urlStream << m_Lon; urlStream << "&username=otbteam"; otbMsgDevMacro("CoordinateToName: retrieve url " << urlStream.str()); try { m_Curl->RetrieveUrlInMemory(urlStream.str(), m_CurlOutput); m_IsValid = true; } catch(itk::ExceptionObject) { m_IsValid = false; } if(m_IsValid) { std::string placeName = ""; std::string countryName = ""; ParseXMLGeonames(placeName, countryName); m_PlaceName = placeName; m_CountryName = countryName; } } } void CoordinateToName::ParseXMLGeonames(std::string& placeName, std::string& countryName) const { TiXmlDocument doc; doc.Parse(m_CurlOutput.c_str()); if (!doc.Error()) { TiXmlHandle docHandle(&doc); TiXmlElement* childName = docHandle.FirstChild("geonames").FirstChild("geoname"). FirstChild("name").Element(); if (childName) { placeName = childName->GetText(); } TiXmlElement* childCountryName = docHandle.FirstChild("geonames").FirstChild("geoname"). FirstChild("countryName").Element(); if (childCountryName) { countryName = childCountryName->GetText(); } otbMsgDevMacro(<< "Near " << placeName << " in " << countryName); } } } // namespace otb <commit_msg>WRG: fix again catching polymorphic type by value<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 <sstream> #include "otbCoordinateToName.h" #include "otbMacro.h" #include "otbUtils.h" #include "otb_tinyxml.h" #include "otbCurlHelper.h" #include "itkMersenneTwisterRandomVariateGenerator.h" namespace otb { /** * Constructor */ CoordinateToName::CoordinateToName() : m_Lon(-1000.0), m_Lat(-1000.0), m_Multithread(false), m_IsValid(false), m_PlaceName(""), m_CountryName("") { /* //Avoid collision between different instance of the class typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGenType; RandomGenType::Pointer randomGen = RandomGenType::GetInstance(); randomGen->SetSeed(reinterpret_cast<long int>(this)); //make sure the seed is unique for this class unsigned int randomNum = randomGen->GetIntegerVariate(); std::stringstream filename; filename << "tmp-coordinateToName-SignayriUt1-"; filename << randomNum; filename << ".xml"; m_TempFileName = filename.str(); */ m_Curl = CurlHelper::New(); m_Threader = itk::MultiThreader::New(); m_UpdateDistance = 0.01; //about 1km at equator } /** * PrintSelf */ void CoordinateToName ::PrintSelf(std::ostream& os, itk::Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << " m_Lon " << m_Lon << std::endl; os << indent << " m_Lat " << m_Lat << std::endl; os << indent << " m_PlaceName " << m_PlaceName << std::endl; } bool CoordinateToName::Evaluate() { if (m_Multithread) { m_Threader->SpawnThread(ThreadFunction, this); } else { DoEvaluate(); } return true; } ITK_THREAD_RETURN_TYPE CoordinateToName::ThreadFunction(void *arg) { struct itk::MultiThreader::ThreadInfoStruct * pInfo = (itk::MultiThreader::ThreadInfoStruct *) (arg); CoordinateToName::Pointer lThis = (CoordinateToName*) (pInfo->UserData); lThis->DoEvaluate(); return ITK_THREAD_RETURN_VALUE; } void CoordinateToName::DoEvaluate() { m_PlaceName = ""; m_CountryName = ""; m_IsValid = false; if (Utils::IsLonLatValid(m_Lon, m_Lat)) { std::ostringstream urlStream; urlStream << "http://api.geonames.org/findNearbyPlaceName?lat="; urlStream << m_Lat; urlStream << "&lng="; urlStream << m_Lon; urlStream << "&username=otbteam"; otbMsgDevMacro("CoordinateToName: retrieve url " << urlStream.str()); try { m_Curl->RetrieveUrlInMemory(urlStream.str(), m_CurlOutput); m_IsValid = true; } catch( itk::ExceptionObject & ) { m_IsValid = false; } if(m_IsValid) { std::string placeName = ""; std::string countryName = ""; ParseXMLGeonames(placeName, countryName); m_PlaceName = placeName; m_CountryName = countryName; } } } void CoordinateToName::ParseXMLGeonames(std::string& placeName, std::string& countryName) const { TiXmlDocument doc; doc.Parse(m_CurlOutput.c_str()); if (!doc.Error()) { TiXmlHandle docHandle(&doc); TiXmlElement* childName = docHandle.FirstChild("geonames").FirstChild("geoname"). FirstChild("name").Element(); if (childName) { placeName = childName->GetText(); } TiXmlElement* childCountryName = docHandle.FirstChild("geonames").FirstChild("geoname"). FirstChild("countryName").Element(); if (childCountryName) { countryName = childCountryName->GetText(); } otbMsgDevMacro(<< "Near " << placeName << " in " << countryName); } } } // namespace otb <|endoftext|>
<commit_before>#include "mpdas.h" #define APIKEY "a0ed2629d3d28606f67d7214c916788d" #define SECRET "295f31c5d28215215b1503fb0327cc01" #define CURL_MAX_RETRIES 3 #define CURL_RETRY_DELAY 3 // Seconds CAudioScrobbler* AudioScrobbler = 0; #define CLEANUP() _response.clear() size_t writecb(void* ptr, size_t size, size_t nmemb, void *stream) { AudioScrobbler->ReportResponse((char*)ptr, size*nmemb); return size*nmemb; } CAudioScrobbler::CAudioScrobbler() { _failcount = 0; _authed = false; _response = ""; _handle = curl_easy_init(); if(!_handle) { eprintf("%s", "Could not initialize CURL."); exit(EXIT_FAILURE); } } CAudioScrobbler::~CAudioScrobbler() { curl_easy_cleanup(_handle); curl_global_cleanup(); } std::string CAudioScrobbler::GetServiceURL() { if(Config->getService() == LibreFm) { return "https://libre.fm/2.0/"; } return "http://ws.audioscrobbler.com/2.0/"; } void CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0) { curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0); curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb); curl_easy_setopt(_handle, CURLOPT_TIMEOUT, 10); if(postfields) { curl_easy_setopt(_handle, CURLOPT_POST, 1); curl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields); } else curl_easy_setopt(_handle, CURLOPT_POST, 0); if(errbuf) curl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf); curl_easy_setopt(_handle, CURLOPT_URL, url.c_str()); CURLcode res = curl_easy_perform(_handle); // Sometimes last.fm likes to just timeout for no reason, leaving us hanging. // If this happens, retry a few times with a small delay. if (res != CURLE_OK) { eprintf("libcurl: (%d)", res); eprintf("%s", curl_easy_strerror(res)); eprintf("Will retry %d times with a %d second delay.", CURL_MAX_RETRIES, CURL_RETRY_DELAY); int retries = 0; do { sleep(CURL_RETRY_DELAY); retries++; eprintf("Retry %d/%d", retries, CURL_MAX_RETRIES); res = curl_easy_perform(_handle); } while (retries < CURL_MAX_RETRIES); eprintf("Failed after %d retries, try again later.", CURL_MAX_RETRIES); } } void CAudioScrobbler::ReportResponse(char* buf, size_t size) { _response.append(buf); } std::string CAudioScrobbler::CreateScrobbleMessage(int index, const CacheEntry& entry) { const Song& song = entry.getSong(); std::ostringstream msg, sigmsg ; std::string artist, title, album, array = "="; char* temp = 0; temp = curl_easy_escape(_handle, song.getArtist().c_str(), song.getArtist().length()); artist = temp; curl_free(temp); temp = curl_easy_escape(_handle, song.getTitle().c_str(), song.getTitle().length()); title = temp; curl_free(temp); temp = curl_easy_escape(_handle, song.getAlbum().c_str(), song.getAlbum().length()); album = temp; curl_free(temp); msg << "&album" << array << album; msg << "&api_key=" << APIKEY; msg << "&artist" << array << artist; msg << "&duration" << array << song.getDuration(); msg << "&method=track.Scrobble"; msg << "&timestamp" << array << entry.getStartTime(); msg << "&track" << array << title; msg << "&sk=" << _sessionid; array = ""; sigmsg << "album" << array << song.getAlbum(); sigmsg << "api_key" << APIKEY; sigmsg << "artist" << array << song.getArtist(); sigmsg << "duration" << array << song.getDuration(); sigmsg << "methodtrack.Scrobble"; sigmsg << "sk" << _sessionid; sigmsg << "timestamp" << array << entry.getStartTime(); sigmsg << "track" << array << song.getTitle(); sigmsg << SECRET; std::string sighash(md5sum((char*)"%s", sigmsg.str().c_str())); msg << "&api_sig=" << sighash; return msg.str(); } void CAudioScrobbler::Failure() { _failcount += 1; if(_failcount >= 3) { eprintf("%s", "Re-Handshaking!"); _failcount = 0; Handshake(); } } bool CAudioScrobbler::CheckFailure(std::string response) { bool retval = false; size_t start, end; start = _response.find("<error code=\"")+13; end = _response.find(">", start)-1; std::string errorcode = _response.substr(start, end-start); int code = strtol(errorcode.c_str(), 0, 10); eprintf("%s%i", "Code: ", code); switch(code) { case 3: eprintf("Invalid Method. This should not happen."); retval = true; break; case 4: eprintf("Authentication failed. Please check your login data."); exit(EXIT_FAILURE); case 9: eprintf("Invalid session key. Re-authenticating."); retval = true; _failcount = 3; break; case 10: eprintf("Invalid API-Key. Let's bugger off."); exit(EXIT_FAILURE); case 16: eprintf("The service is temporarily unavailable, we will try again later.."); retval = true; break; case 26: eprintf("Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm"); exit(EXIT_FAILURE); } return retval; } bool CAudioScrobbler::Scrobble(const CacheEntry& entry) { bool retval = false; if(!_authed) { eprintf("Handshake hasn't been done yet."); Handshake(); return retval; } iprintf("Scrobbling: %s - %s", entry.getSong().getArtist().c_str(), entry.getSong().getTitle().c_str()); OpenURL(GetServiceURL(), CreateScrobbleMessage(0, entry).c_str()); if(_response.find("<lfm status=\"ok\">") != std::string::npos) { iprintf("%s", "Scrobbled successfully."); retval = true; } else if(_response.find("<lfm status=\"failed\">") != std::string::npos) { eprintf("%s%s", "Last.fm returned an error while scrobbling:\n", _response.c_str()); if(CheckFailure(_response)) Failure(); } CLEANUP(); return retval; } bool CAudioScrobbler::LoveTrack(const Song& song, bool unlove) { bool retval = false; char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0); char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0); std::ostringstream query, sig; query << (unlove ? "method=track.unlove&" : "method=track.love&") << "&track=" << title << "&artist=" << artist << "&api_key=" << APIKEY << "&sk=" << _sessionid; curl_free(artist); curl_free(title); sig << "api_key" << APIKEY << "artist" << song.getArtist() << "method" << (unlove ? "track.unlove" : "track.love") << "sk" << _sessionid << "track" << song.getTitle() << SECRET; std::string sighash(md5sum((char*)"%s", sig.str().c_str())); query << "&api_sig=" << sighash; OpenURL(GetServiceURL(), query.str().c_str()); if(_response.find("<lfm status=\"ok\">") != std::string::npos) { iprintf("%s", "(Un)loved track successfully."); retval = true; } else if(_response.find("<lfm status=\"failed\">") != std::string::npos) { eprintf("%s%s", "Last.fm returned an error while (un)loving the currently playing track:\n", _response.c_str()); if(CheckFailure(_response)) Failure(); } CLEANUP(); return retval; } bool CAudioScrobbler::SendNowPlaying(const Song& song) { bool retval = false; char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0); char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0); char* album = song.getAlbum().empty() ? 0 : curl_easy_escape(_handle, song.getAlbum().c_str(), 0); std::ostringstream query, sig; query << "method=track.updateNowPlaying&track=" << title << "&artist=" << artist << "&duration=" << song.getDuration() << "&api_key=" << APIKEY << "&sk=" << _sessionid; if(album) { query << "&album=" << album; sig << "album" << song.getAlbum(); } curl_free(artist); curl_free(title); curl_free(album); sig << "api_key" << APIKEY << "artist" << song.getArtist() << "duration" << song.getDuration() << "methodtrack.updateNowPlaying" << "sk" << _sessionid << "track" << song.getTitle() << SECRET; std::string sighash(md5sum((char*)"%s", sig.str().c_str())); query << "&api_sig=" << sighash; OpenURL(GetServiceURL(), query.str().c_str()); if(_response.find("<lfm status=\"ok\">") != std::string::npos) { iprintf("%s", "Updated \"Now Playing\" status successfully."); retval = true; } else if(_response.find("<lfm status=\"failed\">") != std::string::npos) { eprintf("%s%s", "Last.fm returned an error while updating the currently playing track:\n", _response.c_str()); if(CheckFailure(_response)) Failure(); } CLEANUP(); return retval; } void CAudioScrobbler::Handshake() { std::string username=""; for(unsigned int i = 0; i < Config->getLUsername().length(); i++) { username.append(1, tolower(Config->getLUsername().c_str()[i])); } std::string authtoken(md5sum((char*)"%s%s", username.c_str(), Config->getLPassword().c_str())); std::ostringstream query, sig; query << "method=auth.getMobileSession&username=" << username << "&authToken=" << authtoken << "&api_key=" << APIKEY; sig << "api_key" << APIKEY << "authToken" << authtoken << "methodauth.getMobileSessionusername" << username << SECRET; std::string sighash(md5sum((char*)"%s", sig.str().c_str())); query << "&api_sig=" << sighash; OpenURL(GetServiceURL(), query.str().c_str()); if(_response.find("<lfm status=\"ok\">") != std::string::npos) { size_t start, end; start = _response.find("<key>") + 5; end = _response.find("</key>"); _sessionid = _response.substr(start, end-start); iprintf("%s%s", "Last.fm handshake successful. SessionID: ", _sessionid.c_str()); _authed = true; } else if(_response.find("<lfm status=\"failed\">") != std::string::npos) { CheckFailure(_response); exit(EXIT_FAILURE); } CLEANUP(); } <commit_msg>Check the result of curl rather than just blindly retrying<commit_after>#include "mpdas.h" #define APIKEY "a0ed2629d3d28606f67d7214c916788d" #define SECRET "295f31c5d28215215b1503fb0327cc01" #define CURL_MAX_RETRIES 3 #define CURL_RETRY_DELAY 3 // Seconds CAudioScrobbler* AudioScrobbler = 0; #define CLEANUP() _response.clear() size_t writecb(void* ptr, size_t size, size_t nmemb, void *stream) { AudioScrobbler->ReportResponse((char*)ptr, size*nmemb); return size*nmemb; } CAudioScrobbler::CAudioScrobbler() { _failcount = 0; _authed = false; _response = ""; _handle = curl_easy_init(); if(!_handle) { eprintf("%s", "Could not initialize CURL."); exit(EXIT_FAILURE); } } CAudioScrobbler::~CAudioScrobbler() { curl_easy_cleanup(_handle); curl_global_cleanup(); } std::string CAudioScrobbler::GetServiceURL() { if(Config->getService() == LibreFm) { return "https://libre.fm/2.0/"; } return "http://ws.audioscrobbler.com/2.0/"; } void CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0) { curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0); curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb); curl_easy_setopt(_handle, CURLOPT_TIMEOUT, 10); if(postfields) { curl_easy_setopt(_handle, CURLOPT_POST, 1); curl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields); } else curl_easy_setopt(_handle, CURLOPT_POST, 0); if(errbuf) curl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf); curl_easy_setopt(_handle, CURLOPT_URL, url.c_str()); CURLcode res = curl_easy_perform(_handle); // Sometimes last.fm likes to just timeout for no reason, leaving us hanging. // If this happens, retry a few times with a small delay. if (res != CURLE_OK) { eprintf("libcurl: (%d)", res); eprintf("%s", curl_easy_strerror(res)); eprintf("Will retry %d times with a %d second delay.", CURL_MAX_RETRIES, CURL_RETRY_DELAY); int retries = 0; do { sleep(CURL_RETRY_DELAY); retries++; eprintf("Retry %d/%d", retries, CURL_MAX_RETRIES); res = curl_easy_perform(_handle); } while (res != CURLE_OK || retries < CURL_MAX_RETRIES); eprintf("Failed after %d retries, try again later.", CURL_MAX_RETRIES); } } void CAudioScrobbler::ReportResponse(char* buf, size_t size) { _response.append(buf); } std::string CAudioScrobbler::CreateScrobbleMessage(int index, const CacheEntry& entry) { const Song& song = entry.getSong(); std::ostringstream msg, sigmsg ; std::string artist, title, album, array = "="; char* temp = 0; temp = curl_easy_escape(_handle, song.getArtist().c_str(), song.getArtist().length()); artist = temp; curl_free(temp); temp = curl_easy_escape(_handle, song.getTitle().c_str(), song.getTitle().length()); title = temp; curl_free(temp); temp = curl_easy_escape(_handle, song.getAlbum().c_str(), song.getAlbum().length()); album = temp; curl_free(temp); msg << "&album" << array << album; msg << "&api_key=" << APIKEY; msg << "&artist" << array << artist; msg << "&duration" << array << song.getDuration(); msg << "&method=track.Scrobble"; msg << "&timestamp" << array << entry.getStartTime(); msg << "&track" << array << title; msg << "&sk=" << _sessionid; array = ""; sigmsg << "album" << array << song.getAlbum(); sigmsg << "api_key" << APIKEY; sigmsg << "artist" << array << song.getArtist(); sigmsg << "duration" << array << song.getDuration(); sigmsg << "methodtrack.Scrobble"; sigmsg << "sk" << _sessionid; sigmsg << "timestamp" << array << entry.getStartTime(); sigmsg << "track" << array << song.getTitle(); sigmsg << SECRET; std::string sighash(md5sum((char*)"%s", sigmsg.str().c_str())); msg << "&api_sig=" << sighash; return msg.str(); } void CAudioScrobbler::Failure() { _failcount += 1; if(_failcount >= 3) { eprintf("%s", "Re-Handshaking!"); _failcount = 0; Handshake(); } } bool CAudioScrobbler::CheckFailure(std::string response) { bool retval = false; size_t start, end; start = _response.find("<error code=\"")+13; end = _response.find(">", start)-1; std::string errorcode = _response.substr(start, end-start); int code = strtol(errorcode.c_str(), 0, 10); eprintf("%s%i", "Code: ", code); switch(code) { case 3: eprintf("Invalid Method. This should not happen."); retval = true; break; case 4: eprintf("Authentication failed. Please check your login data."); exit(EXIT_FAILURE); case 9: eprintf("Invalid session key. Re-authenticating."); retval = true; _failcount = 3; break; case 10: eprintf("Invalid API-Key. Let's bugger off."); exit(EXIT_FAILURE); case 16: eprintf("The service is temporarily unavailable, we will try again later.."); retval = true; break; case 26: eprintf("Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm"); exit(EXIT_FAILURE); } return retval; } bool CAudioScrobbler::Scrobble(const CacheEntry& entry) { bool retval = false; if(!_authed) { eprintf("Handshake hasn't been done yet."); Handshake(); return retval; } iprintf("Scrobbling: %s - %s", entry.getSong().getArtist().c_str(), entry.getSong().getTitle().c_str()); OpenURL(GetServiceURL(), CreateScrobbleMessage(0, entry).c_str()); if(_response.find("<lfm status=\"ok\">") != std::string::npos) { iprintf("%s", "Scrobbled successfully."); retval = true; } else if(_response.find("<lfm status=\"failed\">") != std::string::npos) { eprintf("%s%s", "Last.fm returned an error while scrobbling:\n", _response.c_str()); if(CheckFailure(_response)) Failure(); } CLEANUP(); return retval; } bool CAudioScrobbler::LoveTrack(const Song& song, bool unlove) { bool retval = false; char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0); char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0); std::ostringstream query, sig; query << (unlove ? "method=track.unlove&" : "method=track.love&") << "&track=" << title << "&artist=" << artist << "&api_key=" << APIKEY << "&sk=" << _sessionid; curl_free(artist); curl_free(title); sig << "api_key" << APIKEY << "artist" << song.getArtist() << "method" << (unlove ? "track.unlove" : "track.love") << "sk" << _sessionid << "track" << song.getTitle() << SECRET; std::string sighash(md5sum((char*)"%s", sig.str().c_str())); query << "&api_sig=" << sighash; OpenURL(GetServiceURL(), query.str().c_str()); if(_response.find("<lfm status=\"ok\">") != std::string::npos) { iprintf("%s", "(Un)loved track successfully."); retval = true; } else if(_response.find("<lfm status=\"failed\">") != std::string::npos) { eprintf("%s%s", "Last.fm returned an error while (un)loving the currently playing track:\n", _response.c_str()); if(CheckFailure(_response)) Failure(); } CLEANUP(); return retval; } bool CAudioScrobbler::SendNowPlaying(const Song& song) { bool retval = false; char* artist = curl_easy_escape(_handle, song.getArtist().c_str(), 0); char* title = curl_easy_escape(_handle, song.getTitle().c_str(), 0); char* album = song.getAlbum().empty() ? 0 : curl_easy_escape(_handle, song.getAlbum().c_str(), 0); std::ostringstream query, sig; query << "method=track.updateNowPlaying&track=" << title << "&artist=" << artist << "&duration=" << song.getDuration() << "&api_key=" << APIKEY << "&sk=" << _sessionid; if(album) { query << "&album=" << album; sig << "album" << song.getAlbum(); } curl_free(artist); curl_free(title); curl_free(album); sig << "api_key" << APIKEY << "artist" << song.getArtist() << "duration" << song.getDuration() << "methodtrack.updateNowPlaying" << "sk" << _sessionid << "track" << song.getTitle() << SECRET; std::string sighash(md5sum((char*)"%s", sig.str().c_str())); query << "&api_sig=" << sighash; OpenURL(GetServiceURL(), query.str().c_str()); if(_response.find("<lfm status=\"ok\">") != std::string::npos) { iprintf("%s", "Updated \"Now Playing\" status successfully."); retval = true; } else if(_response.find("<lfm status=\"failed\">") != std::string::npos) { eprintf("%s%s", "Last.fm returned an error while updating the currently playing track:\n", _response.c_str()); if(CheckFailure(_response)) Failure(); } CLEANUP(); return retval; } void CAudioScrobbler::Handshake() { std::string username=""; for(unsigned int i = 0; i < Config->getLUsername().length(); i++) { username.append(1, tolower(Config->getLUsername().c_str()[i])); } std::string authtoken(md5sum((char*)"%s%s", username.c_str(), Config->getLPassword().c_str())); std::ostringstream query, sig; query << "method=auth.getMobileSession&username=" << username << "&authToken=" << authtoken << "&api_key=" << APIKEY; sig << "api_key" << APIKEY << "authToken" << authtoken << "methodauth.getMobileSessionusername" << username << SECRET; std::string sighash(md5sum((char*)"%s", sig.str().c_str())); query << "&api_sig=" << sighash; OpenURL(GetServiceURL(), query.str().c_str()); if(_response.find("<lfm status=\"ok\">") != std::string::npos) { size_t start, end; start = _response.find("<key>") + 5; end = _response.find("</key>"); _sessionid = _response.substr(start, end-start); iprintf("%s%s", "Last.fm handshake successful. SessionID: ", _sessionid.c_str()); _authed = true; } else if(_response.find("<lfm status=\"failed\">") != std::string::npos) { CheckFailure(_response); exit(EXIT_FAILURE); } CLEANUP(); } <|endoftext|>
<commit_before>#include <string> #include "json/reader.h" #include "json/value.h" #include "log.h" #include <iostream> #include <fstream> #include <algorithm> #include <ctime> #include "ace/Signal.h" #include <ace/OS_NS_sys_stat.h> #include <ace/Logging_Strategy.h> #ifdef WIN32 #include <Windows.h> #include <shlwapi.h> #include <ShlObj.h> #endif const char *LOG_CONFIG_DIRECTORY = "ammo-gateway"; const char *LOG_CONFIG_FILE = "LoggingConfig.json"; const char *TIME_FORMAT = "%Y%m%dT%H%M%SZ"; std::string findConfigFile(); std::string expandLogFileName(std::string fileName, std::string appName); /** * This function reads the logging config file and sets up logging accordingly. * This should be included in main.cpp and called exactly once when the * application is initialized. */ void setupLogging(std::string appName) { std::string configFilename = findConfigFile(); std::string logLevel = "trace"; std::string logFile = ""; int logFileMaxSize = 10000; int logFileSampleTime = 30; int logFileCount = 20; if(configFilename != "") { std::ifstream configFile(configFilename.c_str()); if(configFile) { Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(configFile, root); if(parsingSuccessful) { if(root["LogLevel"].isString()) { logLevel = root["LogLevel"].asString(); std::transform(logLevel.begin(), logLevel.end(), logLevel.begin(), tolower); } else { LOG_ERROR("LogLevel is missing or wrong type (should be string)"); } if(root["LogFile"].isString()) { logFile = root["LogFile"].asString(); } else { //don't write an error; having the LogFile parameter unconfigured is a //valid scenario } if(root["LogFileMaxSize"].isInt()) { /** * Log file maximum size in KB * 0 means don't rotate (maintain old behavior) */ logFileMaxSize = root["LogFileMaxSize"].asInt(); } else { LOG_ERROR("LogFileMaxSize is missing or wrong type (should be int)"); } if(root["LogFileSampleTime"].isInt()) { int temp = root["LogFileSampleTime"].asInt(); if(temp <= 0) { LOG_ERROR("Invalid LogFileSampleTime (must be > 0)"); } else { logFileSampleTime = temp; } } else { LOG_ERROR("LogFileSampleTime is missing or wrong type (should be int)"); } if(root["LogFileCount"].isInt()) { int temp = root["LogFileCount"].asInt(); if(temp <= 0) { LOG_ERROR("Invalid LogFileCount (must be > 0)"); } else { logFileCount = temp; } } else { LOG_ERROR("LogFileCount is missing or wrong type (should be int)"); } } else { LOG_ERROR("JSON parsing error in config file '" << LOG_CONFIG_FILE << "'. Using defaults."); } } else { LOG_WARN("Could not read from config file '" << LOG_CONFIG_FILE << "'. Using defaults."); } } else { LOG_WARN("Using default configuration."); } if(logFile != "") { //blank filename or no logFile entry in config file writes to stderr if(logFileMaxSize > 0) { std::string expandedFilename = expandLogFileName(logFile, appName); LOG_INFO("Logging to logrolled file with base name " << expandedFilename); std::ostringstream maxSizeStringStream; maxSizeStringStream << logFileMaxSize; std::string maxSizeString = maxSizeStringStream.str(); std::ostringstream sampleTimeStringStream; sampleTimeStringStream << logFileSampleTime; std::string sampleTimeString = sampleTimeStringStream.str(); std::ostringstream countStringStream; countStringStream << logFileCount; std::string countString = countStringStream.str(); LOG_INFO("Logging to file " << expandedFilename); ACE_TCHAR *l_argv[6]; l_argv[0] = (ACE_TCHAR *) ACE_TEXT ("-s"); //log file basename l_argv[1] = (ACE_TCHAR *) ACE_TEXT (expandedFilename.c_str()); l_argv[1] = (ACE_TCHAR *) ACE_TEXT ("-o"); //order files l_argv[2] = (ACE_TCHAR *) ACE_TEXT ("-m"); //max size = ~1MB (1000 KB) l_argv[1] = (ACE_TCHAR *) ACE_TEXT (maxSizeString.c_str()); l_argv[3] = (ACE_TCHAR *) ACE_TEXT ("-i"); //logfile size is sampled every 30 seconds l_argv[1] = (ACE_TCHAR *) ACE_TEXT (sampleTimeString.c_str()); l_argv[4] = (ACE_TCHAR *) ACE_TEXT ("-N"); //support 2 files l_argv[4] = (ACE_TCHAR *) ACE_TEXT (countString.c_str()); l_argv[5] = 0; int ls_argc = 5; ACE_Auto_Basic_Ptr<ACE_TCHAR *> ls_argv (new ACE_TCHAR *[ls_argc]); for (int c = 0; c < ls_argc; ++c) (ls_argv.get ())[c] = l_argv[c]; //Allocate the logging strategy on the heap, because if it's stack allocated, //it will be deleted when it goes out of scope and horrible things will happen //(yes, that means we leak it) ACE_Logging_Strategy *logging_strategy = new ACE_Logging_Strategy(); int result = logging_strategy->init (ls_argc, ls_argv.get ()); if(result != 0) { LOG_WARN("Error creating logging strategy and/or log file... does the directory exist?"); LOG_WARN("Logging to console instead."); } } else { std::string expandedFilename = expandLogFileName(logFile, appName); LOG_INFO("Logging to single file " << expandedFilename); ACE_OSTREAM_TYPE *output = new std::ofstream(expandedFilename.c_str(), std::ofstream::out | std::ofstream::app); if(*output) { ACE_LOG_MSG->msg_ostream(output, 1); ACE_LOG_MSG->set_flags(ACE_Log_Msg::OSTREAM); ACE_LOG_MSG->clr_flags(ACE_Log_Msg::STDERR); } else { LOG_WARN("Couldn't create log file... does the directory exist?"); LOG_WARN("Logging to console instead."); } } } if(logLevel == "trace") { ACE_LOG_MSG->priority_mask (LM_TRACE | LM_DEBUG | LM_INFO | LM_WARNING | LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "debug") { ACE_LOG_MSG->priority_mask (LM_DEBUG | LM_INFO | LM_WARNING | LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "info") { ACE_LOG_MSG->priority_mask (LM_INFO | LM_WARNING | LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "warning") { ACE_LOG_MSG->priority_mask (LM_WARNING | LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "error") { ACE_LOG_MSG->priority_mask (LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "critical") { ACE_LOG_MSG->priority_mask (LM_CRITICAL, ACE_Log_Msg::PROCESS); } else { LOG_ERROR("Unknown logging level... using default configuration."); } } /* * This formats the log file name using a simplified printf-like syntax: * %%: Literal percent sign * %A: Application name (parameter to this function) * %T: Current ISO 8601 date and time (UTC) (YYYYMMDDThhmmssZ; i.e. 20120105T065312Z) * * Unknown format specifiers will be removed. */ std::string expandLogFileName(std::string logFile, std::string appName) { std::ostringstream outputFilename; time_t rawTime; struct tm *utcTime; char utcTimeFormatted[40]; time(&rawTime); utcTime = gmtime(&rawTime); int len = strftime(utcTimeFormatted, 40, TIME_FORMAT, utcTime); if(len == 0) { //didn't work (not big enough); contents of array are indeterminate, so we need to put something in it utcTimeFormatted[0] = '\0'; } for(std::string::iterator it = logFile.begin(); it != logFile.end(); it++) { if((*it) == '%') { it++; char formatCharacter = *it; switch(formatCharacter) { case '%': outputFilename << '%'; break; case 'A': outputFilename << appName; break; case 'T': outputFilename << utcTimeFormatted; break; } } else { outputFilename << (*it); } } return outputFilename.str(); } #ifndef WIN32 std::string findConfigFile() { std::string filePath; ACE_stat statStruct; std::string home, gatewayRoot; char *homeC = ACE_OS::getenv("HOME"); if(homeC == NULL) { home = ""; } else { home = homeC; } char *gatewayRootC = ACE_OS::getenv("GATEWAY_ROOT"); if(gatewayRootC == NULL) { gatewayRoot = ""; } else { gatewayRoot = gatewayRootC; } filePath = LOG_CONFIG_FILE; //stat returns 0 if the file exists if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = home + "/" + "." + LOG_CONFIG_DIRECTORY + "/" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string("/etc/") + LOG_CONFIG_DIRECTORY + "/" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = gatewayRoot + "/etc/" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = gatewayRoot + "/build/etc/" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string("../etc/") + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { LOG_ERROR("No logging config file found."); return ""; } } } } } } LOG_INFO("Using config file: " << filePath); return filePath; } #else /** * Searches for the gateway config file. Search order: * 1) The current working directory * 2) The user's configuration directory (Roaming appdata directory/ammo-gateway) * 3) The all users configuration directory (i.e. C:\ProgramData\ammo-gateway on Vista/7) * Fallback locations (don't rely on these; they may change or disappear in a * future release. Gateway installation should put the config file into * a location that's searched by default): * 4) $GATEWAY_ROOT/etc * 5) $GATEWAY_ROOT/build/etc * 6) ../etc */ std::string findConfigFile() { std::string filePath; ACE_stat statStruct; std::string gatewayRoot; TCHAR userConfigPath[MAX_PATH]; TCHAR systemConfigPath[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, userConfigPath); SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, systemConfigPath); char *gatewayRootC = ACE_OS::getenv("GATEWAY_ROOT"); if(gatewayRootC == NULL) { gatewayRoot = ""; } else { gatewayRoot = gatewayRootC; } filePath = LOG_CONFIG_FILE; //stat returns 0 if the file exists if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string(userConfigPath) + "\\" + LOG_CONFIG_DIRECTORY + "\\" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string(systemConfigPath) + "\\" + LOG_CONFIG_DIRECTORY + "\\" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = gatewayRoot + "\\etc\\" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = gatewayRoot + "\\build\\etc\\" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string("..\\etc\\") + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { LOG_ERROR("No config file found."); return ""; } } } } } } LOG_INFO("Using config file: " << filePath); return filePath; } #endif //:mode=c++: (jEdit modeline for syntax highlighting) <commit_msg>Fix logging settings<commit_after>#include <string> #include "json/reader.h" #include "json/value.h" #include "log.h" #include <iostream> #include <fstream> #include <algorithm> #include <ctime> #include "ace/Signal.h" #include <ace/OS_NS_sys_stat.h> #include <ace/Logging_Strategy.h> #ifdef WIN32 #include <Windows.h> #include <shlwapi.h> #include <ShlObj.h> #endif const char *LOG_CONFIG_DIRECTORY = "ammo-gateway"; const char *LOG_CONFIG_FILE = "LoggingConfig.json"; const char *TIME_FORMAT = "%Y%m%dT%H%M%SZ"; std::string findConfigFile(); std::string expandLogFileName(std::string fileName, std::string appName); /** * This function reads the logging config file and sets up logging accordingly. * This should be included in main.cpp and called exactly once when the * application is initialized. */ void setupLogging(std::string appName) { std::string configFilename = findConfigFile(); std::string logLevel = "trace"; std::string logFile = ""; int logFileMaxSize = 10000; int logFileSampleTime = 30; int logFileCount = 20; if(configFilename != "") { std::ifstream configFile(configFilename.c_str()); if(configFile) { Json::Value root; Json::Reader reader; bool parsingSuccessful = reader.parse(configFile, root); if(parsingSuccessful) { if(root["LogLevel"].isString()) { logLevel = root["LogLevel"].asString(); std::transform(logLevel.begin(), logLevel.end(), logLevel.begin(), tolower); } else { LOG_ERROR("LogLevel is missing or wrong type (should be string)"); } if(root["LogFile"].isString()) { logFile = root["LogFile"].asString(); } else { //don't write an error; having the LogFile parameter unconfigured is a //valid scenario } if(root["LogFileMaxSize"].isInt()) { /** * Log file maximum size in KB * 0 means don't rotate (maintain old behavior) */ logFileMaxSize = root["LogFileMaxSize"].asInt(); } else { LOG_ERROR("LogFileMaxSize is missing or wrong type (should be int)"); } if(root["LogFileSampleTime"].isInt()) { int temp = root["LogFileSampleTime"].asInt(); if(temp <= 0) { LOG_ERROR("Invalid LogFileSampleTime (must be > 0)"); } else { logFileSampleTime = temp; } } else { LOG_ERROR("LogFileSampleTime is missing or wrong type (should be int)"); } if(root["LogFileCount"].isInt()) { int temp = root["LogFileCount"].asInt(); if(temp <= 0) { LOG_ERROR("Invalid LogFileCount (must be > 0)"); } else { logFileCount = temp; } } else { LOG_ERROR("LogFileCount is missing or wrong type (should be int)"); } } else { LOG_ERROR("JSON parsing error in config file '" << LOG_CONFIG_FILE << "'. Using defaults."); } } else { LOG_WARN("Could not read from config file '" << LOG_CONFIG_FILE << "'. Using defaults."); } } else { LOG_WARN("Using default configuration."); } if(logFile != "") { //blank filename or no logFile entry in config file writes to stderr if(logFileMaxSize > 0) { std::string expandedFilename = expandLogFileName(logFile, appName); LOG_INFO("Logging to logrolled file with base name " << expandedFilename); std::ostringstream maxSizeStringStream; maxSizeStringStream << logFileMaxSize; std::string maxSizeString = maxSizeStringStream.str(); std::ostringstream sampleTimeStringStream; sampleTimeStringStream << logFileSampleTime; std::string sampleTimeString = sampleTimeStringStream.str(); std::ostringstream countStringStream; countStringStream << logFileCount; std::string countString = countStringStream.str(); ACE_TCHAR *l_argv[610]; l_argv[0] = (ACE_TCHAR *) ACE_TEXT ("-s"); //log file basename l_argv[1] = (ACE_TCHAR *) ACE_TEXT (expandedFilename.c_str()); l_argv[2] = (ACE_TCHAR *) ACE_TEXT ("-o"); //order files l_argv[3] = (ACE_TCHAR *) ACE_TEXT ("-m"); //max size = ~1MB (1000 KB) l_argv[4] = (ACE_TCHAR *) ACE_TEXT (maxSizeString.c_str()); l_argv[5] = (ACE_TCHAR *) ACE_TEXT ("-i"); //logfile size is sampled every 30 seconds l_argv[6] = (ACE_TCHAR *) ACE_TEXT (sampleTimeString.c_str()); l_argv[7] = (ACE_TCHAR *) ACE_TEXT ("-N"); //support 2 files l_argv[8] = (ACE_TCHAR *) ACE_TEXT (countString.c_str()); l_argv[9] = 0; int ls_argc = 9; ACE_Auto_Basic_Ptr<ACE_TCHAR *> ls_argv (new ACE_TCHAR *[ls_argc]); for (int c = 0; c < ls_argc; ++c) (ls_argv.get ())[c] = l_argv[c]; //Allocate the logging strategy on the heap, because if it's stack allocated, //it will be deleted when it goes out of scope and horrible things will happen //(yes, that means we leak it) ACE_Logging_Strategy *logging_strategy = new ACE_Logging_Strategy(); int result = logging_strategy->init (ls_argc, ls_argv.get ()); if(result != 0) { LOG_WARN("Error creating logging strategy and/or log file... does the directory exist?"); LOG_WARN("Logging to console instead."); } } else { std::string expandedFilename = expandLogFileName(logFile, appName); LOG_INFO("Logging to single file " << expandedFilename); ACE_OSTREAM_TYPE *output = new std::ofstream(expandedFilename.c_str(), std::ofstream::out | std::ofstream::app); if(*output) { ACE_LOG_MSG->msg_ostream(output, 1); ACE_LOG_MSG->set_flags(ACE_Log_Msg::OSTREAM); ACE_LOG_MSG->clr_flags(ACE_Log_Msg::STDERR); } else { LOG_WARN("Couldn't create log file... does the directory exist?"); LOG_WARN("Logging to console instead."); } } } if(logLevel == "trace") { ACE_LOG_MSG->priority_mask (LM_TRACE | LM_DEBUG | LM_INFO | LM_WARNING | LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "debug") { ACE_LOG_MSG->priority_mask (LM_DEBUG | LM_INFO | LM_WARNING | LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "info") { ACE_LOG_MSG->priority_mask (LM_INFO | LM_WARNING | LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "warning") { ACE_LOG_MSG->priority_mask (LM_WARNING | LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "error") { ACE_LOG_MSG->priority_mask (LM_ERROR | LM_CRITICAL, ACE_Log_Msg::PROCESS); } else if(logLevel == "critical") { ACE_LOG_MSG->priority_mask (LM_CRITICAL, ACE_Log_Msg::PROCESS); } else { LOG_ERROR("Unknown logging level... using default configuration."); } } /* * This formats the log file name using a simplified printf-like syntax: * %%: Literal percent sign * %A: Application name (parameter to this function) * %T: Current ISO 8601 date and time (UTC) (YYYYMMDDThhmmssZ; i.e. 20120105T065312Z) * * Unknown format specifiers will be removed. */ std::string expandLogFileName(std::string logFile, std::string appName) { std::ostringstream outputFilename; time_t rawTime; struct tm *utcTime; char utcTimeFormatted[40]; time(&rawTime); utcTime = gmtime(&rawTime); int len = strftime(utcTimeFormatted, 40, TIME_FORMAT, utcTime); if(len == 0) { //didn't work (not big enough); contents of array are indeterminate, so we need to put something in it utcTimeFormatted[0] = '\0'; } for(std::string::iterator it = logFile.begin(); it != logFile.end(); it++) { if((*it) == '%') { it++; char formatCharacter = *it; switch(formatCharacter) { case '%': outputFilename << '%'; break; case 'A': outputFilename << appName; break; case 'T': outputFilename << utcTimeFormatted; break; } } else { outputFilename << (*it); } } return outputFilename.str(); } #ifndef WIN32 std::string findConfigFile() { std::string filePath; ACE_stat statStruct; std::string home, gatewayRoot; char *homeC = ACE_OS::getenv("HOME"); if(homeC == NULL) { home = ""; } else { home = homeC; } char *gatewayRootC = ACE_OS::getenv("GATEWAY_ROOT"); if(gatewayRootC == NULL) { gatewayRoot = ""; } else { gatewayRoot = gatewayRootC; } filePath = LOG_CONFIG_FILE; //stat returns 0 if the file exists if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = home + "/" + "." + LOG_CONFIG_DIRECTORY + "/" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string("/etc/") + LOG_CONFIG_DIRECTORY + "/" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = gatewayRoot + "/etc/" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = gatewayRoot + "/build/etc/" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string("../etc/") + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { LOG_ERROR("No logging config file found."); return ""; } } } } } } LOG_INFO("Using config file: " << filePath); return filePath; } #else /** * Searches for the gateway config file. Search order: * 1) The current working directory * 2) The user's configuration directory (Roaming appdata directory/ammo-gateway) * 3) The all users configuration directory (i.e. C:\ProgramData\ammo-gateway on Vista/7) * Fallback locations (don't rely on these; they may change or disappear in a * future release. Gateway installation should put the config file into * a location that's searched by default): * 4) $GATEWAY_ROOT/etc * 5) $GATEWAY_ROOT/build/etc * 6) ../etc */ std::string findConfigFile() { std::string filePath; ACE_stat statStruct; std::string gatewayRoot; TCHAR userConfigPath[MAX_PATH]; TCHAR systemConfigPath[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, userConfigPath); SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, systemConfigPath); char *gatewayRootC = ACE_OS::getenv("GATEWAY_ROOT"); if(gatewayRootC == NULL) { gatewayRoot = ""; } else { gatewayRoot = gatewayRootC; } filePath = LOG_CONFIG_FILE; //stat returns 0 if the file exists if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string(userConfigPath) + "\\" + LOG_CONFIG_DIRECTORY + "\\" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string(systemConfigPath) + "\\" + LOG_CONFIG_DIRECTORY + "\\" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = gatewayRoot + "\\etc\\" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = gatewayRoot + "\\build\\etc\\" + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { filePath = std::string("..\\etc\\") + LOG_CONFIG_FILE; if(ACE_OS::stat(filePath.c_str(), &statStruct)) { LOG_ERROR("No config file found."); return ""; } } } } } } LOG_INFO("Using config file: " << filePath); return filePath; } #endif //:mode=c++: (jEdit modeline for syntax highlighting) <|endoftext|>
<commit_before>// This file is part of The New Aspell // Copyright (C) 2002 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. #ifndef ASC_CTYPE__HPP #define ASC_CTYPE__HPP #include "parm_string.hpp" #include "posib_err.hpp" namespace acommon { static inline bool asc_isspace(char c) { return c==' ' || c=='\n' || c=='\r' || c=='\t' || c=='\f' || c=='\v'; } static inline bool asc_isdigit(char c) { return '0' <= c && c <= '9'; } static inline bool asc_islower(char c) { return 'a' <= c && c <= 'z'; } static inline bool asc_isupper(char c) { return 'A' <= c && c <= 'Z'; } static inline bool asc_isalpha(char c) { return asc_islower(c) || asc_isupper(c); } static inline char asc_tolower(char c) { return asc_isupper(c) ? c + 0x20 : c; } static inline char asc_toupper(char c) { return asc_islower(c) ? c - 0x20 : c; } } #endif <commit_msg><commit_after>// This file is part of The New Aspell // Copyright (C) 2002 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. #ifndef ASC_CTYPE__HPP #define ASC_CTYPE__HPP namespace acommon { static inline bool asc_isspace(int c) { return c==' ' || c=='\n' || c=='\r' || c=='\t' || c=='\f' || c=='\v'; } static inline bool asc_isdigit(int c) { return '0' <= c && c <= '9'; } static inline bool asc_islower(int c) { return 'a' <= c && c <= 'z'; } static inline bool asc_isupper(int c) { return 'A' <= c && c <= 'Z'; } static inline bool asc_isalpha(int c) { return asc_islower(c) || asc_isupper(c); } static inline int asc_tolower(int c) { return asc_isupper(c) ? c + 0x20 : c; } static inline int asc_toupper(int c) { return asc_islower(c) ? c - 0x20 : c; } } #endif <|endoftext|>
<commit_before>/* * Test Driver for Botan */ #include <vector> #include <string> #include <iostream> #include <cstdlib> #include <cstring> #include <exception> #include <limits> #include <memory> #include <botan/botan.h> #include <botan/libstate.h> #include <botan/mp_types.h> using namespace Botan; #include "getopt.h" #include "bench.h" #include "validate.h" #include "common.h" const std::string VALIDATION_FILE = "checks/validate.dat"; const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat"; const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat"; const std::string EXPECTED_FAIL_FILE = "checks/fail.dat"; int run_test_suite(); namespace { template<typename T> bool test(const char* type, int digits, bool is_signed) { if(std::numeric_limits<T>::is_specialized == false) { std::cout << "WARNING: Could not check parameters of " << type << " in std::numeric_limits" << std::endl; // assume it's OK (full tests will catch it later) return true; } // continue checking after failures bool passed = true; if(std::numeric_limits<T>::is_integer == false) { std::cout << "WARN: std::numeric_limits<> says " << type << " is not an integer" << std::endl; passed = false; } if(std::numeric_limits<T>::is_signed != is_signed) { std::cout << "ERROR: numeric_limits<" << type << ">::is_signed == " << std::boolalpha << std::numeric_limits<T>::is_signed << std::endl; passed = false; } if(std::numeric_limits<T>::digits != digits && digits != 0) { std::cout << "ERROR: numeric_limits<" << type << ">::digits == " << std::numeric_limits<T>::digits << " expected " << digits << std::endl; passed = false; } return passed; } void test_types() { bool passed = true; passed = passed && test<Botan::byte >("byte", 8, false); passed = passed && test<Botan::u16bit>("u16bit", 16, false); passed = passed && test<Botan::u32bit>("u32bit", 32, false); passed = passed && test<Botan::u64bit>("u64bit", 64, false); passed = passed && test<Botan::s32bit>("s32bit", 31, true); passed = passed && test<Botan::word>("word", 0, false); if(!passed) std::cout << "Typedefs in include/types.h may be incorrect!\n"; } } int main(int argc, char* argv[]) { try { OptionParser opts("help|html|init=|test|validate|" "benchmark|bench-type=|bench-algo=|seconds="); opts.parse(argv); test_types(); // do this always Botan::InitializerOptions init_options(opts.value_if_set("init")); Botan::LibraryInitializer init(init_options); //Botan::LibraryInitializer::initialize(init_options); if(opts.is_set("help") || argc <= 1) { std::cerr << "Test driver for " << Botan::version_string() << "\n" << "Options:\n" << " --test || --validate: Run tests (do this at least once)\n" << " --benchmark: Benchmark everything\n" << " --bench-type={block,mode,stream,hash,mac,rng,pk}:\n" << " Benchmark only algorithms of a particular type\n" << " --html: Produce HTML output for benchmarks\n" << " --seconds=n: Benchmark for n seconds\n" << " --init=<str>: Pass <str> to the library\n" << " --help: Print this message\n"; } else if(opts.is_set("validate") || opts.is_set("test")) { run_test_suite(); } if(opts.is_set("bench-algo") || opts.is_set("benchmark") || opts.is_set("bench-type")) { double seconds = 5; if(opts.is_set("seconds")) { seconds = std::atof(opts.value("seconds").c_str()); if(seconds < 0.1 || seconds > (5 * 60)) { std::cout << "Invalid argument to --seconds\n"; return 2; } } const bool html = opts.is_set("html"); AutoSeeded_RNG rng; if(opts.is_set("benchmark")) { benchmark("All", rng, html, seconds); } else if(opts.is_set("bench-algo")) { std::vector<std::string> algs = Botan::split_on(opts.value("bench-algo"), ','); for(u32bit j = 0; j != algs.size(); j++) { const std::string alg = algs[j]; u32bit found = bench_algo(alg, rng, seconds); if(!found) // maybe it's a PK algorithm bench_pk(rng, alg, html, seconds); } } else if(opts.is_set("bench-type")) { const std::string type = opts.value("bench-type"); if(type == "all") benchmark("All", rng, html, seconds); else if(type == "block") benchmark("Block Cipher", rng, html, seconds); else if(type == "stream") benchmark("Stream Cipher", rng, html, seconds); else if(type == "hash") benchmark("Hash", rng, html, seconds); else if(type == "mac") benchmark("MAC", rng, html, seconds); else if(type == "rng") benchmark("RNG", rng, html, seconds); else if(type == "pk") bench_pk(rng, "All", html, seconds); else std::cerr << "Unknown --bench-type " << type << "\n"; } } Botan::set_global_state(0); } catch(std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } catch(...) { std::cerr << "Unknown (...) exception caught" << std::endl; } return 0; } int run_test_suite() { std::cout << "Beginning tests..." << std::endl; u32bit errors = 0; try { AutoSeeded_RNG rng; errors += do_validation_tests(VALIDATION_FILE, rng); errors += do_validation_tests(EXPECTED_FAIL_FILE, rng, false); errors += do_bigint_tests(BIGINT_VALIDATION_FILE, rng); errors += do_gfpmath_tests(rng); errors += do_pk_validation_tests(PK_VALIDATION_FILE, rng); //errors += do_cvc_tests(rng); } catch(Botan::Exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; return 1; } catch(std::exception& e) { std::cout << "Standard library exception caught: " << e.what() << std::endl; return 1; } catch(...) { std::cout << "Unknown exception caught." << std::endl; return 1; } if(errors) { std::cout << errors << " test" << ((errors == 1) ? "" : "s") << " failed." << std::endl; return 1; } std::cout << "All tests passed!" << std::endl; return 0; } <commit_msg>Use a single RNG in check/test code<commit_after>/* * Test Driver for Botan */ #include <vector> #include <string> #include <iostream> #include <cstdlib> #include <cstring> #include <exception> #include <limits> #include <memory> #include <botan/botan.h> #include <botan/libstate.h> #include <botan/mp_types.h> using namespace Botan; #include "getopt.h" #include "bench.h" #include "validate.h" #include "common.h" const std::string VALIDATION_FILE = "checks/validate.dat"; const std::string BIGINT_VALIDATION_FILE = "checks/mp_valid.dat"; const std::string PK_VALIDATION_FILE = "checks/pk_valid.dat"; const std::string EXPECTED_FAIL_FILE = "checks/fail.dat"; int run_test_suite(RandomNumberGenerator& rng); namespace { template<typename T> bool test(const char* type, int digits, bool is_signed) { if(std::numeric_limits<T>::is_specialized == false) { std::cout << "WARNING: Could not check parameters of " << type << " in std::numeric_limits" << std::endl; // assume it's OK (full tests will catch it later) return true; } // continue checking after failures bool passed = true; if(std::numeric_limits<T>::is_integer == false) { std::cout << "WARN: std::numeric_limits<> says " << type << " is not an integer" << std::endl; passed = false; } if(std::numeric_limits<T>::is_signed != is_signed) { std::cout << "ERROR: numeric_limits<" << type << ">::is_signed == " << std::boolalpha << std::numeric_limits<T>::is_signed << std::endl; passed = false; } if(std::numeric_limits<T>::digits != digits && digits != 0) { std::cout << "ERROR: numeric_limits<" << type << ">::digits == " << std::numeric_limits<T>::digits << " expected " << digits << std::endl; passed = false; } return passed; } void test_types() { bool passed = true; passed = passed && test<Botan::byte >("byte", 8, false); passed = passed && test<Botan::u16bit>("u16bit", 16, false); passed = passed && test<Botan::u32bit>("u32bit", 32, false); passed = passed && test<Botan::u64bit>("u64bit", 64, false); passed = passed && test<Botan::s32bit>("s32bit", 31, true); passed = passed && test<Botan::word>("word", 0, false); if(!passed) std::cout << "Typedefs in include/types.h may be incorrect!\n"; } } int main(int argc, char* argv[]) { try { OptionParser opts("help|html|init=|test|validate|" "benchmark|bench-type=|bench-algo=|seconds="); opts.parse(argv); test_types(); // do this always Botan::InitializerOptions init_options(opts.value_if_set("init")); Botan::LibraryInitializer init(init_options); Botan::AutoSeeded_RNG rng; if(opts.is_set("help") || argc <= 1) { std::cerr << "Test driver for " << Botan::version_string() << "\n" << "Options:\n" << " --test || --validate: Run tests (do this at least once)\n" << " --benchmark: Benchmark everything\n" << " --bench-type={block,mode,stream,hash,mac,rng,pk}:\n" << " Benchmark only algorithms of a particular type\n" << " --html: Produce HTML output for benchmarks\n" << " --seconds=n: Benchmark for n seconds\n" << " --init=<str>: Pass <str> to the library\n" << " --help: Print this message\n"; } else if(opts.is_set("validate") || opts.is_set("test")) { run_test_suite(rng); } if(opts.is_set("bench-algo") || opts.is_set("benchmark") || opts.is_set("bench-type")) { double seconds = 5; if(opts.is_set("seconds")) { seconds = std::atof(opts.value("seconds").c_str()); if(seconds < 0.1 || seconds > (5 * 60)) { std::cout << "Invalid argument to --seconds\n"; return 2; } } const bool html = opts.is_set("html"); if(opts.is_set("benchmark")) { benchmark("All", rng, html, seconds); } else if(opts.is_set("bench-algo")) { std::vector<std::string> algs = Botan::split_on(opts.value("bench-algo"), ','); for(u32bit j = 0; j != algs.size(); j++) { const std::string alg = algs[j]; u32bit found = bench_algo(alg, rng, seconds); if(!found) // maybe it's a PK algorithm bench_pk(rng, alg, html, seconds); } } else if(opts.is_set("bench-type")) { const std::string type = opts.value("bench-type"); if(type == "all") benchmark("All", rng, html, seconds); else if(type == "block") benchmark("Block Cipher", rng, html, seconds); else if(type == "stream") benchmark("Stream Cipher", rng, html, seconds); else if(type == "hash") benchmark("Hash", rng, html, seconds); else if(type == "mac") benchmark("MAC", rng, html, seconds); else if(type == "rng") benchmark("RNG", rng, html, seconds); else if(type == "pk") bench_pk(rng, "All", html, seconds); else std::cerr << "Unknown --bench-type " << type << "\n"; } } } catch(std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } catch(...) { std::cerr << "Unknown (...) exception caught" << std::endl; } return 0; } int run_test_suite(RandomNumberGenerator& rng) { std::cout << "Beginning tests..." << std::endl; u32bit errors = 0; try { errors += do_validation_tests(VALIDATION_FILE, rng); errors += do_validation_tests(EXPECTED_FAIL_FILE, rng, false); errors += do_bigint_tests(BIGINT_VALIDATION_FILE, rng); errors += do_gfpmath_tests(rng); errors += do_pk_validation_tests(PK_VALIDATION_FILE, rng); //errors += do_cvc_tests(rng); } catch(Botan::Exception& e) { std::cout << "Exception caught: " << e.what() << std::endl; return 1; } catch(std::exception& e) { std::cout << "Standard library exception caught: " << e.what() << std::endl; return 1; } catch(...) { std::cout << "Unknown exception caught." << std::endl; return 1; } if(errors) { std::cout << errors << " test" << ((errors == 1) ? "" : "s") << " failed." << std::endl; return 1; } std::cout << "All tests passed!" << std::endl; return 0; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief MAX7219 ドライバー Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include <cstring> #include "common/iica_io.hpp" #include "common/time.h" namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief MAX7219 テンプレートクラス @param[in] SPI SPI クラス @param[in] SELECT デバイス選択 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class SPI, class SELECT> class MAX7219 { SPI& spi_; uint8_t limit_; uint8_t data_[8]; enum class command : uint8_t { NO_OP = 0x00, DIGIT_0 = 0x01, DIGIT_1 = 0x02, DIGIT_2 = 0x03, DIGIT_3 = 0x04, DIGIT_4 = 0x05, DIGIT_5 = 0x06, DIGIT_6 = 0x07, DIGIT_7 = 0x08, DECODE_MODE = 0x09, INTENSITY = 0x0A, SCAN_LIMIT = 0x0B, SHUTDOWN = 0x0C, DISPLAY_TEST = 0x0F, }; // MAX7212 D15 first void out_(command cmd, uint8_t dat) { SELECT::P = 0; uint8_t tmp[2]; tmp[0] = static_cast<uint8_t>(cmd); tmp[1] = dat; spi_.send(tmp, 2); SELECT::P = 1; // load } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] spi SPI クラスを参照で渡す */ //-----------------------------------------------------------------// MAX7219(SPI& spi) : spi_(spi), limit_(0) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] limit スキャン・リミット @return エラーなら「false」を返す */ //-----------------------------------------------------------------// bool start(uint8_t limit = 8) { if(limit_ > 8 || limit == 0) { return false; } limit_ = limit; SELECT::DIR = 1; // output; SELECT::PU = 0; // pull-up disable SELECT::P = 1; // /CS = H for(uint8_t i = 0; i < sizeof(data_); ++i) { data_[i] = 0; } out_(command::SHUTDOWN, 0x01); // ノーマル・モード out_(command::DECODE_MODE, 0x00); // デコード・モード out_(command::SCAN_LIMIT, limit - 1); // 表示桁設定 set_intensity(0); // 輝度(最低) service(); return true; } //-----------------------------------------------------------------// /*! @brief 輝度の設定 @param[in] inten 輝度値(最小:0、最大:15) @return エラー(初期化不良)なら「false」 */ //-----------------------------------------------------------------// bool set_intensity(uint8_t inten) { if(limit_ == 0) return false; out_(command::INTENSITY, inten); return true; } //-----------------------------------------------------------------// /*! @brief データ転送 @return エラー(初期化不良)なら「false」 */ //-----------------------------------------------------------------// bool service() { if(limit_ == 0) return false; for(uint8_t i = 0; i < limit_; ++i) { out_(static_cast<command>(static_cast<uint8_t>(command::DIGIT_0) + i), data_[i]); } return true; } //-----------------------------------------------------------------// /*! @brief 値の取得 @param[in] idx インデックス(0~7) @return 値 */ //-----------------------------------------------------------------// uint8_t get(uint8_t idx) { if(idx < limit_) { return data_[idx]; } return 0; } //-----------------------------------------------------------------// /*! @brief 値の設定 @param[in] idx インデックス(0~7) @param[in] dat データ */ //-----------------------------------------------------------------// void set(uint8_t idx, uint8_t dat) { if(idx < limit_) { data_[idx] = dat; } } //-----------------------------------------------------------------// /*! @brief キャラクターの設定 @param[in] idx インデックス(0~7) @param[in] cha キャラクターコード @param[in] dp 小数点 */ //-----------------------------------------------------------------// void set_cha(uint8_t idx, char cha, bool dp = false) { uint8_t d = 0; switch(cha) { case ' ': break; case '0': d = 0b1111110; break; case '1': d = 0b0110000; break; case '2': d = 0b1101101; break; case '3': d = 0b1111001; break; case '4': d = 0b0110011; break; case '5': d = 0b1011011; break; case '6': d = 0b1011111; break; case '7': d = 0b1110000; break; case '8': d = 0b1111111; break; case '9': d = 0b1111011; break; case '-': d = 0b0000001; break; case 'A': case 'a': d = 0b1110111; break; case 'B': case 'b': d = 0b0011111; break; case 'C': d = 0b1001110; break; case 'c': d = 0b0001101; break; case 'D': case 'd': d = 0b0111101; break; case 'E': case 'e': d = 0b1001111; break; case 'F': case 'f': d = 0b1000111; break; case 'G': case 'g': d = 0b1011110; break; case 'H': case 'h': d = 0b0010111; break; case 'I': case 'i': d = 0b0000100; break; case 'J': case 'j': d = 0b0111100; break; case 'K': case 'k': d = 0b1010111; break; case 'L': case 'l': d = 0b0001110; break; case 'M': case 'm': d = 0b1110110; break; case 'N': case 'n': d = 0b0010101; break; case 'O': case 'o': d = 0b0011101; break; case 'P': case 'p': d = 0b1100111; break; case 'Q': case 'q': d = 0b1101111; break; case 'R': case 'r': d = 0b0000101; break; case 'S': case 's': d = 0b0011011; break; case 'T': case 't': d = 0b0001111; break; case 'U': case 'u': d = 0b0011100; break; case 'V': case 'v': d = 0b0111110; break; case 'W': case 'w': d = 0b0111111; break; case 'X': case 'x': d = 0b0110111; break; case 'Y': case 'y': d = 0b0111011; break; case 'Z': case 'z': d = 0b1101100; break; default: break; } if(dp) d |= 0x80; set(idx, d); } //-----------------------------------------------------------------// /*! @brief シフト、バッファ先頭 @param[in] fill 埋めるデータ */ //-----------------------------------------------------------------// uint8_t shift_begin(uint8_t fill = 0) { uint8_t full = data_[0]; std::memmove(&data_[1], &data_[0], 7); data_[0] = fill; return full; } //-----------------------------------------------------------------// /*! @brief シフト、バッファ @param[in] fill 埋めるデータ */ //-----------------------------------------------------------------// void shift_last(uint8_t fill = 0) { uint8_t full = data_[7]; std::memmove(&data_[0], &data_[1], 7); data_[7] = fill; return full; } }; } <commit_msg>update daisy chain<commit_after>#pragma once //=====================================================================// /*! @file @brief MAX7219 ドライバー Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include <cstring> #include "common/iica_io.hpp" #include "common/time.h" namespace chip { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief MAX7219 テンプレートクラス @param[in] SPI SPI クラス @param[in] SELECT デバイス選択 @param[in] CHAIN デージー・チェイン数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class SPI, class SELECT, uint32_t CHAIN = 1> class MAX7219 { SPI& spi_; uint16_t limit_; uint8_t data_[CHAIN * 8]; enum class command : uint8_t { NO_OP = 0x00, DIGIT_0 = 0x01, DIGIT_1 = 0x02, DIGIT_2 = 0x03, DIGIT_3 = 0x04, DIGIT_4 = 0x05, DIGIT_5 = 0x06, DIGIT_6 = 0x07, DIGIT_7 = 0x08, DECODE_MODE = 0x09, INTENSITY = 0x0A, SCAN_LIMIT = 0x0B, SHUTDOWN = 0x0C, DISPLAY_TEST = 0x0F, }; // MAX7212 MSB first, 2 bytes void out_(command cmd, uint8_t dat) { SELECT::P = 0; uint8_t tmp[2]; tmp[0] = static_cast<uint8_t>(cmd); tmp[1] = dat; spi_.send(tmp, 2); SELECT::P = 1; // load } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] spi SPI クラスを参照で渡す */ //-----------------------------------------------------------------// MAX7219(SPI& spi) : spi_(spi), limit_(0) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] limit スキャン・リミット @return エラーなら「false」を返す */ //-----------------------------------------------------------------// bool start(uint8_t limit = (CHAIN * 8)) { if(limit_ > (8 * CHAIN) || limit == 0) { return false; } limit_ = limit; SELECT::DIR = 1; // output; SELECT::PU = 0; // pull-up disable SELECT::P = 1; // /CS = H for(uint8_t i = 0; i < sizeof(data_); ++i) { data_[i] = 0; } out_(command::SHUTDOWN, 0x01); // ノーマル・モード out_(command::DECODE_MODE, 0x00); // デコード・モード out_(command::SCAN_LIMIT, limit - 1); // 表示桁設定 set_intensity(0); // 輝度(最低) service(); return true; } //-----------------------------------------------------------------// /*! @brief 輝度の設定 @param[in] inten 輝度値(最小:0、最大:15) @return エラー(初期化不良)なら「false」 */ //-----------------------------------------------------------------// bool set_intensity(uint8_t inten) { if(limit_ == 0) return false; out_(command::INTENSITY, inten); return true; } //-----------------------------------------------------------------// /*! @brief データ転送 @return エラー(初期化不良)なら「false」 */ //-----------------------------------------------------------------// bool service() { if(limit_ == 0) return false; for(uint8_t i = 0; i < limit_; ++i) { out_(static_cast<command>(static_cast<uint8_t>(command::DIGIT_0) + i), data_[i]); } return true; } //-----------------------------------------------------------------// /*! @brief 値の取得 @param[in] idx インデックス(0~7) @return 値 */ //-----------------------------------------------------------------// uint8_t get(uint8_t idx) { if(idx < limit_) { return data_[idx]; } return 0; } //-----------------------------------------------------------------// /*! @brief 値の設定 @param[in] idx インデックス(0~7) @param[in] dat データ */ //-----------------------------------------------------------------// void set(uint8_t idx, uint8_t dat) { if(idx < limit_) { data_[idx] = dat; } } //-----------------------------------------------------------------// /*! @brief キャラクターの設定 @param[in] idx インデックス(0~7) @param[in] cha キャラクターコード @param[in] dp 小数点 */ //-----------------------------------------------------------------// void set_cha(uint8_t idx, char cha, bool dp = false) { uint8_t d = 0; switch(cha) { case ' ': break; case '-': d = 0b0000001; break; case '_': d = 0b0001000; break; case '~': d = 0b1000000; break; case '0': d = 0b1111110; break; case '1': d = 0b0110000; break; case '2': d = 0b1101101; break; case '3': d = 0b1111001; break; case '4': d = 0b0110011; break; case '5': d = 0b1011011; break; case '6': d = 0b1011111; break; case '7': d = 0b1110000; break; case '8': d = 0b1111111; break; case '9': d = 0b1111011; break; case 'A': case 'a': d = 0b1110111; break; case 'B': case 'b': d = 0b0011111; break; case 'C': d = 0b1001110; break; case 'c': d = 0b0001101; break; case 'D': case 'd': d = 0b0111101; break; case 'E': case 'e': d = 0b1001111; break; case 'F': case 'f': d = 0b1000111; break; case 'G': case 'g': d = 0b1011110; break; case 'H': case 'h': d = 0b0010111; break; case 'I': case 'i': d = 0b0000100; break; case 'J': case 'j': d = 0b0111100; break; case 'K': case 'k': d = 0b1010111; break; case 'L': case 'l': d = 0b0001110; break; case 'M': case 'm': d = 0b1110110; break; case 'N': case 'n': d = 0b0010101; break; case 'O': case 'o': d = 0b0011101; break; case 'P': case 'p': d = 0b1100111; break; case 'Q': case 'q': d = 0b1101111; break; case 'R': case 'r': d = 0b0000101; break; case 'S': case 's': d = 0b0011011; break; case 'T': case 't': d = 0b0001111; break; case 'U': case 'u': d = 0b0011100; break; case 'V': case 'v': d = 0b0111110; break; case 'W': case 'w': d = 0b0111111; break; case 'X': case 'x': d = 0b0110111; break; case 'Y': case 'y': d = 0b0111011; break; case 'Z': case 'z': d = 0b1101100; break; default: break; } if(dp) d |= 0x80; set(idx, d); } //-----------------------------------------------------------------// /*! @brief シフト、バッファ先頭 @param[in] fill 埋めるデータ */ //-----------------------------------------------------------------// uint8_t shift_begin(uint8_t fill = 0) { uint8_t full = data_[0]; std::memmove(&data_[1], &data_[0], 7); data_[0] = fill; return full; } //-----------------------------------------------------------------// /*! @brief シフト、バッファ @param[in] fill 埋めるデータ */ //-----------------------------------------------------------------// void shift_last(uint8_t fill = 0) { uint8_t full = data_[7]; std::memmove(&data_[0], &data_[1], 7); data_[7] = fill; return full; } }; } <|endoftext|>
<commit_before>#include <tst/set.hpp> #include <tst/check.hpp> #include <regex> #include <png.h> #include <utki/span.hpp> #include <r4/vector.hpp> #include <papki/fs_file.hpp> #include <svgdom/dom.hpp> #include "../../src/svgren/config.hxx" #include "../../src/svgren/render.hpp" namespace{ const unsigned tolerance = 10; const std::string data_dir = "samples_data/"; const std::string render_backend_name = #if SVGREN_BACKEND == SVGREN_BACKEND_CAIRO "cairo" #elif SVGREN_BACKEND == SVGREN_BACKEND_AGG "agg" #else # error "Unknown rendering backend" #endif ; } class Image final{ public: /** * @brief Image color depth. */ enum class ColorDepth_e{ UNKNOWN = 0, GREY = 1, //1 channel. Only Grey channel GREYA = 2, //2 channels. Grey with Alpha channel RGB = 3, //3 channels. Red Green Blue channels RGBA = 4 //4 channels. RGBA format (4 channels) }; /** * @brief Basic image exception. */ class Exc : public std::runtime_error{ public: Exc(const std::string& msg = std::string()) : std::runtime_error(msg.c_str()) {} }; class IllegalArgumentExc : public Exc{ public: IllegalArgumentExc(const std::string& msg = std::string()) : Exc(msg) {} }; private: ColorDepth_e colorDepth_v; r4::vector2<unsigned> dim_v = 0; std::vector<uint8_t> buf_v; // image pixels data public: /** * @brief Default constructor. * Creates uninitialized Image object. */ Image() : colorDepth_v(ColorDepth_e::UNKNOWN) {} Image(const Image& im) = default; /** * @brief Get image dimensions. * @return Image dimensions. */ const r4::vector2<unsigned>& dims()const noexcept{ return this->dim_v; } /** * @brief Get color depth. * @return Bits per pixel. */ unsigned bitsPerPixel()const{ return this->numChannels() * 8; } /** * @brief Get color depth. * @return Number of color channels. */ unsigned numChannels()const{ return unsigned(this->colorDepth_v); } /** * @brief Get color depth. * @return Color depth type. */ ColorDepth_e colorDepth()const{ return this->colorDepth_v; } /** * @brief Get pixel data. * @return Pixel data of the image. */ utki::span<uint8_t> buf(){ return utki::make_span(this->buf_v); } /** * @brief Get pixel data. * @return Pixel data of the image. */ utki::span<const uint8_t> buf()const{ return utki::make_span(this->buf_v); } public: /** * @brief Initialize this image object with given parameters. * Pixel data remains uninitialized. * @param dimensions - image dimensions. * @param colorDepth - color depth. */ void init(r4::vector2<unsigned> dimensions, ColorDepth_e colorDepth){ this->dim_v = dimensions; this->colorDepth_v = colorDepth; this->buf_v.resize(this->dims().x() * this->dims().y() * this->numChannels()); } /** * @brief Flip image vertically. */ void flipVertical(); private: static void PNG_CustomReadFunction(png_structp pngPtr, png_bytep data, png_size_t length){ papki::file* fi = reinterpret_cast<papki::file*>(png_get_io_ptr(pngPtr)); ASSERT_ALWAYS(fi) // TRACE(<< "PNG_CustomReadFunction: fi = " << fi << " pngPtr = " << pngPtr << " data = " << std::hex << data << " length = " << length << std::endl) try{ utki::span<png_byte> bufWrapper(data, size_t(length)); fi->read(bufWrapper); // TRACE(<< "PNG_CustomReadFunction: fi->Read() finished" << std::endl) }catch(...){ // do not let any exception get out of this function // TRACE(<< "PNG_CustomReadFunction: fi->Read() failed" << std::endl) } } public: /** * @brief Load image from PNG file. * @param f - PNG file. */ void loadPNG(const papki::file& fi){ ASSERT_ALWAYS(!fi.is_open()) ASSERT_ALWAYS(this->buf_v.size() == 0) papki::file::guard file_guard(fi); // this will guarantee that the file will be closed upon exit // TRACE(<< "Image::LoadPNG(): file opened" << std::endl) #define PNGSIGSIZE 8 // The size of PNG signature (max 8 bytes) std::array<png_byte, PNGSIGSIZE> sig; memset(&*sig.begin(), 0, sig.size() * sizeof(sig[0])); { auto ret = // TODO: we should not rely on that it will always read the requested number of bytes (or should we?) fi.read(utki::make_span(sig)); ASSERT_ALWAYS(ret == sig.size() * sizeof(sig[0])) } if(png_sig_cmp(&*sig.begin(), 0, sig.size() * sizeof(sig[0])) != 0){ // if it is not a PNG-file throw Image::Exc("Image::LoadPNG(): not a PNG file"); } // Great!!! We have a PNG-file! // TRACE(<< "Image::LoadPNG(): file is a PNG" << std::endl) // Create internal PNG-structure to work with PNG file // (no warning and error callbacks) png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); png_infop infoPtr = png_create_info_struct(pngPtr);// Create structure with file info png_set_sig_bytes(pngPtr, PNGSIGSIZE);// We've already read PNGSIGSIZE bytes // Set custom "ReadFromFile" function png_set_read_fn(pngPtr, const_cast<papki::file*>(&fi), PNG_CustomReadFunction); png_read_info(pngPtr, infoPtr); // Read in all information about file // Get information from infoPtr png_uint_32 width = 0; png_uint_32 height = 0; int bitDepth = 0; int colorType = 0; png_get_IHDR(pngPtr, infoPtr, &width, &height, &bitDepth, &colorType, 0, 0, 0); // Strip 16bit png to 8bit if(bitDepth == 16){ png_set_strip_16(pngPtr); } // Convert paletted PNG to RGB image if(colorType == PNG_COLOR_TYPE_PALETTE){ png_set_palette_to_rgb(pngPtr); } // Convert grayscale PNG to 8bit greyscale PNG if(colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8){ png_set_expand_gray_1_2_4_to_8(pngPtr); } // if(png_get_valid(pngPtr, infoPtr,PNG_INFO_tRNS)) png_set_tRNS_to_alpha(pngPtr); // set gamma information double gamma = 0.0f; // if there's gamma info in the file, set it to 2.2 if(png_get_gAMA(pngPtr, infoPtr, &gamma)){ png_set_gamma(pngPtr, 2.2, gamma); }else{ png_set_gamma(pngPtr, 2.2, 0.45455); // set to 0.45455 otherwise (good guess for GIF images on PCs) } // update info after all transformations png_read_update_info(pngPtr, infoPtr); // get all dimensions and color info again png_get_IHDR(pngPtr, infoPtr, &width, &height, &bitDepth, &colorType, 0, 0, 0); ASSERT_ALWAYS(bitDepth == 8) // Set image type Image::ColorDepth_e imageType; switch(colorType){ case PNG_COLOR_TYPE_GRAY: imageType = Image::ColorDepth_e::GREY; break; case PNG_COLOR_TYPE_GRAY_ALPHA: imageType = Image::ColorDepth_e::GREYA; break; case PNG_COLOR_TYPE_RGB: imageType = Image::ColorDepth_e::RGB; break; case PNG_COLOR_TYPE_RGB_ALPHA: imageType = Image::ColorDepth_e::RGBA; break; default: throw Image::Exc("Image::LoadPNG(): unknown colorType"); break; } // Great! Number of channels and bits per pixel are initialized now! // set image dimensions and set buffer size this->init(r4::vector2<unsigned>(width, height), imageType);//Set buf array size (allocate memory) // Great! height and width are initialized and buffer memory allocated // TRACE(<< "Image::LoadPNG(): memory for image allocated" << std::endl) // Read image data png_size_t bytesPerRow = png_get_rowbytes(pngPtr, infoPtr);//get bytes per row // check that our expectations are correct if(bytesPerRow != this->dims().x() * this->numChannels()){ throw Image::Exc("Image::LoadPNG(): number of bytes per row does not match expected value"); } ASSERT_ALWAYS((bytesPerRow * height) == this->buf_v.size()) // TRACE(<< "Image::LoadPNG(): going to read in the data" << std::endl) { ASSERT_ALWAYS(this->dims().y() && this->buf_v.size()) std::vector<png_bytep> rows(this->dims().y()); // initialize row pointers // TRACE(<< "Image::LoadPNG(): this->buf.Buf() = " << std::hex << this->buf.Buf() << std::endl) for(unsigned i = 0; i < this->dims().y(); ++i){ rows[i] = &*this->buf_v.begin() + i * bytesPerRow; // TRACE(<< "Image::LoadPNG(): rows[i] = " << std::hex << rows[i] << std::endl) } // TRACE(<< "Image::LoadPNG(): row pointers are set" << std::endl) // Read in image data! png_read_image(pngPtr, &*rows.begin()); // TRACE(<< "Image::LoadPNG(): image data read" << std::endl) } png_destroy_read_struct(&pngPtr,0,0); // free libpng memory } }; namespace{ tst::set set("samples", [](tst::suite& suite){ std::vector<std::string> files; { const std::regex suffix_regex("^.*\\.svg$"); auto all_files = papki::fs_file(data_dir).list_dir(); std::copy_if( all_files.begin(), all_files.end(), std::back_inserter(files), [&suffix_regex](auto& f){ return std::regex_match(f, suffix_regex); } ); } suite.add<std::string>( "sample", std::move(files), [](const auto& p){ papki::fs_file in_file(data_dir + p); auto dom = svgdom::load(in_file); auto res = svgren::render(*dom); auto& img = res.pixels; papki::fs_file png_file(data_dir + render_backend_name + "/" + papki::not_suffix(in_file.not_dir()) + ".png"); Image png; png.loadPNG(png_file); ASSERT_ALWAYS(png.buf().size() != 0) tst::check(png.colorDepth() == Image::ColorDepth_e::RGBA, SL) << "Error: PNG color depth is not RGBA: " << unsigned(png.colorDepth()); tst::check(res.dims == png.dims(), SL) << "Error: svg dims " << res.dims << " did not match png dims " << png.dims(); tst::check(img.size() == png.buf().size() / png.numChannels(), SL) << "Error: svg pixel buffer size (" << img.size() << ") did not match png pixel buffer size(" << png.buf().size() / png.numChannels() << ")"; for(size_t i = 0; i != img.size(); ++i){ std::array<uint8_t, 4> rgba; rgba[0] = img[i] & 0xff; rgba[1] = (img[i] >> 8) & 0xff; rgba[2] = (img[i] >> 16) & 0xff; rgba[3] = (img[i] >> 24) & 0xff; for(unsigned j = 0; j != rgba.size(); ++j){ auto c1 = rgba[j]; auto c2 = png.buf()[i * png.numChannels() + j]; if(c1 > c2){ std::swap(c1, c2); } if(unsigned(c2 - c1) > tolerance){ uint32_t pixel = uint32_t(png.buf()[i * png.numChannels()]) | (uint32_t(png.buf()[i * png.numChannels() + 1]) << 8) | (uint32_t(png.buf()[i * png.numChannels() + 2]) << 16) | (uint32_t(png.buf()[i * png.numChannels() + 3]) << 24) ; tst::check(false, SL) << "Error: PNG pixel #" << std::dec << i << " [" << (i % res.dims.x()) << ", " << (i / res.dims.y()) << "]" << " (0x" << std::hex << pixel << ") did not match SVG pixel (0x" << img[i] << ")" << ", png_file = " << png_file.path(); } } } } ); }); } <commit_msg>disable sample tests for non-64 bit CPUs<commit_after>#include <tst/set.hpp> #include <tst/check.hpp> #include <regex> #include <png.h> #include <utki/config.hpp> #include <utki/span.hpp> #include <r4/vector.hpp> #include <papki/fs_file.hpp> #include <svgdom/dom.hpp> #include "../../src/svgren/config.hxx" #include "../../src/svgren/render.hpp" namespace{ const unsigned tolerance = 10; const std::string data_dir = "samples_data/"; const std::string render_backend_name = #if SVGREN_BACKEND == SVGREN_BACKEND_CAIRO "cairo" #elif SVGREN_BACKEND == SVGREN_BACKEND_AGG "agg" #else # error "Unknown rendering backend" #endif ; } class Image final{ public: /** * @brief Image color depth. */ enum class ColorDepth_e{ UNKNOWN = 0, GREY = 1, //1 channel. Only Grey channel GREYA = 2, //2 channels. Grey with Alpha channel RGB = 3, //3 channels. Red Green Blue channels RGBA = 4 //4 channels. RGBA format (4 channels) }; /** * @brief Basic image exception. */ class Exc : public std::runtime_error{ public: Exc(const std::string& msg = std::string()) : std::runtime_error(msg.c_str()) {} }; class IllegalArgumentExc : public Exc{ public: IllegalArgumentExc(const std::string& msg = std::string()) : Exc(msg) {} }; private: ColorDepth_e colorDepth_v; r4::vector2<unsigned> dim_v = 0; std::vector<uint8_t> buf_v; // image pixels data public: /** * @brief Default constructor. * Creates uninitialized Image object. */ Image() : colorDepth_v(ColorDepth_e::UNKNOWN) {} Image(const Image& im) = default; /** * @brief Get image dimensions. * @return Image dimensions. */ const r4::vector2<unsigned>& dims()const noexcept{ return this->dim_v; } /** * @brief Get color depth. * @return Bits per pixel. */ unsigned bitsPerPixel()const{ return this->numChannels() * 8; } /** * @brief Get color depth. * @return Number of color channels. */ unsigned numChannels()const{ return unsigned(this->colorDepth_v); } /** * @brief Get color depth. * @return Color depth type. */ ColorDepth_e colorDepth()const{ return this->colorDepth_v; } /** * @brief Get pixel data. * @return Pixel data of the image. */ utki::span<uint8_t> buf(){ return utki::make_span(this->buf_v); } /** * @brief Get pixel data. * @return Pixel data of the image. */ utki::span<const uint8_t> buf()const{ return utki::make_span(this->buf_v); } public: /** * @brief Initialize this image object with given parameters. * Pixel data remains uninitialized. * @param dimensions - image dimensions. * @param colorDepth - color depth. */ void init(r4::vector2<unsigned> dimensions, ColorDepth_e colorDepth){ this->dim_v = dimensions; this->colorDepth_v = colorDepth; this->buf_v.resize(this->dims().x() * this->dims().y() * this->numChannels()); } /** * @brief Flip image vertically. */ void flipVertical(); private: static void PNG_CustomReadFunction(png_structp pngPtr, png_bytep data, png_size_t length){ papki::file* fi = reinterpret_cast<papki::file*>(png_get_io_ptr(pngPtr)); ASSERT_ALWAYS(fi) // TRACE(<< "PNG_CustomReadFunction: fi = " << fi << " pngPtr = " << pngPtr << " data = " << std::hex << data << " length = " << length << std::endl) try{ utki::span<png_byte> bufWrapper(data, size_t(length)); fi->read(bufWrapper); // TRACE(<< "PNG_CustomReadFunction: fi->Read() finished" << std::endl) }catch(...){ // do not let any exception get out of this function // TRACE(<< "PNG_CustomReadFunction: fi->Read() failed" << std::endl) } } public: /** * @brief Load image from PNG file. * @param f - PNG file. */ void loadPNG(const papki::file& fi){ ASSERT_ALWAYS(!fi.is_open()) ASSERT_ALWAYS(this->buf_v.size() == 0) papki::file::guard file_guard(fi); // this will guarantee that the file will be closed upon exit // TRACE(<< "Image::LoadPNG(): file opened" << std::endl) #define PNGSIGSIZE 8 // The size of PNG signature (max 8 bytes) std::array<png_byte, PNGSIGSIZE> sig; memset(&*sig.begin(), 0, sig.size() * sizeof(sig[0])); { auto ret = // TODO: we should not rely on that it will always read the requested number of bytes (or should we?) fi.read(utki::make_span(sig)); ASSERT_ALWAYS(ret == sig.size() * sizeof(sig[0])) } if(png_sig_cmp(&*sig.begin(), 0, sig.size() * sizeof(sig[0])) != 0){ // if it is not a PNG-file throw Image::Exc("Image::LoadPNG(): not a PNG file"); } // Great!!! We have a PNG-file! // TRACE(<< "Image::LoadPNG(): file is a PNG" << std::endl) // Create internal PNG-structure to work with PNG file // (no warning and error callbacks) png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); png_infop infoPtr = png_create_info_struct(pngPtr);// Create structure with file info png_set_sig_bytes(pngPtr, PNGSIGSIZE);// We've already read PNGSIGSIZE bytes // Set custom "ReadFromFile" function png_set_read_fn(pngPtr, const_cast<papki::file*>(&fi), PNG_CustomReadFunction); png_read_info(pngPtr, infoPtr); // Read in all information about file // Get information from infoPtr png_uint_32 width = 0; png_uint_32 height = 0; int bitDepth = 0; int colorType = 0; png_get_IHDR(pngPtr, infoPtr, &width, &height, &bitDepth, &colorType, 0, 0, 0); // Strip 16bit png to 8bit if(bitDepth == 16){ png_set_strip_16(pngPtr); } // Convert paletted PNG to RGB image if(colorType == PNG_COLOR_TYPE_PALETTE){ png_set_palette_to_rgb(pngPtr); } // Convert grayscale PNG to 8bit greyscale PNG if(colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8){ png_set_expand_gray_1_2_4_to_8(pngPtr); } // if(png_get_valid(pngPtr, infoPtr,PNG_INFO_tRNS)) png_set_tRNS_to_alpha(pngPtr); // set gamma information double gamma = 0.0f; // if there's gamma info in the file, set it to 2.2 if(png_get_gAMA(pngPtr, infoPtr, &gamma)){ png_set_gamma(pngPtr, 2.2, gamma); }else{ png_set_gamma(pngPtr, 2.2, 0.45455); // set to 0.45455 otherwise (good guess for GIF images on PCs) } // update info after all transformations png_read_update_info(pngPtr, infoPtr); // get all dimensions and color info again png_get_IHDR(pngPtr, infoPtr, &width, &height, &bitDepth, &colorType, 0, 0, 0); ASSERT_ALWAYS(bitDepth == 8) // Set image type Image::ColorDepth_e imageType; switch(colorType){ case PNG_COLOR_TYPE_GRAY: imageType = Image::ColorDepth_e::GREY; break; case PNG_COLOR_TYPE_GRAY_ALPHA: imageType = Image::ColorDepth_e::GREYA; break; case PNG_COLOR_TYPE_RGB: imageType = Image::ColorDepth_e::RGB; break; case PNG_COLOR_TYPE_RGB_ALPHA: imageType = Image::ColorDepth_e::RGBA; break; default: throw Image::Exc("Image::LoadPNG(): unknown colorType"); break; } // Great! Number of channels and bits per pixel are initialized now! // set image dimensions and set buffer size this->init(r4::vector2<unsigned>(width, height), imageType);//Set buf array size (allocate memory) // Great! height and width are initialized and buffer memory allocated // TRACE(<< "Image::LoadPNG(): memory for image allocated" << std::endl) // Read image data png_size_t bytesPerRow = png_get_rowbytes(pngPtr, infoPtr);//get bytes per row // check that our expectations are correct if(bytesPerRow != this->dims().x() * this->numChannels()){ throw Image::Exc("Image::LoadPNG(): number of bytes per row does not match expected value"); } ASSERT_ALWAYS((bytesPerRow * height) == this->buf_v.size()) // TRACE(<< "Image::LoadPNG(): going to read in the data" << std::endl) { ASSERT_ALWAYS(this->dims().y() && this->buf_v.size()) std::vector<png_bytep> rows(this->dims().y()); // initialize row pointers // TRACE(<< "Image::LoadPNG(): this->buf.Buf() = " << std::hex << this->buf.Buf() << std::endl) for(unsigned i = 0; i < this->dims().y(); ++i){ rows[i] = &*this->buf_v.begin() + i * bytesPerRow; // TRACE(<< "Image::LoadPNG(): rows[i] = " << std::hex << rows[i] << std::endl) } // TRACE(<< "Image::LoadPNG(): row pointers are set" << std::endl) // Read in image data! png_read_image(pngPtr, &*rows.begin()); // TRACE(<< "Image::LoadPNG(): image data read" << std::endl) } png_destroy_read_struct(&pngPtr,0,0); // free libpng memory } }; namespace{ tst::set set("samples", [](tst::suite& suite){ std::vector<std::string> files; { const std::regex suffix_regex("^.*\\.svg$"); auto all_files = papki::fs_file(data_dir).list_dir(); std::copy_if( all_files.begin(), all_files.end(), std::back_inserter(files), [&suffix_regex](auto& f){ return std::regex_match(f, suffix_regex); } ); } suite.add<std::string>( "sample", { #if M_CPU_BITS != 64 tst::flag::disabled #endif }, std::move(files), [](const auto& p){ papki::fs_file in_file(data_dir + p); auto dom = svgdom::load(in_file); auto res = svgren::render(*dom); auto& img = res.pixels; papki::fs_file png_file(data_dir + render_backend_name + "/" + papki::not_suffix(in_file.not_dir()) + ".png"); Image png; png.loadPNG(png_file); ASSERT_ALWAYS(png.buf().size() != 0) tst::check(png.colorDepth() == Image::ColorDepth_e::RGBA, SL) << "Error: PNG color depth is not RGBA: " << unsigned(png.colorDepth()); tst::check(res.dims == png.dims(), SL) << "Error: svg dims " << res.dims << " did not match png dims " << png.dims(); tst::check(img.size() == png.buf().size() / png.numChannels(), SL) << "Error: svg pixel buffer size (" << img.size() << ") did not match png pixel buffer size(" << png.buf().size() / png.numChannels() << ")"; for(size_t i = 0; i != img.size(); ++i){ std::array<uint8_t, 4> rgba; rgba[0] = img[i] & 0xff; rgba[1] = (img[i] >> 8) & 0xff; rgba[2] = (img[i] >> 16) & 0xff; rgba[3] = (img[i] >> 24) & 0xff; for(unsigned j = 0; j != rgba.size(); ++j){ auto c1 = rgba[j]; auto c2 = png.buf()[i * png.numChannels() + j]; if(c1 > c2){ std::swap(c1, c2); } if(unsigned(c2 - c1) > tolerance){ uint32_t pixel = uint32_t(png.buf()[i * png.numChannels()]) | (uint32_t(png.buf()[i * png.numChannels() + 1]) << 8) | (uint32_t(png.buf()[i * png.numChannels() + 2]) << 16) | (uint32_t(png.buf()[i * png.numChannels() + 3]) << 24) ; tst::check(false, SL) << "Error: PNG pixel #" << std::dec << i << " [" << (i % res.dims.x()) << ", " << (i / res.dims.y()) << "]" << " (0x" << std::hex << pixel << ") did not match SVG pixel (0x" << img[i] << ")" << ", png_file = " << png_file.path(); } } } } ); }); } <|endoftext|>
<commit_before>// Copyright Hugh Perkins 2014 hughperkins at gmail // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "conv/ForwardIm2Col.h" #include "util/stringhelper.h" #include "util/StatefulTimer.h" #include "conv/AddBias.h" #include <sstream> #include <iostream> #include <string> using namespace std; #undef VIRTUAL #undef STATIC #define VIRTUAL #define STATIC #define PUBLIC STATIC void ForwardIm2Col::im2col( CLWrapper* im, int imOffset, CLWrapper* columns) { // We are going to launch channels * height_col * width_col kernels, each // kernel responsible for copying a single-channel grid. int num_kernels = channels * size_col * size_col; CLKernel *k = kernelIm2Col; k->in(num_kernels); k->in(im); k->out(col); k->run_1d(GET_BLOCKS(state, num_kernels), getNumThreads(state)); } //STATIC void ForwardIm2Col::col2im( // CLWrapper* col, THClTensor* im) { // int num_kernels = channels * height * width; // // To avoid involving atomic operations, we will launch one kernel per // // bottom dimension, and then in the kernel add up the top dimensions. // EasyCL *cl = im->storage->cl; // std::string uniqueName = "ForwardIm2Col::col2im"; // CLKernel *kernel = 0; // if(cl->kernelExists(uniqueName)) { // kernel = cl->getKernel(uniqueName); // } else { // TemplatedKernel kernelBuilder(cl); // kernel = kernelBuilder.buildKernel(uniqueName, "ForwardIm2Col.cl", // ForwardIm2Col_getKernelTemplate(), "col2im_kernel"); // } // CLKernel *k = kernelCol2Im; // k->in(num_kernels); // k->in(col); // k->out(im); // k->run_1d(GET_BLOCKS(state, num_kernels), getNumThreads(state)); //} PUBLIC VIRTUAL ForwardIm2Col::~ForwardIm2Col() { delete kernelIm2Col; // delete kernelCol2Im; delete addBias; } PUBLIC VIRTUAL void ForwardIm2Col::forward( int batchSize, CLWrapper *dataWrapper, CLWrapper *weightsWrapper, CLWrapper *biasWrapper, CLWrapper *outputWrapper ) { StatefulTimer::timeCheck("ForwardIm2Col::forward START"); int columnsSize= dim.inputPlanes * dim.filterSizeSquared * dim.outputImageSizeSquared; float *columns = new float[columnsSize]; CLWrapper *columnsWrapper = cl->wrap(columnsSize, columns); StatefulTimer::timeCheck("ForwardIm2Col::forward after alloc"); for (int b = 0; b < batchSize; b ++) { // Extract columns: im2col( dataWrapper, b * inputCubeSize, columnsWrapper ); // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/clblas/#clblas-lt-t-gt-gemm) long m = weight->size[0]; long n = columns->size[1]; long k = weight->size[1]; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) cl_err err = clblasSgemm( clblasColumnMajor, clblasNoTrans, clblasNoTrans, n, m, k, 1, columnsWrapper->getBuffer(), 0, n, weightsWrapper->getBuffer(), 0, k, 1, outputWrapper->getBuffer(), b * dim.outputCubeSize, n, 1, cl->queue, 0, NULL, 0 ); if (err != CL_SUCCESS) { throw runtime_error("clblasSgemm() failed with " + toString(err)); } } delete columnsWrapper; delete columns; StatefulTimer::timeCheck("ForwardIm2Col::forward after call forward"); if( dim.biased ) { addBias->forward( batchSize, dim.numFilters, dim.outputImageSize, outputWrapper, biasWrapper ); } StatefulTimer::timeCheck("ForwardIm2Col::forward END"); } PUBLIC ForwardIm2Col::ForwardIm2Col( EasyCL *cl, LayerDimensions dim ) : Forward( cl, dim ) { addBias = new AddBias( cl ); int size = dim.inputSize; int padding = dim.padZeros ? dim.halfFilterSize : 0; int stride = 1; int size_col = (size + 2 * padding - filterSize) / stride + 1; TemplatedKernel builder(cl); builder.set("padding", dim.padZeros ? dim.halfFilterSize : 0); builder.set("stride", 1); builder.set("colSize", size_col); builder.set("channels", dim.inputPlanes); builder.set("filterSize", dim.filterSize); builder.set("size", dim.inputImageSize); this->kernelIm2Col = kernelBuilder.buildKernel( "im2col", "ForwardIm2Col.cl", getIm2ColTemplate(), "im2col", false); // this->kernelCol2Im = kernelBuilder.buildKernel( // "col2im", // "ForwardIm2Col.cl", // getIm2ColTemplate(), // "col2im", // false); } STATIC std::string ForwardIm2Col::getKernelTemplate() { // [[[cog // import stringify // stringify.write_kernel( "kernel", "ForwardIm2Col.cl" ) // ]]] // generated using cog, from cl/forward1.cl: const char * kernelSource = "// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail\n" "//\n" "// This Source Code Form is subject to the terms of the Mozilla Public License,\n" "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n" "// obtain one at http://mozilla.org/MPL/2.0/.\n" "\n" "// notes on non-odd filtersizes:\n" "// for odd, imagesize and filtersize 3, padZeros = 0:\n" "// output is a single square\n" "// m and n should vary between -1,0,1\n" "// for even, imagesize and filtersize 2, padzeros = 0\n" "// output is a single square, which we can position at topleft or bottomrigth\n" "// lets position it in bottomright\n" "// then m and n should vary as -1,0\n" "//\n" "// for even, imagesize and filtersize 2, padzeros = 1\n" "// output is 2 by 2\n" "// well... if it is even:\n" "// - if we are not padding zeros, then we simply move our filter around the image somehow\n" "// - if we are padding zeros, then we conceptually pad the bottom and right edge of the image with zeros by 1\n" "// filtersize remains the same\n" "// m will vary as -1,0,1\n" "// outputrow is fixed by globalid\n" "// inputrow should be unchanged...\n" "// padzeros = 0:\n" "// x x . . . .\n" "// x x . . x x\n" "// . . . . x x\n" "// when filtersize even:\n" "// new imagesize = oldimagesize - filtersize + 1\n" "// when filtersize odd:\n" "// x x x .\n" "// x x x .\n" "// x x x .\n" "// . . . .\n" "// new imagesize = oldimagesize - filtersize + 1\n" "// padzeros = 1:\n" "// x x\n" "// x x . . x x . . . . . . .\n" "// . . . x x . . x x . . .\n" "// . . . . . . . x x . . x x\n" "// outrow=0 outrow=1 outrow=2 x x\n" "// outcol=0 outcol=1 outcol=2 outrow=3\n" "// outcol=3\n" "// when filtersize is even, and padzeros, imagesize grows by 1 each time...\n" "// imagesize = oldimagesize + 1\n" "// when filtersize is odd\n" "// x x x\n" "// x x x . x x x . . .\n" "// x x x . x x x . x x x\n" "// . . . x x x . x x x\n" "// x x x\n" "\n" "// images are organized like [imageId][plane][row][col]\n" "// filters are organized like [filterid][inplane][filterrow][filtercol]\n" "// output are organized like [imageid][filterid][row][col]\n" "// global id is organized like output, ie: [imageid][outplane][outrow][outcol]\n" "// - no local memory used currently\n" "// - each thread:\n" "// - loads a whole upstream cube\n" "// - loads a whole filter cube\n" "// - writes one output...\n" "void kernel convolve_imagecubes_float2(\n" " const int numExamples,\n" " global const float *inputs, global const float *filters,\n" " global float *output ) {\n" " int globalId = get_global_id(0);\n" "\n" " int outputImage2Id = globalId / gOutputImageSizeSquared;\n" " int exampleId = outputImage2Id / gNumFilters;\n" " int filterId = outputImage2Id % gNumFilters;\n" "\n" " // intraimage coords\n" " int localid = globalId % gOutputImageSizeSquared;\n" " int outputRow = localid / gOutputImageSize;\n" " int outputCol = localid % gOutputImageSize;\n" "\n" " global float const*inputCube = inputs + exampleId * gNumInputPlanes * gInputImageSizeSquared;\n" " global float const*filterCube = filters + filterId * gNumInputPlanes * gFilterSizeSquared;\n" "\n" " float sum = 0;\n" " if( exampleId < numExamples ) {\n" " for( int inputPlaneIdx = 0; inputPlaneIdx < gNumInputPlanes; inputPlaneIdx++ ) {\n" " global float const*inputPlane = inputCube + inputPlaneIdx * gInputImageSizeSquared;\n" " global float const*filterPlane = filterCube + inputPlaneIdx * gFilterSizeSquared;\n" " for( int u = -gHalfFilterSize; u <= gHalfFilterSize - gEven; u++ ) {\n" " // trying to reduce register pressure...\n" " #if gPadZeros == 1\n" " #define inputRowIdx ( outputRow + u )\n" " #else\n" " #define inputRowIdx ( outputRow + u + gHalfFilterSize )\n" " #endif\n" " global float const *inputRow = inputPlane + inputRowIdx * gInputImageSize;\n" " global float const *filterRow = filterPlane + (u+gHalfFilterSize) * gFilterSize + gHalfFilterSize;\n" " bool rowOk = inputRowIdx >= 0 && inputRowIdx < gInputImageSize;\n" " #pragma unroll\n" " for( int v = -gHalfFilterSize; v <= gHalfFilterSize - gEven; v++ ) {\n" " #if gPadZeros == 1\n" " #define inputColIdx ( outputCol + v )\n" " #else\n" " #define inputColIdx ( outputCol + v + gHalfFilterSize )\n" " #endif\n" " bool process = rowOk && inputColIdx >= 0 && inputColIdx < gInputImageSize;\n" " if( process ) {\n" " sum += inputRow[inputColIdx] * filterRow[v];\n" " }\n" " }\n" " }\n" " }\n" " }\n" "\n" " if( exampleId < numExamples ) {\n" " output[globalId] = sum;\n" " }\n" "}\n" "\n" ""; kernel = cl->buildKernelFromString( kernelSource, "convolve_imagecubes_float2", options, "cl/ForwardIm2Col.cl" ); // [[[end]]] return kernelSource; } <commit_msg>assigned values for m,n,k<commit_after>// Copyright Hugh Perkins 2014 hughperkins at gmail // // This Source Code Form is subject to the terms of the Mozilla Public License, // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "conv/ForwardIm2Col.h" #include "util/stringhelper.h" #include "util/StatefulTimer.h" #include "conv/AddBias.h" #include <sstream> #include <iostream> #include <string> using namespace std; #undef VIRTUAL #undef STATIC #define VIRTUAL #define STATIC #define PUBLIC STATIC void ForwardIm2Col::im2col( CLWrapper* im, int imOffset, CLWrapper* columns) { // We are going to launch channels * height_col * width_col kernels, each // kernel responsible for copying a single-channel grid. int num_kernels = channels * size_col * size_col; CLKernel *k = kernelIm2Col; k->in(num_kernels); k->in(im); k->out(col); k->run_1d(GET_BLOCKS(state, num_kernels), getNumThreads(state)); } //STATIC void ForwardIm2Col::col2im( // CLWrapper* col, THClTensor* im) { // int num_kernels = channels * height * width; // // To avoid involving atomic operations, we will launch one kernel per // // bottom dimension, and then in the kernel add up the top dimensions. // EasyCL *cl = im->storage->cl; // std::string uniqueName = "ForwardIm2Col::col2im"; // CLKernel *kernel = 0; // if(cl->kernelExists(uniqueName)) { // kernel = cl->getKernel(uniqueName); // } else { // TemplatedKernel kernelBuilder(cl); // kernel = kernelBuilder.buildKernel(uniqueName, "ForwardIm2Col.cl", // ForwardIm2Col_getKernelTemplate(), "col2im_kernel"); // } // CLKernel *k = kernelCol2Im; // k->in(num_kernels); // k->in(col); // k->out(im); // k->run_1d(GET_BLOCKS(state, num_kernels), getNumThreads(state)); //} PUBLIC VIRTUAL ForwardIm2Col::~ForwardIm2Col() { delete kernelIm2Col; // delete kernelCol2Im; delete addBias; } PUBLIC VIRTUAL void ForwardIm2Col::forward( int batchSize, CLWrapper *dataWrapper, CLWrapper *weightsWrapper, CLWrapper *biasWrapper, CLWrapper *outputWrapper ) { StatefulTimer::timeCheck("ForwardIm2Col::forward START"); int columnsSize= dim.inputPlanes * dim.filterSizeSquared * dim.outputImageSizeSquared; float *columns = new float[columnsSize]; CLWrapper *columnsWrapper = cl->wrap(columnsSize, columns); StatefulTimer::timeCheck("ForwardIm2Col::forward after alloc"); for (int b = 0; b < batchSize; b ++) { // Extract columns: im2col( dataWrapper, b * inputCubeSize, columnsWrapper ); // M,N,K are dims of matrix A and B // (see http://docs.nvidia.com/cuda/clblas/#clblas-lt-t-gt-gemm) long m = dim.numFilters; long n = dim.outputSizeSquared; long k = dim.numFilters * dim.filterSizeSquared; // Do GEMM (note: this is a bit confusing because gemm assumes column-major matrices) cl_err err = clblasSgemm( clblasColumnMajor, clblasNoTrans, clblasNoTrans, n, m, k, 1, columnsWrapper->getBuffer(), 0, n, weightsWrapper->getBuffer(), 0, k, 1, outputWrapper->getBuffer(), b * dim.outputCubeSize, n, 1, cl->queue, 0, NULL, 0 ); if (err != CL_SUCCESS) { throw runtime_error("clblasSgemm() failed with " + toString(err)); } } delete columnsWrapper; delete columns; StatefulTimer::timeCheck("ForwardIm2Col::forward after call forward"); if( dim.biased ) { addBias->forward( batchSize, dim.numFilters, dim.outputImageSize, outputWrapper, biasWrapper ); } StatefulTimer::timeCheck("ForwardIm2Col::forward END"); } PUBLIC ForwardIm2Col::ForwardIm2Col( EasyCL *cl, LayerDimensions dim ) : Forward( cl, dim ) { addBias = new AddBias( cl ); int size = dim.inputSize; int padding = dim.padZeros ? dim.halfFilterSize : 0; int stride = 1; int size_col = (size + 2 * padding - filterSize) / stride + 1; TemplatedKernel builder(cl); builder.set("padding", dim.padZeros ? dim.halfFilterSize : 0); builder.set("stride", 1); builder.set("colSize", size_col); builder.set("channels", dim.inputPlanes); builder.set("filterSize", dim.filterSize); builder.set("size", dim.inputImageSize); this->kernelIm2Col = kernelBuilder.buildKernel( "im2col", "ForwardIm2Col.cl", getIm2ColTemplate(), "im2col", false); // this->kernelCol2Im = kernelBuilder.buildKernel( // "col2im", // "ForwardIm2Col.cl", // getIm2ColTemplate(), // "col2im", // false); } STATIC std::string ForwardIm2Col::getKernelTemplate() { // [[[cog // import stringify // stringify.write_kernel( "kernel", "ForwardIm2Col.cl" ) // ]]] // generated using cog, from cl/forward1.cl: const char * kernelSource = "// Copyright Hugh Perkins 2014, 2015 hughperkins at gmail\n" "//\n" "// This Source Code Form is subject to the terms of the Mozilla Public License,\n" "// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n" "// obtain one at http://mozilla.org/MPL/2.0/.\n" "\n" "// notes on non-odd filtersizes:\n" "// for odd, imagesize and filtersize 3, padZeros = 0:\n" "// output is a single square\n" "// m and n should vary between -1,0,1\n" "// for even, imagesize and filtersize 2, padzeros = 0\n" "// output is a single square, which we can position at topleft or bottomrigth\n" "// lets position it in bottomright\n" "// then m and n should vary as -1,0\n" "//\n" "// for even, imagesize and filtersize 2, padzeros = 1\n" "// output is 2 by 2\n" "// well... if it is even:\n" "// - if we are not padding zeros, then we simply move our filter around the image somehow\n" "// - if we are padding zeros, then we conceptually pad the bottom and right edge of the image with zeros by 1\n" "// filtersize remains the same\n" "// m will vary as -1,0,1\n" "// outputrow is fixed by globalid\n" "// inputrow should be unchanged...\n" "// padzeros = 0:\n" "// x x . . . .\n" "// x x . . x x\n" "// . . . . x x\n" "// when filtersize even:\n" "// new imagesize = oldimagesize - filtersize + 1\n" "// when filtersize odd:\n" "// x x x .\n" "// x x x .\n" "// x x x .\n" "// . . . .\n" "// new imagesize = oldimagesize - filtersize + 1\n" "// padzeros = 1:\n" "// x x\n" "// x x . . x x . . . . . . .\n" "// . . . x x . . x x . . .\n" "// . . . . . . . x x . . x x\n" "// outrow=0 outrow=1 outrow=2 x x\n" "// outcol=0 outcol=1 outcol=2 outrow=3\n" "// outcol=3\n" "// when filtersize is even, and padzeros, imagesize grows by 1 each time...\n" "// imagesize = oldimagesize + 1\n" "// when filtersize is odd\n" "// x x x\n" "// x x x . x x x . . .\n" "// x x x . x x x . x x x\n" "// . . . x x x . x x x\n" "// x x x\n" "\n" "// images are organized like [imageId][plane][row][col]\n" "// filters are organized like [filterid][inplane][filterrow][filtercol]\n" "// output are organized like [imageid][filterid][row][col]\n" "// global id is organized like output, ie: [imageid][outplane][outrow][outcol]\n" "// - no local memory used currently\n" "// - each thread:\n" "// - loads a whole upstream cube\n" "// - loads a whole filter cube\n" "// - writes one output...\n" "void kernel convolve_imagecubes_float2(\n" " const int numExamples,\n" " global const float *inputs, global const float *filters,\n" " global float *output ) {\n" " int globalId = get_global_id(0);\n" "\n" " int outputImage2Id = globalId / gOutputImageSizeSquared;\n" " int exampleId = outputImage2Id / gNumFilters;\n" " int filterId = outputImage2Id % gNumFilters;\n" "\n" " // intraimage coords\n" " int localid = globalId % gOutputImageSizeSquared;\n" " int outputRow = localid / gOutputImageSize;\n" " int outputCol = localid % gOutputImageSize;\n" "\n" " global float const*inputCube = inputs + exampleId * gNumInputPlanes * gInputImageSizeSquared;\n" " global float const*filterCube = filters + filterId * gNumInputPlanes * gFilterSizeSquared;\n" "\n" " float sum = 0;\n" " if( exampleId < numExamples ) {\n" " for( int inputPlaneIdx = 0; inputPlaneIdx < gNumInputPlanes; inputPlaneIdx++ ) {\n" " global float const*inputPlane = inputCube + inputPlaneIdx * gInputImageSizeSquared;\n" " global float const*filterPlane = filterCube + inputPlaneIdx * gFilterSizeSquared;\n" " for( int u = -gHalfFilterSize; u <= gHalfFilterSize - gEven; u++ ) {\n" " // trying to reduce register pressure...\n" " #if gPadZeros == 1\n" " #define inputRowIdx ( outputRow + u )\n" " #else\n" " #define inputRowIdx ( outputRow + u + gHalfFilterSize )\n" " #endif\n" " global float const *inputRow = inputPlane + inputRowIdx * gInputImageSize;\n" " global float const *filterRow = filterPlane + (u+gHalfFilterSize) * gFilterSize + gHalfFilterSize;\n" " bool rowOk = inputRowIdx >= 0 && inputRowIdx < gInputImageSize;\n" " #pragma unroll\n" " for( int v = -gHalfFilterSize; v <= gHalfFilterSize - gEven; v++ ) {\n" " #if gPadZeros == 1\n" " #define inputColIdx ( outputCol + v )\n" " #else\n" " #define inputColIdx ( outputCol + v + gHalfFilterSize )\n" " #endif\n" " bool process = rowOk && inputColIdx >= 0 && inputColIdx < gInputImageSize;\n" " if( process ) {\n" " sum += inputRow[inputColIdx] * filterRow[v];\n" " }\n" " }\n" " }\n" " }\n" " }\n" "\n" " if( exampleId < numExamples ) {\n" " output[globalId] = sum;\n" " }\n" "}\n" "\n" ""; kernel = cl->buildKernelFromString( kernelSource, "convolve_imagecubes_float2", options, "cl/ForwardIm2Col.cl" ); // [[[end]]] return kernelSource; } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPictureFlat.h" #include "SkColorFilter.h" #include "SkDrawLooper.h" #include "SkMaskFilter.h" #include "SkRasterizer.h" #include "SkShader.h" #include "SkTypeface.h" #include "SkXfermode.h" #include "SkOrderedReadBuffer.h" #include "SkOrderedWriteBuffer.h" SkFlatData* SkFlatData::Alloc(SkChunkAlloc* heap, int32_t size, int index) { SkFlatData* result = (SkFlatData*) heap->allocThrow(size + sizeof(SkFlatData)); result->fIndex = index; result->fAllocSize = size + sizeof(result->fAllocSize); return result; } SkFlatBitmap* SkFlatBitmap::Flatten(SkChunkAlloc* heap, const SkBitmap& bitmap, int index, SkRefCntSet* rec) { SkOrderedWriteBuffer buffer(1024); buffer.setRefCntRecorder(rec); bitmap.flatten(buffer); size_t size = buffer.size(); SkFlatBitmap* result = (SkFlatBitmap*) INHERITED::Alloc(heap, size, index); buffer.flatten(result->fBitmapData); return result; } SkFlatMatrix* SkFlatMatrix::Flatten(SkChunkAlloc* heap, const SkMatrix& matrix, int index) { size_t size = matrix.flatten(NULL); SkFlatMatrix* result = (SkFlatMatrix*) INHERITED::Alloc(heap, size, index); matrix.flatten(&result->fMatrixData); return result; } #ifdef SK_DEBUG_DUMP void SkFlatMatrix::dump() const { const SkMatrix* matrix = (const SkMatrix*) fMatrixData; char pBuffer[DUMP_BUFFER_SIZE]; char* bufferPtr = pBuffer; bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "matrix: "); SkScalar scaleX = matrix->getScaleX(); SkMatrix defaultMatrix; defaultMatrix.reset(); if (scaleX != defaultMatrix.getScaleX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "scaleX:%g ", SkScalarToFloat(scaleX)); SkScalar scaleY = matrix->getScaleY(); if (scaleY != defaultMatrix.getScaleY()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "scaleY:%g ", SkScalarToFloat(scaleY)); SkScalar skewX = matrix->getSkewX(); if (skewX != defaultMatrix.getSkewX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "skewX:%g ", SkScalarToFloat(skewX)); SkScalar skewY = matrix->getSkewY(); if (skewY != defaultMatrix.getSkewY()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "skewY:%g ", SkScalarToFloat(skewY)); SkScalar translateX = matrix->getTranslateX(); if (translateX != defaultMatrix.getTranslateX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "translateX:%g ", SkScalarToFloat(translateX)); SkScalar translateY = matrix->getTranslateY(); if (translateY != defaultMatrix.getTranslateY()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "translateY:%g ", SkScalarToFloat(translateY)); SkScalar perspX = matrix->getPerspX(); if (perspX != defaultMatrix.getPerspX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "perspX:%g ", SkFractToFloat(perspX)); SkScalar perspY = matrix->getPerspY(); if (perspY != defaultMatrix.getPerspY()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "perspY:%g ", SkFractToFloat(perspY)); SkDebugf("%s\n", pBuffer); } #endif /////////////////////////////////////////////////////////////////////////////// SkFlatPaint* SkFlatPaint::Flatten(SkChunkAlloc* heap, const SkPaint& paint, int index, SkRefCntSet* rec, SkRefCntSet* faceRecorder) { SkOrderedWriteBuffer buffer(2*sizeof(SkPaint)); buffer.setRefCntRecorder(rec); buffer.setTypefaceRecorder(faceRecorder); paint.flatten(buffer); uint32_t size = buffer.size(); SkFlatPaint* result = (SkFlatPaint*) INHERITED::Alloc(heap, size, index); buffer.flatten(&result->fPaintData); return result; } void SkFlatPaint::Read(const void* storage, SkPaint* paint, SkRefCntPlayback* rcp, SkTypefacePlayback* facePlayback) { SkOrderedReadBuffer buffer(storage, 1024*1024); if (rcp) { rcp->setupBuffer(buffer); } if (facePlayback) { facePlayback->setupBuffer(buffer); } paint->unflatten(buffer); } #ifdef SK_DEBUG_DUMP void SkFlatPaint::dump() const { SkPaint defaultPaint; SkFlattenableReadBuffer buffer(fPaintData); SkTypeface* typeface = (SkTypeface*) buffer.readPtr(); char pBuffer[DUMP_BUFFER_SIZE]; char* bufferPtr = pBuffer; bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "paint: "); if (typeface != defaultPaint.getTypeface()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "typeface:%p ", typeface); SkScalar textSize = buffer.readScalar(); if (textSize != defaultPaint.getTextSize()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textSize:%g ", SkScalarToFloat(textSize)); SkScalar textScaleX = buffer.readScalar(); if (textScaleX != defaultPaint.getTextScaleX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textScaleX:%g ", SkScalarToFloat(textScaleX)); SkScalar textSkewX = buffer.readScalar(); if (textSkewX != defaultPaint.getTextSkewX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textSkewX:%g ", SkScalarToFloat(textSkewX)); const SkPathEffect* pathEffect = (const SkPathEffect*) buffer.readFlattenable(); if (pathEffect != defaultPaint.getPathEffect()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "pathEffect:%p ", pathEffect); SkDELETE(pathEffect); const SkShader* shader = (const SkShader*) buffer.readFlattenable(); if (shader != defaultPaint.getShader()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "shader:%p ", shader); SkDELETE(shader); const SkXfermode* xfermode = (const SkXfermode*) buffer.readFlattenable(); if (xfermode != defaultPaint.getXfermode()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "xfermode:%p ", xfermode); SkDELETE(xfermode); const SkMaskFilter* maskFilter = (const SkMaskFilter*) buffer.readFlattenable(); if (maskFilter != defaultPaint.getMaskFilter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "maskFilter:%p ", maskFilter); SkDELETE(maskFilter); const SkColorFilter* colorFilter = (const SkColorFilter*) buffer.readFlattenable(); if (colorFilter != defaultPaint.getColorFilter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "colorFilter:%p ", colorFilter); SkDELETE(colorFilter); const SkRasterizer* rasterizer = (const SkRasterizer*) buffer.readFlattenable(); if (rasterizer != defaultPaint.getRasterizer()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "rasterizer:%p ", rasterizer); SkDELETE(rasterizer); const SkDrawLooper* drawLooper = (const SkDrawLooper*) buffer.readFlattenable(); if (drawLooper != defaultPaint.getLooper()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "drawLooper:%p ", drawLooper); SkDELETE(drawLooper); unsigned color = buffer.readU32(); if (color != defaultPaint.getColor()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "color:0x%x ", color); SkScalar strokeWidth = buffer.readScalar(); if (strokeWidth != defaultPaint.getStrokeWidth()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeWidth:%g ", SkScalarToFloat(strokeWidth)); SkScalar strokeMiter = buffer.readScalar(); if (strokeMiter != defaultPaint.getStrokeMiter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeMiter:%g ", SkScalarToFloat(strokeMiter)); unsigned flags = buffer.readU16(); if (flags != defaultPaint.getFlags()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "flags:0x%x ", flags); int align = buffer.readU8(); if (align != defaultPaint.getTextAlign()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "align:0x%x ", align); int strokeCap = buffer.readU8(); if (strokeCap != defaultPaint.getStrokeCap()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeCap:0x%x ", strokeCap); int strokeJoin = buffer.readU8(); if (strokeJoin != defaultPaint.getStrokeJoin()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "align:0x%x ", strokeJoin); int style = buffer.readU8(); if (style != defaultPaint.getStyle()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "style:0x%x ", style); int textEncoding = buffer.readU8(); if (textEncoding != defaultPaint.getTextEncoding()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textEncoding:0x%x ", textEncoding); SkDebugf("%s\n", pBuffer); } #endif SkFlatRegion* SkFlatRegion::Flatten(SkChunkAlloc* heap, const SkRegion& region, int index) { uint32_t size = region.flatten(NULL); SkFlatRegion* result = (SkFlatRegion*) INHERITED::Alloc(heap, size, index); region.flatten(&result->fRegionData); return result; } /////////////////////////////////////////////////////////////////////////////// SkRefCntPlayback::SkRefCntPlayback() : fCount(0), fArray(NULL) {} SkRefCntPlayback::~SkRefCntPlayback() { this->reset(NULL); } void SkRefCntPlayback::reset(const SkRefCntSet* rec) { for (int i = 0; i < fCount; i++) { SkASSERT(fArray[i]); fArray[i]->unref(); } SkDELETE_ARRAY(fArray); if (rec) { fCount = rec->count(); fArray = SkNEW_ARRAY(SkRefCnt*, fCount); rec->copyToArray(fArray); for (int i = 0; i < fCount; i++) { fArray[i]->ref(); } } else { fCount = 0; fArray = NULL; } } void SkRefCntPlayback::setCount(int count) { this->reset(NULL); fCount = count; fArray = SkNEW_ARRAY(SkRefCnt*, count); sk_bzero(fArray, count * sizeof(SkRefCnt*)); } SkRefCnt* SkRefCntPlayback::set(int index, SkRefCnt* obj) { SkASSERT((unsigned)index < (unsigned)fCount); SkRefCnt_SafeAssign(fArray[index], obj); return obj; } <commit_msg>use new storage parameter to SkOrderedWriteBuffer (to avoid small dynamic allocs)<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPictureFlat.h" #include "SkColorFilter.h" #include "SkDrawLooper.h" #include "SkMaskFilter.h" #include "SkRasterizer.h" #include "SkShader.h" #include "SkTypeface.h" #include "SkXfermode.h" #include "SkOrderedReadBuffer.h" #include "SkOrderedWriteBuffer.h" SkFlatData* SkFlatData::Alloc(SkChunkAlloc* heap, int32_t size, int index) { SkFlatData* result = (SkFlatData*) heap->allocThrow(size + sizeof(SkFlatData)); result->fIndex = index; result->fAllocSize = size + sizeof(result->fAllocSize); return result; } SkFlatBitmap* SkFlatBitmap::Flatten(SkChunkAlloc* heap, const SkBitmap& bitmap, int index, SkRefCntSet* rec) { SkOrderedWriteBuffer buffer(1024); buffer.setRefCntRecorder(rec); bitmap.flatten(buffer); size_t size = buffer.size(); SkFlatBitmap* result = (SkFlatBitmap*) INHERITED::Alloc(heap, size, index); buffer.flatten(result->fBitmapData); return result; } SkFlatMatrix* SkFlatMatrix::Flatten(SkChunkAlloc* heap, const SkMatrix& matrix, int index) { size_t size = matrix.flatten(NULL); SkFlatMatrix* result = (SkFlatMatrix*) INHERITED::Alloc(heap, size, index); matrix.flatten(&result->fMatrixData); return result; } #ifdef SK_DEBUG_DUMP void SkFlatMatrix::dump() const { const SkMatrix* matrix = (const SkMatrix*) fMatrixData; char pBuffer[DUMP_BUFFER_SIZE]; char* bufferPtr = pBuffer; bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "matrix: "); SkScalar scaleX = matrix->getScaleX(); SkMatrix defaultMatrix; defaultMatrix.reset(); if (scaleX != defaultMatrix.getScaleX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "scaleX:%g ", SkScalarToFloat(scaleX)); SkScalar scaleY = matrix->getScaleY(); if (scaleY != defaultMatrix.getScaleY()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "scaleY:%g ", SkScalarToFloat(scaleY)); SkScalar skewX = matrix->getSkewX(); if (skewX != defaultMatrix.getSkewX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "skewX:%g ", SkScalarToFloat(skewX)); SkScalar skewY = matrix->getSkewY(); if (skewY != defaultMatrix.getSkewY()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "skewY:%g ", SkScalarToFloat(skewY)); SkScalar translateX = matrix->getTranslateX(); if (translateX != defaultMatrix.getTranslateX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "translateX:%g ", SkScalarToFloat(translateX)); SkScalar translateY = matrix->getTranslateY(); if (translateY != defaultMatrix.getTranslateY()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "translateY:%g ", SkScalarToFloat(translateY)); SkScalar perspX = matrix->getPerspX(); if (perspX != defaultMatrix.getPerspX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "perspX:%g ", SkFractToFloat(perspX)); SkScalar perspY = matrix->getPerspY(); if (perspY != defaultMatrix.getPerspY()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "perspY:%g ", SkFractToFloat(perspY)); SkDebugf("%s\n", pBuffer); } #endif /////////////////////////////////////////////////////////////////////////////// SkFlatPaint* SkFlatPaint::Flatten(SkChunkAlloc* heap, const SkPaint& paint, int index, SkRefCntSet* rec, SkRefCntSet* faceRecorder) { intptr_t storage[256]; SkOrderedWriteBuffer buffer(4*sizeof(SkPaint), storage, sizeof(storage)); buffer.setRefCntRecorder(rec); buffer.setTypefaceRecorder(faceRecorder); paint.flatten(buffer); uint32_t size = buffer.size(); SkFlatPaint* result = (SkFlatPaint*) INHERITED::Alloc(heap, size, index); buffer.flatten(&result->fPaintData); return result; } void SkFlatPaint::Read(const void* storage, SkPaint* paint, SkRefCntPlayback* rcp, SkTypefacePlayback* facePlayback) { SkOrderedReadBuffer buffer(storage, 1024*1024); if (rcp) { rcp->setupBuffer(buffer); } if (facePlayback) { facePlayback->setupBuffer(buffer); } paint->unflatten(buffer); } #ifdef SK_DEBUG_DUMP void SkFlatPaint::dump() const { SkPaint defaultPaint; SkFlattenableReadBuffer buffer(fPaintData); SkTypeface* typeface = (SkTypeface*) buffer.readPtr(); char pBuffer[DUMP_BUFFER_SIZE]; char* bufferPtr = pBuffer; bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "paint: "); if (typeface != defaultPaint.getTypeface()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "typeface:%p ", typeface); SkScalar textSize = buffer.readScalar(); if (textSize != defaultPaint.getTextSize()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textSize:%g ", SkScalarToFloat(textSize)); SkScalar textScaleX = buffer.readScalar(); if (textScaleX != defaultPaint.getTextScaleX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textScaleX:%g ", SkScalarToFloat(textScaleX)); SkScalar textSkewX = buffer.readScalar(); if (textSkewX != defaultPaint.getTextSkewX()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textSkewX:%g ", SkScalarToFloat(textSkewX)); const SkPathEffect* pathEffect = (const SkPathEffect*) buffer.readFlattenable(); if (pathEffect != defaultPaint.getPathEffect()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "pathEffect:%p ", pathEffect); SkDELETE(pathEffect); const SkShader* shader = (const SkShader*) buffer.readFlattenable(); if (shader != defaultPaint.getShader()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "shader:%p ", shader); SkDELETE(shader); const SkXfermode* xfermode = (const SkXfermode*) buffer.readFlattenable(); if (xfermode != defaultPaint.getXfermode()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "xfermode:%p ", xfermode); SkDELETE(xfermode); const SkMaskFilter* maskFilter = (const SkMaskFilter*) buffer.readFlattenable(); if (maskFilter != defaultPaint.getMaskFilter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "maskFilter:%p ", maskFilter); SkDELETE(maskFilter); const SkColorFilter* colorFilter = (const SkColorFilter*) buffer.readFlattenable(); if (colorFilter != defaultPaint.getColorFilter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "colorFilter:%p ", colorFilter); SkDELETE(colorFilter); const SkRasterizer* rasterizer = (const SkRasterizer*) buffer.readFlattenable(); if (rasterizer != defaultPaint.getRasterizer()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "rasterizer:%p ", rasterizer); SkDELETE(rasterizer); const SkDrawLooper* drawLooper = (const SkDrawLooper*) buffer.readFlattenable(); if (drawLooper != defaultPaint.getLooper()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "drawLooper:%p ", drawLooper); SkDELETE(drawLooper); unsigned color = buffer.readU32(); if (color != defaultPaint.getColor()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "color:0x%x ", color); SkScalar strokeWidth = buffer.readScalar(); if (strokeWidth != defaultPaint.getStrokeWidth()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeWidth:%g ", SkScalarToFloat(strokeWidth)); SkScalar strokeMiter = buffer.readScalar(); if (strokeMiter != defaultPaint.getStrokeMiter()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeMiter:%g ", SkScalarToFloat(strokeMiter)); unsigned flags = buffer.readU16(); if (flags != defaultPaint.getFlags()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "flags:0x%x ", flags); int align = buffer.readU8(); if (align != defaultPaint.getTextAlign()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "align:0x%x ", align); int strokeCap = buffer.readU8(); if (strokeCap != defaultPaint.getStrokeCap()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "strokeCap:0x%x ", strokeCap); int strokeJoin = buffer.readU8(); if (strokeJoin != defaultPaint.getStrokeJoin()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "align:0x%x ", strokeJoin); int style = buffer.readU8(); if (style != defaultPaint.getStyle()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "style:0x%x ", style); int textEncoding = buffer.readU8(); if (textEncoding != defaultPaint.getTextEncoding()) bufferPtr += snprintf(bufferPtr, DUMP_BUFFER_SIZE - (bufferPtr - pBuffer), "textEncoding:0x%x ", textEncoding); SkDebugf("%s\n", pBuffer); } #endif SkFlatRegion* SkFlatRegion::Flatten(SkChunkAlloc* heap, const SkRegion& region, int index) { uint32_t size = region.flatten(NULL); SkFlatRegion* result = (SkFlatRegion*) INHERITED::Alloc(heap, size, index); region.flatten(&result->fRegionData); return result; } /////////////////////////////////////////////////////////////////////////////// SkRefCntPlayback::SkRefCntPlayback() : fCount(0), fArray(NULL) {} SkRefCntPlayback::~SkRefCntPlayback() { this->reset(NULL); } void SkRefCntPlayback::reset(const SkRefCntSet* rec) { for (int i = 0; i < fCount; i++) { SkASSERT(fArray[i]); fArray[i]->unref(); } SkDELETE_ARRAY(fArray); if (rec) { fCount = rec->count(); fArray = SkNEW_ARRAY(SkRefCnt*, fCount); rec->copyToArray(fArray); for (int i = 0; i < fCount; i++) { fArray[i]->ref(); } } else { fCount = 0; fArray = NULL; } } void SkRefCntPlayback::setCount(int count) { this->reset(NULL); fCount = count; fArray = SkNEW_ARRAY(SkRefCnt*, count); sk_bzero(fArray, count * sizeof(SkRefCnt*)); } SkRefCnt* SkRefCntPlayback::set(int index, SkRefCnt* obj) { SkASSERT((unsigned)index < (unsigned)fCount); SkRefCnt_SafeAssign(fArray[index], obj); return obj; } <|endoftext|>
<commit_before>/* <src/capi.cpp> * * This file is part of the x0 web server project and is released under GPL-3. * http://www.xzero.io/ * * (c) 2009-2013 Christian Parpart <trapni@gmail.com> */ #include <x0/capi.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpWorker.h> #include <x0/http/HttpRequest.h> #include <x0/io/BufferSource.h> #include <cstdarg> using namespace x0; struct x0_server_s { HttpServer server; bool autoflush; x0_server_s(struct ev_loop* loop) : server(loop), autoflush(true) {} }; struct x0_request_s { x0_server_t* server; HttpRequest* request; x0_request_body_fn body_cb; void* body_userdata; x0_request_abort_fn abort_cb; void* abort_userdata; x0_request_s(HttpRequest* r, x0_server_t* s) : server(s), request(r), body_cb(nullptr), body_userdata(nullptr), abort_cb(nullptr), abort_userdata(nullptr) { request->connection.setAutoFlush(server->autoflush); } void bodyCallback(const BufferRef& ref) { if (body_cb) { body_cb(this, ref.data(), ref.size(), body_userdata); } } static void abortCallback(void* p) { x0_request_s* self = (x0_request_s*) p; if (self->abort_cb) { self->abort_cb(self->abort_userdata); } } }; x0_server_t* x0_server_create(struct ev_loop* loop) { auto s = new x0_server_t(loop); s->server.requestHandler = [](HttpRequest* r) -> bool { BufferSource body("Hello, I am lazy to serve anything; I wasn't configured properly\n"); r->status = HttpStatus::InternalServerError; char buf[40]; snprintf(buf, sizeof(buf), "%zu", body.size()); r->responseHeaders.push_back("Content-Length", buf); r->responseHeaders.push_back("Content-Type", "plain/text"); r->write<BufferSource>(body); r->finish(); return true; }; return s; } int x0_listener_add(x0_server_t* server, const char* bind, int port, int backlog) { auto listener = server->server.setupListener(bind, port, 128); if (listener == nullptr) return -1; return 0; } void x0_server_destroy(x0_server_t* server, int kill) { if (!kill) { // TODO wait until all current connections have been finished, if more than one worker has been set up } delete server; } void x0_server_stop(x0_server_t* server) { server->server.stop(); } int x0_setup_worker_count(x0_server_t* server, int count) { ssize_t current = server->server.workers().size(); while (current < count) { server->server.spawnWorker(); current = server->server.workers().size(); } return 0; } void x0_setup_handler(x0_server_t* server, x0_request_handler_fn handler, void* userdata) { server->server.requestHandler = [=](HttpRequest* r) -> bool { auto rr = new x0_request_t(r, server); handler(rr, userdata); return true; }; } void x0_setup_connection_limit(x0_server_t* li, size_t limit) { li->server.maxConnections = limit; } void x0_setup_timeouts(x0_server_t* server, int read, int write) { server->server.maxReadIdle = TimeSpan::fromSeconds(read); server->server.maxWriteIdle = TimeSpan::fromSeconds(write); } void x0_setup_keepalive(x0_server_t* server, int count, int timeout) { server->server.maxKeepAliveRequests = count; server->server.maxKeepAlive = TimeSpan::fromSeconds(timeout); } void x0_setup_autoflush(x0_server_t* server, int value) { server->autoflush = value; } // -------------------------------------------------------------------------- // REQUEST SETUP void x0_request_body_callback(x0_request_t* r, x0_request_body_fn handler, void* userdata) { r->request->setBodyCallback<x0_request_t, &x0_request_t::bodyCallback>(r); r->body_cb = handler; r->body_userdata = userdata; } void x0_request_abort_callback(x0_request_t* r, x0_request_abort_fn handler, void* userdata) { r->request->setAbortHandler(&x0_request_t::abortCallback, r); r->abort_cb = handler; r->abort_userdata = userdata; } void x0_request_post(x0_request_t* r, x0_request_post_fn fn, void* userdata) { r->request->post([=]() { fn(r, userdata); }); } // -------------------------------------------------------------------------- // REQUEST int x0_request_method_id(x0_request_t* r) { if (r->request->method == "GET") return X0_REQUEST_METHOD_GET; if (r->request->method == "POST") return X0_REQUEST_METHOD_POST; if (r->request->method == "PUT") return X0_REQUEST_METHOD_PUT; if (r->request->method == "DELETE") return X0_REQUEST_METHOD_DELETE; return X0_REQUEST_METHOD_UNKNOWN; } size_t x0_request_method(x0_request_t* r, char* buf, size_t size) { if (!size) return 0; size_t n = std::min(r->request->method.size(), size - 1); memcpy(buf, r->request->method.data(), n); buf[n] = '\0'; return n; } size_t x0_request_path(x0_request_t* r, char* buf, size_t size) { size_t rsize = std::min(size - 1, r->request->path.size()); memcpy(buf, r->request->path.data(), rsize); buf[rsize] = '\0'; return rsize + 1; } int x0_request_version(x0_request_t* r) { static const struct { int major; int minor; int code; } versions[] = { { 0, 9, X0_HTTP_VERSION_0_9 }, { 1, 0, X0_HTTP_VERSION_1_0 }, { 1, 1, X0_HTTP_VERSION_1_1 }, { 2, 0, X0_HTTP_VERSION_2_0 }, }; int major = r->request->httpVersionMajor; int minor = r->request->httpVersionMinor; for (const auto& version: versions) if (version.major == major && version.minor == minor) return version.code; return X0_HTTP_VERSION_UNKNOWN; } int x0_request_header_exists(x0_request_t* r, const char* name) { for (const auto& header: r->request->requestHeaders) if (header.name == name) return 1; return 0; } int x0_request_header_get(x0_request_t* r, const char* name, char* buf, size_t size) { if (size) { for (const auto& header: r->request->requestHeaders) { if (header.name == name) { size_t len = std::min(header.value.size(), size - 1); memcpy(buf, header.value.data(), len); buf[len] = '\0'; return len; } } } return 0; } int x0_request_cookie_get(x0_request_t* r, const char* cookie, char* buf, size_t size) { if (size == 0) return 0; BufferRef value = r->request->cookie(cookie); size_t n = std::min(value.size(), size - 1); memcpy(buf, value.data(), n); buf[n] = '\0'; return n; } int x0_request_header_count(x0_request_t* r) { return r->request->requestHeaders.size(); } int x0_request_header_name_geti(x0_request_t* r, off_t index, char* buf, size_t size) { if (size && (size_t)index < r->request->requestHeaders.size()) { const auto& header = r->request->requestHeaders[index]; size_t len = std::min(header.name.size(), size - 1); memcpy(buf, header.name.data(), len); buf[len] = '\0'; return len; } return 0; } int x0_request_header_value_geti(x0_request_t* r, off_t index, char* buf, size_t size) { if (size && (size_t)index < r->request->requestHeaders.size()) { const auto& header = r->request->requestHeaders[index]; size_t len = std::min(header.value.size(), size - 1); memcpy(buf, header.value.data(), len); buf[len] = '\0'; return len; } return 0; } // -------------------------------------------------------------------------- // RESPONSE void x0_response_flush(x0_request_t* r) { r->request->connection.flush(); } void x0_response_status_set(x0_request_t* r, int code) { r->request->status = static_cast<HttpStatus>(code); } void x0_response_header_set(x0_request_t* r, const char* name, const char* value) { r->request->responseHeaders.overwrite(name, value); } void x0_response_write(x0_request_t* r, const char* buf, size_t size) { Buffer b; b.push_back(buf, size); r->request->write<BufferSource>(b); } void x0_response_printf(x0_request_t* r, const char* fmt, ...) { Buffer b; va_list ap; va_start(ap, fmt); b.vprintf(fmt, ap); va_end(ap); r->request->write<BufferSource>(b); } void x0_response_vprintf(x0_request_t* r, const char* fmt, va_list args) { Buffer b; va_list va; va_copy(va, args); b.vprintf(fmt, va); va_end(va); r->request->write<BufferSource>(b); } void x0_response_finish(x0_request_t* r) { r->request->finish(); delete r; } void x0_response_sendfile(x0_request_t* r, const char* path) { r->request->sendfile(path); } <commit_msg>capi: always auto-flush on finish<commit_after>/* <src/capi.cpp> * * This file is part of the x0 web server project and is released under GPL-3. * http://www.xzero.io/ * * (c) 2009-2013 Christian Parpart <trapni@gmail.com> */ #include <x0/capi.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpWorker.h> #include <x0/http/HttpRequest.h> #include <x0/io/BufferSource.h> #include <cstdarg> using namespace x0; struct x0_server_s { HttpServer server; bool autoflush; x0_server_s(struct ev_loop* loop) : server(loop), autoflush(true) {} }; struct x0_request_s { x0_server_t* server; HttpRequest* request; x0_request_body_fn body_cb; void* body_userdata; x0_request_abort_fn abort_cb; void* abort_userdata; x0_request_s(HttpRequest* r, x0_server_t* s) : server(s), request(r), body_cb(nullptr), body_userdata(nullptr), abort_cb(nullptr), abort_userdata(nullptr) { request->connection.setAutoFlush(server->autoflush); } void bodyCallback(const BufferRef& ref) { if (body_cb) { body_cb(this, ref.data(), ref.size(), body_userdata); } } static void abortCallback(void* p) { x0_request_s* self = (x0_request_s*) p; if (self->abort_cb) { self->abort_cb(self->abort_userdata); } } }; x0_server_t* x0_server_create(struct ev_loop* loop) { auto s = new x0_server_t(loop); s->server.requestHandler = [](HttpRequest* r) -> bool { BufferSource body("Hello, I am lazy to serve anything; I wasn't configured properly\n"); r->status = HttpStatus::InternalServerError; char buf[40]; snprintf(buf, sizeof(buf), "%zu", body.size()); r->responseHeaders.push_back("Content-Length", buf); r->responseHeaders.push_back("Content-Type", "plain/text"); r->write<BufferSource>(body); r->finish(); return true; }; return s; } int x0_listener_add(x0_server_t* server, const char* bind, int port, int backlog) { auto listener = server->server.setupListener(bind, port, 128); if (listener == nullptr) return -1; return 0; } void x0_server_destroy(x0_server_t* server, int kill) { if (!kill) { // TODO wait until all current connections have been finished, if more than one worker has been set up } delete server; } void x0_server_stop(x0_server_t* server) { server->server.stop(); } int x0_setup_worker_count(x0_server_t* server, int count) { ssize_t current = server->server.workers().size(); while (current < count) { server->server.spawnWorker(); current = server->server.workers().size(); } return 0; } void x0_setup_handler(x0_server_t* server, x0_request_handler_fn handler, void* userdata) { server->server.requestHandler = [=](HttpRequest* r) -> bool { auto rr = new x0_request_t(r, server); handler(rr, userdata); return true; }; } void x0_setup_connection_limit(x0_server_t* li, size_t limit) { li->server.maxConnections = limit; } void x0_setup_timeouts(x0_server_t* server, int read, int write) { server->server.maxReadIdle = TimeSpan::fromSeconds(read); server->server.maxWriteIdle = TimeSpan::fromSeconds(write); } void x0_setup_keepalive(x0_server_t* server, int count, int timeout) { server->server.maxKeepAliveRequests = count; server->server.maxKeepAlive = TimeSpan::fromSeconds(timeout); } void x0_setup_autoflush(x0_server_t* server, int value) { server->autoflush = value; } // -------------------------------------------------------------------------- // REQUEST SETUP void x0_request_body_callback(x0_request_t* r, x0_request_body_fn handler, void* userdata) { r->request->setBodyCallback<x0_request_t, &x0_request_t::bodyCallback>(r); r->body_cb = handler; r->body_userdata = userdata; } void x0_request_abort_callback(x0_request_t* r, x0_request_abort_fn handler, void* userdata) { r->request->setAbortHandler(&x0_request_t::abortCallback, r); r->abort_cb = handler; r->abort_userdata = userdata; } void x0_request_post(x0_request_t* r, x0_request_post_fn fn, void* userdata) { r->request->post([=]() { fn(r, userdata); }); } // -------------------------------------------------------------------------- // REQUEST int x0_request_method_id(x0_request_t* r) { if (r->request->method == "GET") return X0_REQUEST_METHOD_GET; if (r->request->method == "POST") return X0_REQUEST_METHOD_POST; if (r->request->method == "PUT") return X0_REQUEST_METHOD_PUT; if (r->request->method == "DELETE") return X0_REQUEST_METHOD_DELETE; return X0_REQUEST_METHOD_UNKNOWN; } size_t x0_request_method(x0_request_t* r, char* buf, size_t size) { if (!size) return 0; size_t n = std::min(r->request->method.size(), size - 1); memcpy(buf, r->request->method.data(), n); buf[n] = '\0'; return n; } size_t x0_request_path(x0_request_t* r, char* buf, size_t size) { size_t rsize = std::min(size - 1, r->request->path.size()); memcpy(buf, r->request->path.data(), rsize); buf[rsize] = '\0'; return rsize + 1; } int x0_request_version(x0_request_t* r) { static const struct { int major; int minor; int code; } versions[] = { { 0, 9, X0_HTTP_VERSION_0_9 }, { 1, 0, X0_HTTP_VERSION_1_0 }, { 1, 1, X0_HTTP_VERSION_1_1 }, { 2, 0, X0_HTTP_VERSION_2_0 }, }; int major = r->request->httpVersionMajor; int minor = r->request->httpVersionMinor; for (const auto& version: versions) if (version.major == major && version.minor == minor) return version.code; return X0_HTTP_VERSION_UNKNOWN; } int x0_request_header_exists(x0_request_t* r, const char* name) { for (const auto& header: r->request->requestHeaders) if (header.name == name) return 1; return 0; } int x0_request_header_get(x0_request_t* r, const char* name, char* buf, size_t size) { if (size) { for (const auto& header: r->request->requestHeaders) { if (header.name == name) { size_t len = std::min(header.value.size(), size - 1); memcpy(buf, header.value.data(), len); buf[len] = '\0'; return len; } } } return 0; } int x0_request_cookie_get(x0_request_t* r, const char* cookie, char* buf, size_t size) { if (size == 0) return 0; BufferRef value = r->request->cookie(cookie); size_t n = std::min(value.size(), size - 1); memcpy(buf, value.data(), n); buf[n] = '\0'; return n; } int x0_request_header_count(x0_request_t* r) { return r->request->requestHeaders.size(); } int x0_request_header_name_geti(x0_request_t* r, off_t index, char* buf, size_t size) { if (size && (size_t)index < r->request->requestHeaders.size()) { const auto& header = r->request->requestHeaders[index]; size_t len = std::min(header.name.size(), size - 1); memcpy(buf, header.name.data(), len); buf[len] = '\0'; return len; } return 0; } int x0_request_header_value_geti(x0_request_t* r, off_t index, char* buf, size_t size) { if (size && (size_t)index < r->request->requestHeaders.size()) { const auto& header = r->request->requestHeaders[index]; size_t len = std::min(header.value.size(), size - 1); memcpy(buf, header.value.data(), len); buf[len] = '\0'; return len; } return 0; } // -------------------------------------------------------------------------- // RESPONSE void x0_response_flush(x0_request_t* r) { r->request->connection.flush(); } void x0_response_status_set(x0_request_t* r, int code) { r->request->status = static_cast<HttpStatus>(code); } void x0_response_header_set(x0_request_t* r, const char* name, const char* value) { r->request->responseHeaders.overwrite(name, value); } void x0_response_write(x0_request_t* r, const char* buf, size_t size) { Buffer b; b.push_back(buf, size); r->request->write<BufferSource>(b); } void x0_response_printf(x0_request_t* r, const char* fmt, ...) { Buffer b; va_list ap; va_start(ap, fmt); b.vprintf(fmt, ap); va_end(ap); r->request->write<BufferSource>(b); } void x0_response_vprintf(x0_request_t* r, const char* fmt, va_list args) { Buffer b; va_list va; va_copy(va, args); b.vprintf(fmt, va); va_end(va); r->request->write<BufferSource>(b); } void x0_response_finish(x0_request_t* r) { r->request->finish(); if (!r->server->autoflush) r->request->connection.flush(); delete r; } void x0_response_sendfile(x0_request_t* r, const char* path) { r->request->sendfile(path); } <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/core/SkWriteBuffer.h" #include "include/core/SkBitmap.h" #include "include/core/SkData.h" #include "include/core/SkM44.h" #include "include/core/SkStream.h" #include "include/core/SkTypeface.h" #include "include/private/SkTo.h" #include "src/core/SkImagePriv.h" #include "src/core/SkMatrixPriv.h" #include "src/core/SkPaintPriv.h" #include "src/core/SkPtrRecorder.h" /////////////////////////////////////////////////////////////////////////////////////////////////// SkBinaryWriteBuffer::SkBinaryWriteBuffer() : fFactorySet(nullptr) , fTFSet(nullptr) { } SkBinaryWriteBuffer::SkBinaryWriteBuffer(void* storage, size_t storageSize) : fFactorySet(nullptr) , fTFSet(nullptr) , fWriter(storage, storageSize) {} SkBinaryWriteBuffer::~SkBinaryWriteBuffer() {} bool SkBinaryWriteBuffer::usingInitialStorage() const { return fWriter.usingInitialStorage(); } void SkBinaryWriteBuffer::writeByteArray(const void* data, size_t size) { fWriter.write32(SkToU32(size)); fWriter.writePad(data, size); } void SkBinaryWriteBuffer::writeBool(bool value) { fWriter.writeBool(value); } void SkBinaryWriteBuffer::writeScalar(SkScalar value) { fWriter.writeScalar(value); } void SkBinaryWriteBuffer::writeScalarArray(const SkScalar* value, uint32_t count) { fWriter.write32(count); fWriter.write(value, count * sizeof(SkScalar)); } void SkBinaryWriteBuffer::writeInt(int32_t value) { fWriter.write32(value); } void SkBinaryWriteBuffer::writeIntArray(const int32_t* value, uint32_t count) { fWriter.write32(count); fWriter.write(value, count * sizeof(int32_t)); } void SkBinaryWriteBuffer::writeUInt(uint32_t value) { fWriter.write32(value); } void SkBinaryWriteBuffer::writeString(const char* value) { fWriter.writeString(value); } void SkBinaryWriteBuffer::writeColor(SkColor color) { fWriter.write32(color); } void SkBinaryWriteBuffer::writeColorArray(const SkColor* color, uint32_t count) { fWriter.write32(count); fWriter.write(color, count * sizeof(SkColor)); } void SkBinaryWriteBuffer::writeColor4f(const SkColor4f& color) { fWriter.write(&color, sizeof(SkColor4f)); } void SkBinaryWriteBuffer::writeColor4fArray(const SkColor4f* color, uint32_t count) { fWriter.write32(count); fWriter.write(color, count * sizeof(SkColor4f)); } void SkBinaryWriteBuffer::writePoint(const SkPoint& point) { fWriter.writeScalar(point.fX); fWriter.writeScalar(point.fY); } void SkBinaryWriteBuffer::writePoint3(const SkPoint3& point) { this->writePad32(&point, sizeof(SkPoint3)); } void SkBinaryWriteBuffer::writePointArray(const SkPoint* point, uint32_t count) { fWriter.write32(count); fWriter.write(point, count * sizeof(SkPoint)); } void SkBinaryWriteBuffer::write(const SkM44& matrix) { fWriter.write(SkMatrixPriv::M44ColMajor(matrix), sizeof(float) * 16); } void SkBinaryWriteBuffer::writeMatrix(const SkMatrix& matrix) { fWriter.writeMatrix(matrix); } void SkBinaryWriteBuffer::writeIRect(const SkIRect& rect) { fWriter.write(&rect, sizeof(SkIRect)); } void SkBinaryWriteBuffer::writeRect(const SkRect& rect) { fWriter.writeRect(rect); } void SkBinaryWriteBuffer::writeRegion(const SkRegion& region) { fWriter.writeRegion(region); } void SkBinaryWriteBuffer::writePath(const SkPath& path) { fWriter.writePath(path); } size_t SkBinaryWriteBuffer::writeStream(SkStream* stream, size_t length) { fWriter.write32(SkToU32(length)); size_t bytesWritten = fWriter.readFromStream(stream, length); if (bytesWritten < length) { fWriter.reservePad(length - bytesWritten); } return bytesWritten; } bool SkBinaryWriteBuffer::writeToStream(SkWStream* stream) const { return fWriter.writeToStream(stream); } #include "src/image/SkImage_Base.h" /* Format: * flags: U32 * encoded : size_32 + data[] * [subset: IRect] * [mips] : size_32 + data[] */ void SkBinaryWriteBuffer::writeImage(const SkImage* image) { uint32_t flags = 0; const SkMipmap* mips = as_IB(image)->onPeekMips(); if (mips) { flags |= SkWriteBufferImageFlags::kHasMipmap; } this->write32(flags); sk_sp<SkData> data; if (fProcs.fImageProc) { data = fProcs.fImageProc(const_cast<SkImage*>(image), fProcs.fImageCtx); } if (!data) { data = image->encodeToData(); } this->writeDataAsByteArray(data.get()); if (flags & SkWriteBufferImageFlags::kHasMipmap) { this->writeDataAsByteArray(mips->serialize().get()); } } void SkBinaryWriteBuffer::writeTypeface(SkTypeface* obj) { // Write 32 bits (signed) // 0 -- default font // >0 -- index // <0 -- custom (serial procs) if (obj == nullptr) { fWriter.write32(0); } else if (fProcs.fTypefaceProc) { auto data = fProcs.fTypefaceProc(obj, fProcs.fTypefaceCtx); if (data) { size_t size = data->size(); if (!SkTFitsIn<int32_t>(size)) { size = 0; // fall back to default font } int32_t ssize = SkToS32(size); fWriter.write32(-ssize); // negative to signal custom if (size) { this->writePad32(data->data(), size); } return; } // no data means fall through for std behavior } fWriter.write32(fTFSet ? fTFSet->add(obj) : 0); } void SkBinaryWriteBuffer::writePaint(const SkPaint& paint) { SkPaintPriv::Flatten(paint, *this); } void SkBinaryWriteBuffer::setFactoryRecorder(sk_sp<SkFactorySet> rec) { fFactorySet = std::move(rec); } void SkBinaryWriteBuffer::setTypefaceRecorder(sk_sp<SkRefCntSet> rec) { fTFSet = std::move(rec); } void SkBinaryWriteBuffer::writeFlattenable(const SkFlattenable* flattenable) { if (nullptr == flattenable) { this->write32(0); return; } /* * We can write 1 of 2 versions of the flattenable: * 1. index into fFactorySet : This assumes the writer will later * resolve the function-ptrs into strings for its reader. SkPicture * does exactly this, by writing a table of names (matching the indices) * up front in its serialized form. * 2. string name of the flattenable or index into fFlattenableDict: We * store the string to allow the reader to specify its own factories * after write time. In order to improve compression, if we have * already written the string, we write its index instead. */ if (fFactorySet) { SkFlattenable::Factory factory = flattenable->getFactory(); SkASSERT(factory); this->write32(fFactorySet->add(factory)); } else { const char* name = flattenable->getTypeName(); SkASSERT(name); SkASSERT(0 != strcmp("", name)); if (uint32_t* indexPtr = fFlattenableDict.find(name)) { // We will write the index as a 32-bit int. We want the first byte // that we send to be zero - this will act as a sentinel that we // have an index (not a string). This means that we will send the // the index shifted left by 8. The remaining 24-bits should be // plenty to store the index. Note that this strategy depends on // being little endian, and type names being non-empty. SkASSERT(0 == *indexPtr >> 24); this->write32(*indexPtr << 8); } else { this->writeString(name); fFlattenableDict.set(name, fFlattenableDict.count() + 1); } } // make room for the size of the flattened object (void)fWriter.reserve(sizeof(uint32_t)); // record the current size, so we can subtract after the object writes. size_t offset = fWriter.bytesWritten(); // now flatten the object flattenable->flatten(*this); size_t objSize = fWriter.bytesWritten() - offset; // record the obj's size fWriter.overwriteTAt(offset - sizeof(uint32_t), SkToU32(objSize)); } <commit_msg>Fix SKP serialization when SK_DISABLE_EFFECT_SERIALIZATION is defined<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/core/SkWriteBuffer.h" #include "include/core/SkBitmap.h" #include "include/core/SkData.h" #include "include/core/SkM44.h" #include "include/core/SkStream.h" #include "include/core/SkTypeface.h" #include "include/private/SkTo.h" #include "src/core/SkImagePriv.h" #include "src/core/SkMatrixPriv.h" #include "src/core/SkPaintPriv.h" #include "src/core/SkPtrRecorder.h" /////////////////////////////////////////////////////////////////////////////////////////////////// SkBinaryWriteBuffer::SkBinaryWriteBuffer() : fFactorySet(nullptr) , fTFSet(nullptr) { } SkBinaryWriteBuffer::SkBinaryWriteBuffer(void* storage, size_t storageSize) : fFactorySet(nullptr) , fTFSet(nullptr) , fWriter(storage, storageSize) {} SkBinaryWriteBuffer::~SkBinaryWriteBuffer() {} bool SkBinaryWriteBuffer::usingInitialStorage() const { return fWriter.usingInitialStorage(); } void SkBinaryWriteBuffer::writeByteArray(const void* data, size_t size) { fWriter.write32(SkToU32(size)); fWriter.writePad(data, size); } void SkBinaryWriteBuffer::writeBool(bool value) { fWriter.writeBool(value); } void SkBinaryWriteBuffer::writeScalar(SkScalar value) { fWriter.writeScalar(value); } void SkBinaryWriteBuffer::writeScalarArray(const SkScalar* value, uint32_t count) { fWriter.write32(count); fWriter.write(value, count * sizeof(SkScalar)); } void SkBinaryWriteBuffer::writeInt(int32_t value) { fWriter.write32(value); } void SkBinaryWriteBuffer::writeIntArray(const int32_t* value, uint32_t count) { fWriter.write32(count); fWriter.write(value, count * sizeof(int32_t)); } void SkBinaryWriteBuffer::writeUInt(uint32_t value) { fWriter.write32(value); } void SkBinaryWriteBuffer::writeString(const char* value) { fWriter.writeString(value); } void SkBinaryWriteBuffer::writeColor(SkColor color) { fWriter.write32(color); } void SkBinaryWriteBuffer::writeColorArray(const SkColor* color, uint32_t count) { fWriter.write32(count); fWriter.write(color, count * sizeof(SkColor)); } void SkBinaryWriteBuffer::writeColor4f(const SkColor4f& color) { fWriter.write(&color, sizeof(SkColor4f)); } void SkBinaryWriteBuffer::writeColor4fArray(const SkColor4f* color, uint32_t count) { fWriter.write32(count); fWriter.write(color, count * sizeof(SkColor4f)); } void SkBinaryWriteBuffer::writePoint(const SkPoint& point) { fWriter.writeScalar(point.fX); fWriter.writeScalar(point.fY); } void SkBinaryWriteBuffer::writePoint3(const SkPoint3& point) { this->writePad32(&point, sizeof(SkPoint3)); } void SkBinaryWriteBuffer::writePointArray(const SkPoint* point, uint32_t count) { fWriter.write32(count); fWriter.write(point, count * sizeof(SkPoint)); } void SkBinaryWriteBuffer::write(const SkM44& matrix) { fWriter.write(SkMatrixPriv::M44ColMajor(matrix), sizeof(float) * 16); } void SkBinaryWriteBuffer::writeMatrix(const SkMatrix& matrix) { fWriter.writeMatrix(matrix); } void SkBinaryWriteBuffer::writeIRect(const SkIRect& rect) { fWriter.write(&rect, sizeof(SkIRect)); } void SkBinaryWriteBuffer::writeRect(const SkRect& rect) { fWriter.writeRect(rect); } void SkBinaryWriteBuffer::writeRegion(const SkRegion& region) { fWriter.writeRegion(region); } void SkBinaryWriteBuffer::writePath(const SkPath& path) { fWriter.writePath(path); } size_t SkBinaryWriteBuffer::writeStream(SkStream* stream, size_t length) { fWriter.write32(SkToU32(length)); size_t bytesWritten = fWriter.readFromStream(stream, length); if (bytesWritten < length) { fWriter.reservePad(length - bytesWritten); } return bytesWritten; } bool SkBinaryWriteBuffer::writeToStream(SkWStream* stream) const { return fWriter.writeToStream(stream); } #include "src/image/SkImage_Base.h" /* Format: * flags: U32 * encoded : size_32 + data[] * [subset: IRect] * [mips] : size_32 + data[] */ void SkBinaryWriteBuffer::writeImage(const SkImage* image) { uint32_t flags = 0; const SkMipmap* mips = as_IB(image)->onPeekMips(); if (mips) { flags |= SkWriteBufferImageFlags::kHasMipmap; } this->write32(flags); sk_sp<SkData> data; if (fProcs.fImageProc) { data = fProcs.fImageProc(const_cast<SkImage*>(image), fProcs.fImageCtx); } if (!data) { data = image->encodeToData(); } this->writeDataAsByteArray(data.get()); if (flags & SkWriteBufferImageFlags::kHasMipmap) { this->writeDataAsByteArray(mips->serialize().get()); } } void SkBinaryWriteBuffer::writeTypeface(SkTypeface* obj) { // Write 32 bits (signed) // 0 -- default font // >0 -- index // <0 -- custom (serial procs) if (obj == nullptr) { fWriter.write32(0); } else if (fProcs.fTypefaceProc) { auto data = fProcs.fTypefaceProc(obj, fProcs.fTypefaceCtx); if (data) { size_t size = data->size(); if (!SkTFitsIn<int32_t>(size)) { size = 0; // fall back to default font } int32_t ssize = SkToS32(size); fWriter.write32(-ssize); // negative to signal custom if (size) { this->writePad32(data->data(), size); } return; } // no data means fall through for std behavior } fWriter.write32(fTFSet ? fTFSet->add(obj) : 0); } void SkBinaryWriteBuffer::writePaint(const SkPaint& paint) { SkPaintPriv::Flatten(paint, *this); } void SkBinaryWriteBuffer::setFactoryRecorder(sk_sp<SkFactorySet> rec) { fFactorySet = std::move(rec); } void SkBinaryWriteBuffer::setTypefaceRecorder(sk_sp<SkRefCntSet> rec) { fTFSet = std::move(rec); } void SkBinaryWriteBuffer::writeFlattenable(const SkFlattenable* flattenable) { if (nullptr == flattenable) { this->write32(0); return; } /* * We can write 1 of 2 versions of the flattenable: * * 1. index into fFactorySet: This assumes the writer will later resolve the function-ptrs * into strings for its reader. SkPicture does exactly this, by writing a table of names * (matching the indices) up front in its serialized form. * * 2. string name of the flattenable or index into fFlattenableDict: We store the string to * allow the reader to specify its own factories after write time. In order to improve * compression, if we have already written the string, we write its index instead. */ if (SkFlattenable::Factory factory = flattenable->getFactory(); factory && fFactorySet) { this->write32(fFactorySet->add(factory)); } else { const char* name = flattenable->getTypeName(); SkASSERT(name); SkASSERT(0 != strcmp("", name)); if (uint32_t* indexPtr = fFlattenableDict.find(name)) { // We will write the index as a 32-bit int. We want the first byte // that we send to be zero - this will act as a sentinel that we // have an index (not a string). This means that we will send the // the index shifted left by 8. The remaining 24-bits should be // plenty to store the index. Note that this strategy depends on // being little endian, and type names being non-empty. SkASSERT(0 == *indexPtr >> 24); this->write32(*indexPtr << 8); } else { this->writeString(name); fFlattenableDict.set(name, fFlattenableDict.count() + 1); } } // make room for the size of the flattened object (void)fWriter.reserve(sizeof(uint32_t)); // record the current size, so we can subtract after the object writes. size_t offset = fWriter.bytesWritten(); // now flatten the object flattenable->flatten(*this); size_t objSize = fWriter.bytesWritten() - offset; // record the obj's size fWriter.overwriteTAt(offset - sizeof(uint32_t), SkToU32(objSize)); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "TFile.h" void readandtest (const std::string & fname) { TFile* inputFile = new TFile(fname.c_str(),"READ"); inputFile->Print(); inputFile->Close(); } # ifndef __CINT__ int main(int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " rootfilename " << std::endl; return 1; } readandtest(argv[1]); return 0; } # endif <commit_msg>basic calls<commit_after>#include <iostream> #include <string> #include "TFile.h" #include "TNtuple.h" void readandtest (const std::string & fname) { TFile* inputFile = new TFile(fname.c_str(),"READ"); std::cout << "Print file info: " << std::endl; inputFile->Print(); std::cout << std::endl; std::cout << "List file TTree: " << std::endl; inputFile->ls(); std::cout << std::endl; std::cout << "Print TkStubs info: " << std::endl; TTree* t1 = (TTree*) inputFile->Get("TkStubs"); t1->Print(); std::cout << std::endl; inputFile->Close(); } # ifndef __CINT__ int main(int argc, char ** argv) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " rootfilename " << std::endl; return 1; } readandtest(argv[1]); return 0; } # endif <|endoftext|>
<commit_before><commit_msg>Fix DICOM import: Series sorting<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: bmkmenu.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2005-01-21 09:50:54 $ * * 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): _______________________________________ * * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <limits.h> #include "classes/bmkmenu.hxx" #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_ #include <macros/debug/assertion.hxx> #endif #ifndef __FRAMEWORK_HELPER_IMAGEPRODUCER_HXX_ #include <helper/imageproducer.hxx> #endif #ifndef __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_ #include <classes/menuconfiguration.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_UTIL_URL_HPP_ #include <com/sun/star/util/URL.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _UNOTOOLS_PROCESSFACTORY_HXX #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_ #include <com/sun/star/util/DateTime.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _CONFIG_HXX #include <tools/config.hxx> #endif #include <vcl/svapp.hxx> #include <svtools/dynamicmenuoptions.hxx> #ifndef INCLUDED_SVTOOLS_MENUOPTIONS_HXX #include <svtools/menuoptions.hxx> #endif #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ using namespace ::rtl; using namespace ::comphelper; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::beans; namespace framework { void GetMenuEntry( Sequence< PropertyValue >& aDynamicMenuEntry, ::rtl::OUString& rTitle, ::rtl::OUString& rURL, ::rtl::OUString& rFrame, ::rtl::OUString& rImageId ); class BmkMenu_Impl { private: static USHORT m_nMID; public: BmkMenu* m_pRoot; BOOL m_bInitialized; BmkMenu_Impl( BmkMenu* pRoot ); BmkMenu_Impl(); ~BmkMenu_Impl(); static USHORT GetMID(); }; USHORT BmkMenu_Impl::m_nMID = BMKMENU_ITEMID_START; BmkMenu_Impl::BmkMenu_Impl( BmkMenu* pRoot ) : m_pRoot(pRoot), m_bInitialized(FALSE) { } BmkMenu_Impl::BmkMenu_Impl() : m_pRoot(0), m_bInitialized(FALSE) { } BmkMenu_Impl::~BmkMenu_Impl() { } USHORT BmkMenu_Impl::GetMID() { m_nMID++; if( !m_nMID ) m_nMID = BMKMENU_ITEMID_START; return m_nMID; } // ------------------------------------------------------------------------ BmkMenu::BmkMenu( Reference< XFrame >& xFrame, BmkMenu::BmkMenuType nType, BmkMenu* pRoot ) : m_xFrame( xFrame ), m_nType( nType ) { _pImp = new BmkMenu_Impl( pRoot ); Initialize(); } BmkMenu::BmkMenu( Reference< XFrame >& xFrame, BmkMenu::BmkMenuType nType ) : m_nType( nType ), m_xFrame( xFrame ) { _pImp = new BmkMenu_Impl(); Initialize(); } BmkMenu::~BmkMenu() { delete _pImp; for ( int i = 0; i < GetItemCount(); i++ ) { if ( GetItemType( i ) != MENUITEM_SEPARATOR ) { // delete user attributes created with new! USHORT nId = GetItemId( i ); MenuConfiguration::Attributes* pUserAttributes = (MenuConfiguration::Attributes*)GetUserValue( nId ); delete pUserAttributes; } } } void BmkMenu::Initialize() { RTL_LOGFILE_CONTEXT( aLog, "framework (cd100003) ::BmkMenu::Initialize" ); if( _pImp->m_bInitialized ) return; _pImp->m_bInitialized = TRUE; Sequence< Sequence< PropertyValue > > aDynamicMenuEntries; if ( m_nType == BmkMenu::BMK_NEWMENU ) aDynamicMenuEntries = SvtDynamicMenuOptions().GetMenu( E_NEWMENU ); else if ( m_nType == BmkMenu::BMK_WIZARDMENU ) aDynamicMenuEntries = SvtDynamicMenuOptions().GetMenu( E_WIZARDMENU ); BOOL bShowMenuImages = SvtMenuOptions().IsMenuIconsEnabled(); ::rtl::OUString aTitle; ::rtl::OUString aURL; ::rtl::OUString aTargetFrame; ::rtl::OUString aImageId; const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings(); BOOL bIsHiContrastMode = rSettings.GetMenuColor().IsDark(); UINT32 i, nCount = aDynamicMenuEntries.getLength(); for ( i = 0; i < nCount; ++i ) { GetMenuEntry( aDynamicMenuEntries[i], aTitle, aURL, aTargetFrame, aImageId ); if ( !aTitle.getLength() && !aURL.getLength() ) continue; if ( aURL == ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:separator" ))) InsertSeparator(); else { sal_Bool bImageSet = sal_False; USHORT nId = CreateMenuId(); if ( bShowMenuImages ) { if ( aImageId.getLength() > 0 ) { Image aImage = GetImageFromURL( m_xFrame, aImageId, FALSE, bIsHiContrastMode ); if ( !!aImage ) { bImageSet = sal_True; InsertItem( nId, aTitle, aImage ); } } if ( !bImageSet ) { Image aImage = GetImageFromURL( m_xFrame, aURL, FALSE, bIsHiContrastMode ); if ( !aImage ) InsertItem( nId, aTitle ); else InsertItem( nId, aTitle, aImage ); } } else InsertItem( nId, aTitle ); // Store values from configuration to the New and Wizard menu entries to enable // sfx2 based code to support high contrast mode correctly! MenuConfiguration::Attributes* pUserAttributes = new MenuConfiguration::Attributes( aTargetFrame, aImageId ); SetUserValue( nId, (ULONG)pUserAttributes ); SetItemCommand( nId, aURL ); } } } USHORT BmkMenu::CreateMenuId() { return BmkMenu_Impl::GetMID(); } void GetMenuEntry ( Sequence< PropertyValue >& aDynamicMenuEntry, ::rtl::OUString& rTitle, ::rtl::OUString& rURL, ::rtl::OUString& rFrame, ::rtl::OUString& rImageId ) { for ( int i = 0; i < aDynamicMenuEntry.getLength(); i++ ) { if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_URL ) aDynamicMenuEntry[i].Value >>= rURL; else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_TITLE ) aDynamicMenuEntry[i].Value >>= rTitle; else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_IMAGEIDENTIFIER ) aDynamicMenuEntry[i].Value >>= rImageId; else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_TARGETNAME ) aDynamicMenuEntry[i].Value >>= rFrame; } } } <commit_msg>INTEGRATION: CWS ooo19126 (1.12.158); FILE MERGED 2005/09/05 13:06:03 rt 1.12.158.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bmkmenu.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2005-09-09 01:08:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #include <limits.h> #include "classes/bmkmenu.hxx" #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif #ifndef __FRAMEWORK_MACROS_DEBUG_ASSERTION_HXX_ #include <macros/debug/assertion.hxx> #endif #ifndef __FRAMEWORK_HELPER_IMAGEPRODUCER_HXX_ #include <helper/imageproducer.hxx> #endif #ifndef __FRAMEWORK_CLASSES_MENUCONFIGURATION_HXX_ #include <classes/menuconfiguration.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_UTIL_URL_HPP_ #include <com/sun/star/util/URL.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _UNOTOOLS_PROCESSFACTORY_HXX #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_ #include <com/sun/star/util/DateTime.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _CONFIG_HXX #include <tools/config.hxx> #endif #include <vcl/svapp.hxx> #include <svtools/dynamicmenuoptions.hxx> #ifndef INCLUDED_SVTOOLS_MENUOPTIONS_HXX #include <svtools/menuoptions.hxx> #endif #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif //_________________________________________________________________________________________________________________ // namespace //_________________________________________________________________________________________________________________ using namespace ::rtl; using namespace ::comphelper; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::beans; namespace framework { void GetMenuEntry( Sequence< PropertyValue >& aDynamicMenuEntry, ::rtl::OUString& rTitle, ::rtl::OUString& rURL, ::rtl::OUString& rFrame, ::rtl::OUString& rImageId ); class BmkMenu_Impl { private: static USHORT m_nMID; public: BmkMenu* m_pRoot; BOOL m_bInitialized; BmkMenu_Impl( BmkMenu* pRoot ); BmkMenu_Impl(); ~BmkMenu_Impl(); static USHORT GetMID(); }; USHORT BmkMenu_Impl::m_nMID = BMKMENU_ITEMID_START; BmkMenu_Impl::BmkMenu_Impl( BmkMenu* pRoot ) : m_pRoot(pRoot), m_bInitialized(FALSE) { } BmkMenu_Impl::BmkMenu_Impl() : m_pRoot(0), m_bInitialized(FALSE) { } BmkMenu_Impl::~BmkMenu_Impl() { } USHORT BmkMenu_Impl::GetMID() { m_nMID++; if( !m_nMID ) m_nMID = BMKMENU_ITEMID_START; return m_nMID; } // ------------------------------------------------------------------------ BmkMenu::BmkMenu( Reference< XFrame >& xFrame, BmkMenu::BmkMenuType nType, BmkMenu* pRoot ) : m_xFrame( xFrame ), m_nType( nType ) { _pImp = new BmkMenu_Impl( pRoot ); Initialize(); } BmkMenu::BmkMenu( Reference< XFrame >& xFrame, BmkMenu::BmkMenuType nType ) : m_nType( nType ), m_xFrame( xFrame ) { _pImp = new BmkMenu_Impl(); Initialize(); } BmkMenu::~BmkMenu() { delete _pImp; for ( int i = 0; i < GetItemCount(); i++ ) { if ( GetItemType( i ) != MENUITEM_SEPARATOR ) { // delete user attributes created with new! USHORT nId = GetItemId( i ); MenuConfiguration::Attributes* pUserAttributes = (MenuConfiguration::Attributes*)GetUserValue( nId ); delete pUserAttributes; } } } void BmkMenu::Initialize() { RTL_LOGFILE_CONTEXT( aLog, "framework (cd100003) ::BmkMenu::Initialize" ); if( _pImp->m_bInitialized ) return; _pImp->m_bInitialized = TRUE; Sequence< Sequence< PropertyValue > > aDynamicMenuEntries; if ( m_nType == BmkMenu::BMK_NEWMENU ) aDynamicMenuEntries = SvtDynamicMenuOptions().GetMenu( E_NEWMENU ); else if ( m_nType == BmkMenu::BMK_WIZARDMENU ) aDynamicMenuEntries = SvtDynamicMenuOptions().GetMenu( E_WIZARDMENU ); BOOL bShowMenuImages = SvtMenuOptions().IsMenuIconsEnabled(); ::rtl::OUString aTitle; ::rtl::OUString aURL; ::rtl::OUString aTargetFrame; ::rtl::OUString aImageId; const StyleSettings& rSettings = Application::GetSettings().GetStyleSettings(); BOOL bIsHiContrastMode = rSettings.GetMenuColor().IsDark(); UINT32 i, nCount = aDynamicMenuEntries.getLength(); for ( i = 0; i < nCount; ++i ) { GetMenuEntry( aDynamicMenuEntries[i], aTitle, aURL, aTargetFrame, aImageId ); if ( !aTitle.getLength() && !aURL.getLength() ) continue; if ( aURL == ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:separator" ))) InsertSeparator(); else { sal_Bool bImageSet = sal_False; USHORT nId = CreateMenuId(); if ( bShowMenuImages ) { if ( aImageId.getLength() > 0 ) { Image aImage = GetImageFromURL( m_xFrame, aImageId, FALSE, bIsHiContrastMode ); if ( !!aImage ) { bImageSet = sal_True; InsertItem( nId, aTitle, aImage ); } } if ( !bImageSet ) { Image aImage = GetImageFromURL( m_xFrame, aURL, FALSE, bIsHiContrastMode ); if ( !aImage ) InsertItem( nId, aTitle ); else InsertItem( nId, aTitle, aImage ); } } else InsertItem( nId, aTitle ); // Store values from configuration to the New and Wizard menu entries to enable // sfx2 based code to support high contrast mode correctly! MenuConfiguration::Attributes* pUserAttributes = new MenuConfiguration::Attributes( aTargetFrame, aImageId ); SetUserValue( nId, (ULONG)pUserAttributes ); SetItemCommand( nId, aURL ); } } } USHORT BmkMenu::CreateMenuId() { return BmkMenu_Impl::GetMID(); } void GetMenuEntry ( Sequence< PropertyValue >& aDynamicMenuEntry, ::rtl::OUString& rTitle, ::rtl::OUString& rURL, ::rtl::OUString& rFrame, ::rtl::OUString& rImageId ) { for ( int i = 0; i < aDynamicMenuEntry.getLength(); i++ ) { if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_URL ) aDynamicMenuEntry[i].Value >>= rURL; else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_TITLE ) aDynamicMenuEntry[i].Value >>= rTitle; else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_IMAGEIDENTIFIER ) aDynamicMenuEntry[i].Value >>= rImageId; else if ( aDynamicMenuEntry[i].Name == DYNAMICMENU_PROPERTYNAME_TARGETNAME ) aDynamicMenuEntry[i].Value >>= rFrame; } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSuperquadricSource.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* vtkSuperquadric originally written by Michael Halle, Brigham and Women's Hospital, July 1998. Based on "Rigid physically based superquadrics", A. H. Barr, in "Graphics Gems III", David Kirk, ed., Academic Press, 1992. */ #include "vtkSuperquadricSource.h" #include "vtkCellArray.h" #include "vtkFloatArray.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include <math.h> vtkStandardNewMacro(vtkSuperquadricSource); static void evalSuperquadric(double u, double v, double du, double dv, double e, double n, double dims[3], double alpha, double xyz[3], double nrm[3]); // Description: vtkSuperquadricSource::vtkSuperquadricSource(int res) { res = res < 4 ? 4 : res; this->AxisOfSymmetry = 2; //z-axis symmetry this->Toroidal = 0; this->Thickness = 0.3333; this->PhiRoundness = 0.0; this->SetPhiRoundness(1.0); this->ThetaRoundness = 0.0; this->SetThetaRoundness(1.0); this->Center[0] = this->Center[1] = this->Center[2] = 0.0; this->Scale[0] = this->Scale[1] = this->Scale[2] = 1.0; this->Size = .5; this->ThetaResolution = 0; this->SetThetaResolution(res); this->PhiResolution = 0; this->SetPhiResolution(res); this->SetNumberOfInputPorts(0); } void vtkSuperquadricSource::SetPhiResolution(int i) { if(i < 4) { i = 4; } i = (i+3)/4*4; // make it divisible by 4 if(i > VTK_MAX_SUPERQUADRIC_RESOLUTION) { i = VTK_MAX_SUPERQUADRIC_RESOLUTION; } if (this->PhiResolution != i) { this->PhiResolution = i; this->Modified (); } } void vtkSuperquadricSource::SetThetaResolution(int i) { if(i < 8) { i = 8; } i = (i+7)/8*8; // make it divisible by 8 if(i > VTK_MAX_SUPERQUADRIC_RESOLUTION) { i = VTK_MAX_SUPERQUADRIC_RESOLUTION; } if (this->ThetaResolution != i) { this->ThetaResolution = i; this->Modified (); } } void vtkSuperquadricSource::SetThetaRoundness(double e) { if(e < VTK_MIN_SUPERQUADRIC_ROUNDNESS) { e = VTK_MIN_SUPERQUADRIC_ROUNDNESS; } if (this->ThetaRoundness != e) { this->ThetaRoundness = e; this->Modified(); } } void vtkSuperquadricSource::SetPhiRoundness(double e) { if(e < VTK_MIN_SUPERQUADRIC_ROUNDNESS) { e = VTK_MIN_SUPERQUADRIC_ROUNDNESS; } if (this->PhiRoundness != e) { this->PhiRoundness = e; this->Modified(); } } static const double SQ_SMALL_OFFSET = 0.01; int vtkSuperquadricSource::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); int i, j; vtkIdType numPts; vtkPoints *newPoints; vtkFloatArray *newNormals; vtkFloatArray *newTCoords; vtkCellArray *newPolys; vtkIdType *ptidx; double pt[3], nv[3], dims[3]; double len; double alpha; double deltaPhi, deltaTheta, phi, theta; double phiLim[2], thetaLim[2]; double deltaPhiTex, deltaThetaTex; int base, pbase; vtkIdType numStrips; int ptsPerStrip; int phiSubsegs, thetaSubsegs, phiSegs, thetaSegs; int iq, jq, rowOffset; double thetaOffset, phiOffset; double texCoord[2]; double tmp; dims[0] = this->Scale[0] * this->Size; dims[1] = this->Scale[1] * this->Size; dims[2] = this->Scale[2] * this->Size; if(this->Toroidal) { phiLim[0] = -vtkMath::Pi(); phiLim[1] = vtkMath::Pi(); thetaLim[0] = -vtkMath::Pi(); thetaLim[1] = vtkMath::Pi(); alpha = (1.0 / this->Thickness); dims[0] /= (alpha + 1.0); dims[1] /= (alpha + 1.0); dims[2] /= (alpha + 1.0); } else { //Ellipsoidal phiLim[0] = -vtkMath::Pi() / 2.0; phiLim[1] = vtkMath::Pi() / 2.0; thetaLim[0] = -vtkMath::Pi(); thetaLim[1] = vtkMath::Pi(); alpha = 0.0; } deltaPhi = (phiLim[1] - phiLim[0]) / this->PhiResolution; deltaPhiTex = 1.0 / this->PhiResolution; deltaTheta = (thetaLim[1] - thetaLim[0]) / this->ThetaResolution; deltaThetaTex = 1.0 / this->ThetaResolution; phiSegs = 4; thetaSegs = 8; phiSubsegs = this->PhiResolution / phiSegs; thetaSubsegs = this->ThetaResolution / thetaSegs; numPts = (this->PhiResolution + phiSegs)*(this->ThetaResolution + thetaSegs); // creating triangles numStrips = this->PhiResolution * thetaSegs; ptsPerStrip = thetaSubsegs*2 + 2; // // Set things up; allocate memory // newPoints = vtkPoints::New(); newPoints->Allocate(numPts); newNormals = vtkFloatArray::New(); newNormals->SetNumberOfComponents(3); newNormals->Allocate(3*numPts); newNormals->SetName("Normals"); newTCoords = vtkFloatArray::New(); newTCoords->SetNumberOfComponents(2); newTCoords->Allocate(2*numPts); newTCoords->SetName("TextureCoords"); newPolys = vtkCellArray::New(); newPolys->Allocate(newPolys->EstimateSize(numStrips,ptsPerStrip)); // generate! for(iq = 0; iq < phiSegs; iq++) { for(i = 0; i <= phiSubsegs; i++) { phi = phiLim[0] + deltaPhi*(i + iq*phiSubsegs); texCoord[1] = deltaPhiTex*(i + iq*phiSubsegs); // SQ_SMALL_OFFSET makes sure that the normal vector isn't // evaluated exactly on a crease; if that were to happen, // large shading errors can occur. if(i == 0) { phiOffset = SQ_SMALL_OFFSET*deltaPhi; } else if (i == phiSubsegs) { phiOffset = -SQ_SMALL_OFFSET*deltaPhi; } else { phiOffset = 0.0; } for(jq = 0; jq < thetaSegs; jq++) { for(j = 0; j <= thetaSubsegs; j++) { theta = thetaLim[0] + deltaTheta*(j + jq*thetaSubsegs); texCoord[0] = deltaThetaTex*(j + jq*thetaSubsegs); if(j == 0) { thetaOffset = SQ_SMALL_OFFSET*deltaTheta; } else if (j == thetaSubsegs) { thetaOffset = -SQ_SMALL_OFFSET*deltaTheta; } else { thetaOffset = 0.0; } // This gives a superquadric with axis of symmetry: z evalSuperquadric(theta, phi, thetaOffset, phiOffset, this->ThetaRoundness, this->PhiRoundness, dims, alpha, pt, nv); switch (this->AxisOfSymmetry) { case 0: // x-axis tmp = pt[0]; pt[0] = pt[2]; pt[2] = tmp; pt[1] = -pt[1]; tmp = nv[0]; nv[0] = nv[2]; nv[2] = tmp; nv[1] = -nv[1]; break; case 1: //y-axis //PENDING break; } if((len = vtkMath::Norm(nv)) == 0.0) { len = 1.0; } nv[0] /= len; nv[1] /= len; nv[2] /= len; if(!this->Toroidal && ((iq == 0 && i == 0) || (iq == (phiSegs-1) && i == phiSubsegs))) { // we're at a pole: // make sure the pole is at the same location for all evals // (the superquadric evaluation is numerically unstable // at the poles) switch (this->AxisOfSymmetry) { case 0: // x-axis pt[1] = pt[2] = 0.0; break; case 2: // z-axis pt[0] = pt[1] = 0.0; break; } } pt[0] += this->Center[0]; pt[1] += this->Center[1]; pt[2] += this->Center[2]; newPoints->InsertNextPoint(pt); newNormals->InsertNextTuple(nv); newTCoords->InsertNextTuple(texCoord); } } } } // mesh! // build triangle strips for efficiency.... ptidx = new vtkIdType[ptsPerStrip]; rowOffset = this->ThetaResolution+thetaSegs; for(iq = 0; iq < phiSegs; iq++) { for(i = 0; i < phiSubsegs; i++) { pbase = rowOffset*(i +iq*(phiSubsegs+1)); for(jq = 0; jq < thetaSegs; jq++) { base = pbase + jq*(thetaSubsegs+1); for(j = 0; j <= thetaSubsegs; j++) { ptidx[2*j] = base + rowOffset + j; ptidx[2*j+1] = base + j; } newPolys->InsertNextCell(ptsPerStrip, ptidx); } } } delete[] ptidx; output->SetPoints(newPoints); newPoints->Delete(); output->GetPointData()->SetNormals(newNormals); newNormals->Delete(); output->GetPointData()->SetTCoords(newTCoords); newTCoords->Delete(); output->SetStrips(newPolys); newPolys->Delete(); return 1; } void vtkSuperquadricSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Toroidal: " << (this->Toroidal ? "On\n" : "Off\n"); os << indent << "Axis Of Symmetry: " << this->AxisOfSymmetry << "\n"; os << indent << "Size: " << this->Size << "\n"; os << indent << "Thickness: " << this->Thickness << "\n"; os << indent << "Theta Resolution: " << this->ThetaResolution << "\n"; os << indent << "Theta Roundness: " << this->ThetaRoundness << "\n"; os << indent << "Phi Resolution: " << this->PhiResolution << "\n"; os << indent << "Phi Roundness: " << this->PhiRoundness << "\n"; os << indent << "Center: (" << this->Center[0] << ", " << this->Center[1] << ", " << this->Center[2] << ")\n"; os << indent << "Scale: (" << this->Scale[0] << ", " << this->Scale[1] << ", " << this->Scale[2] << ")\n"; } static double cf(double w, double m, double a = 0) { double c; double sgn; if (w == vtkMath::Pi() || w == -vtkMath::Pi()) { c = -1.0; } else { c = cos(w); } sgn = c < 0.0 ? -1.0 : 1.0; return a + sgn*pow(sgn*c, m); } static double sf(double w, double m) { double s; double sgn; if (w == vtkMath::Pi() || w == -vtkMath::Pi()) { s = 0.0; } else { s = sin(w); } sgn = s < 0.0 ? -1.0 : 1.0; return sgn*pow(sgn*s, m); } static void evalSuperquadric(double theta, double phi, // parametric coords double dtheta, double dphi, // offsets for normals double rtheta, double rphi, // roundness params double dims[3], // x, y, z dimensions double alpha, // hole size double xyz[3], // output coords double nrm[3]) // output normals { // axis of symmetry: z double cf1, cf2; cf1 = cf(phi, rphi, alpha); xyz[0] = dims[0] * cf1 * cf(theta, rtheta); xyz[1] = dims[1] * cf1 * sf(theta, rtheta); xyz[2] = dims[2] * sf(phi, rphi); cf2 = cf(phi+dphi, 2.0-rphi); nrm[0] = 1.0/dims[0] * cf2 * cf(theta+dtheta, 2.0-rtheta); nrm[1] = 1.0/dims[1] * cf2 * sf(theta+dtheta, 2.0-rtheta); nrm[2] = 1.0/dims[2] * sf(phi+dphi, 2.0-rphi); } <commit_msg>Revert "Revert "ENH: Provide code for aligned of axis along the global y-axis.""<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSuperquadricSource.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* vtkSuperquadric originally written by Michael Halle, Brigham and Women's Hospital, July 1998. Based on "Rigid physically based superquadrics", A. H. Barr, in "Graphics Gems III", David Kirk, ed., Academic Press, 1992. */ #include "vtkSuperquadricSource.h" #include "vtkCellArray.h" #include "vtkFloatArray.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include <math.h> vtkStandardNewMacro(vtkSuperquadricSource); static void evalSuperquadric(double u, double v, double du, double dv, double e, double n, double dims[3], double alpha, double xyz[3], double nrm[3]); // Description: vtkSuperquadricSource::vtkSuperquadricSource(int res) { res = res < 4 ? 4 : res; this->AxisOfSymmetry = 2; //z-axis symmetry this->Toroidal = 0; this->Thickness = 0.3333; this->PhiRoundness = 0.0; this->SetPhiRoundness(1.0); this->ThetaRoundness = 0.0; this->SetThetaRoundness(1.0); this->Center[0] = this->Center[1] = this->Center[2] = 0.0; this->Scale[0] = this->Scale[1] = this->Scale[2] = 1.0; this->Size = .5; this->ThetaResolution = 0; this->SetThetaResolution(res); this->PhiResolution = 0; this->SetPhiResolution(res); this->SetNumberOfInputPorts(0); } void vtkSuperquadricSource::SetPhiResolution(int i) { if(i < 4) { i = 4; } i = (i+3)/4*4; // make it divisible by 4 if(i > VTK_MAX_SUPERQUADRIC_RESOLUTION) { i = VTK_MAX_SUPERQUADRIC_RESOLUTION; } if (this->PhiResolution != i) { this->PhiResolution = i; this->Modified (); } } void vtkSuperquadricSource::SetThetaResolution(int i) { if(i < 8) { i = 8; } i = (i+7)/8*8; // make it divisible by 8 if(i > VTK_MAX_SUPERQUADRIC_RESOLUTION) { i = VTK_MAX_SUPERQUADRIC_RESOLUTION; } if (this->ThetaResolution != i) { this->ThetaResolution = i; this->Modified (); } } void vtkSuperquadricSource::SetThetaRoundness(double e) { if(e < VTK_MIN_SUPERQUADRIC_ROUNDNESS) { e = VTK_MIN_SUPERQUADRIC_ROUNDNESS; } if (this->ThetaRoundness != e) { this->ThetaRoundness = e; this->Modified(); } } void vtkSuperquadricSource::SetPhiRoundness(double e) { if(e < VTK_MIN_SUPERQUADRIC_ROUNDNESS) { e = VTK_MIN_SUPERQUADRIC_ROUNDNESS; } if (this->PhiRoundness != e) { this->PhiRoundness = e; this->Modified(); } } static const double SQ_SMALL_OFFSET = 0.01; int vtkSuperquadricSource::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); int i, j; vtkIdType numPts; vtkPoints *newPoints; vtkFloatArray *newNormals; vtkFloatArray *newTCoords; vtkCellArray *newPolys; vtkIdType *ptidx; double pt[3], nv[3], dims[3]; double len; double alpha; double deltaPhi, deltaTheta, phi, theta; double phiLim[2], thetaLim[2]; double deltaPhiTex, deltaThetaTex; int base, pbase; vtkIdType numStrips; int ptsPerStrip; int phiSubsegs, thetaSubsegs, phiSegs, thetaSegs; int iq, jq, rowOffset; double thetaOffset, phiOffset; double texCoord[2]; double tmp; dims[0] = this->Scale[0] * this->Size; dims[1] = this->Scale[1] * this->Size; dims[2] = this->Scale[2] * this->Size; if(this->Toroidal) { phiLim[0] = -vtkMath::Pi(); phiLim[1] = vtkMath::Pi(); thetaLim[0] = -vtkMath::Pi(); thetaLim[1] = vtkMath::Pi(); alpha = (1.0 / this->Thickness); dims[0] /= (alpha + 1.0); dims[1] /= (alpha + 1.0); dims[2] /= (alpha + 1.0); } else { //Ellipsoidal phiLim[0] = -vtkMath::Pi() / 2.0; phiLim[1] = vtkMath::Pi() / 2.0; thetaLim[0] = -vtkMath::Pi(); thetaLim[1] = vtkMath::Pi(); alpha = 0.0; } deltaPhi = (phiLim[1] - phiLim[0]) / this->PhiResolution; deltaPhiTex = 1.0 / this->PhiResolution; deltaTheta = (thetaLim[1] - thetaLim[0]) / this->ThetaResolution; deltaThetaTex = 1.0 / this->ThetaResolution; phiSegs = 4; thetaSegs = 8; phiSubsegs = this->PhiResolution / phiSegs; thetaSubsegs = this->ThetaResolution / thetaSegs; numPts = (this->PhiResolution + phiSegs)*(this->ThetaResolution + thetaSegs); // creating triangles numStrips = this->PhiResolution * thetaSegs; ptsPerStrip = thetaSubsegs*2 + 2; // // Set things up; allocate memory // newPoints = vtkPoints::New(); newPoints->Allocate(numPts); newNormals = vtkFloatArray::New(); newNormals->SetNumberOfComponents(3); newNormals->Allocate(3*numPts); newNormals->SetName("Normals"); newTCoords = vtkFloatArray::New(); newTCoords->SetNumberOfComponents(2); newTCoords->Allocate(2*numPts); newTCoords->SetName("TextureCoords"); newPolys = vtkCellArray::New(); newPolys->Allocate(newPolys->EstimateSize(numStrips,ptsPerStrip)); // generate! for(iq = 0; iq < phiSegs; iq++) { for(i = 0; i <= phiSubsegs; i++) { phi = phiLim[0] + deltaPhi*(i + iq*phiSubsegs); texCoord[1] = deltaPhiTex*(i + iq*phiSubsegs); // SQ_SMALL_OFFSET makes sure that the normal vector isn't // evaluated exactly on a crease; if that were to happen, // large shading errors can occur. if(i == 0) { phiOffset = SQ_SMALL_OFFSET*deltaPhi; } else if (i == phiSubsegs) { phiOffset = -SQ_SMALL_OFFSET*deltaPhi; } else { phiOffset = 0.0; } for(jq = 0; jq < thetaSegs; jq++) { for(j = 0; j <= thetaSubsegs; j++) { theta = thetaLim[0] + deltaTheta*(j + jq*thetaSubsegs); texCoord[0] = deltaThetaTex*(j + jq*thetaSubsegs); if(j == 0) { thetaOffset = SQ_SMALL_OFFSET*deltaTheta; } else if (j == thetaSubsegs) { thetaOffset = -SQ_SMALL_OFFSET*deltaTheta; } else { thetaOffset = 0.0; } // This gives a superquadric with axis of symmetry: z evalSuperquadric(theta, phi, thetaOffset, phiOffset, this->ThetaRoundness, this->PhiRoundness, dims, alpha, pt, nv); switch (this->AxisOfSymmetry) { case 0: // x-axis tmp = pt[0]; pt[0] = pt[2]; pt[2] = tmp; pt[1] = -pt[1]; tmp = nv[0]; nv[0] = nv[2]; nv[2] = tmp; nv[1] = -nv[1]; break; case 1: // y-axis tmp = pt[1]; pt[1] = pt[2]; pt[2] = tmp; pt[0] = -pt[0]; tmp = nv[1]; nv[1] = nv[2]; nv[2] = tmp; nv[0] = -nv[0]; break; } if((len = vtkMath::Norm(nv)) == 0.0) { len = 1.0; } nv[0] /= len; nv[1] /= len; nv[2] /= len; if(!this->Toroidal && ((iq == 0 && i == 0) || (iq == (phiSegs-1) && i == phiSubsegs))) { // we're at a pole: // make sure the pole is at the same location for all evals // (the superquadric evaluation is numerically unstable // at the poles) switch (this->AxisOfSymmetry) { case 0: // x-axis pt[1] = pt[2] = 0.0; break; case 1: // y-axis pt[0] = pt[2] = 0.0; break; case 2: // z-axis pt[0] = pt[1] = 0.0; break; } } pt[0] += this->Center[0]; pt[1] += this->Center[1]; pt[2] += this->Center[2]; newPoints->InsertNextPoint(pt); newNormals->InsertNextTuple(nv); newTCoords->InsertNextTuple(texCoord); } } } } // mesh! // build triangle strips for efficiency.... ptidx = new vtkIdType[ptsPerStrip]; rowOffset = this->ThetaResolution+thetaSegs; for(iq = 0; iq < phiSegs; iq++) { for(i = 0; i < phiSubsegs; i++) { pbase = rowOffset*(i +iq*(phiSubsegs+1)); for(jq = 0; jq < thetaSegs; jq++) { base = pbase + jq*(thetaSubsegs+1); for(j = 0; j <= thetaSubsegs; j++) { ptidx[2*j] = base + rowOffset + j; ptidx[2*j+1] = base + j; } newPolys->InsertNextCell(ptsPerStrip, ptidx); } } } delete[] ptidx; output->SetPoints(newPoints); newPoints->Delete(); output->GetPointData()->SetNormals(newNormals); newNormals->Delete(); output->GetPointData()->SetTCoords(newTCoords); newTCoords->Delete(); output->SetStrips(newPolys); newPolys->Delete(); return 1; } void vtkSuperquadricSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Toroidal: " << (this->Toroidal ? "On\n" : "Off\n"); os << indent << "Axis Of Symmetry: " << this->AxisOfSymmetry << "\n"; os << indent << "Size: " << this->Size << "\n"; os << indent << "Thickness: " << this->Thickness << "\n"; os << indent << "Theta Resolution: " << this->ThetaResolution << "\n"; os << indent << "Theta Roundness: " << this->ThetaRoundness << "\n"; os << indent << "Phi Resolution: " << this->PhiResolution << "\n"; os << indent << "Phi Roundness: " << this->PhiRoundness << "\n"; os << indent << "Center: (" << this->Center[0] << ", " << this->Center[1] << ", " << this->Center[2] << ")\n"; os << indent << "Scale: (" << this->Scale[0] << ", " << this->Scale[1] << ", " << this->Scale[2] << ")\n"; } static double cf(double w, double m, double a = 0) { double c; double sgn; if (w == vtkMath::Pi() || w == -vtkMath::Pi()) { c = -1.0; } else { c = cos(w); } sgn = c < 0.0 ? -1.0 : 1.0; return a + sgn*pow(sgn*c, m); } static double sf(double w, double m) { double s; double sgn; if (w == vtkMath::Pi() || w == -vtkMath::Pi()) { s = 0.0; } else { s = sin(w); } sgn = s < 0.0 ? -1.0 : 1.0; return sgn*pow(sgn*s, m); } static void evalSuperquadric(double theta, double phi, // parametric coords double dtheta, double dphi, // offsets for normals double rtheta, double rphi, // roundness params double dims[3], // x, y, z dimensions double alpha, // hole size double xyz[3], // output coords double nrm[3]) // output normals { // axis of symmetry: z double cf1, cf2; cf1 = cf(phi, rphi, alpha); xyz[0] = dims[0] * cf1 * cf(theta, rtheta); xyz[1] = dims[1] * cf1 * sf(theta, rtheta); xyz[2] = dims[2] * sf(phi, rphi); cf2 = cf(phi+dphi, 2.0-rphi); nrm[0] = 1.0/dims[0] * cf2 * cf(theta+dtheta, 2.0-rtheta); nrm[1] = 1.0/dims[1] * cf2 * sf(theta+dtheta, 2.0-rtheta); nrm[2] = 1.0/dims[2] * sf(phi+dphi, 2.0-rphi); } <|endoftext|>
<commit_before>/** * Touhou Community Reliant Automatic Patcher * Main DLL * * ---- * * Breakpoints for contiguous files. */ #include "thcrap.h" #include <map> #define POST_JSON_SIZE(fr) (fr)->pre_json_size + (fr)->patch_size int file_rep_init(file_rep_t *fr, const char *file_name) { size_t fn_len; if (fr->name) { file_rep_clear(fr); } fn_len = strlen(file_name) + 1; fr->name = EnsureUTF8(file_name, fn_len); fr->rep_buffer = stack_game_file_resolve(fr->name, &fr->pre_json_size); fr->offset = -1; fr->hooks = patchhooks_build(fr->name); if (fr->hooks) { size_t diff_fn_len = strlen(fr->name) + strlen(".jdiff") + 1; size_t diff_size = 0; VLA(char, diff_fn, diff_fn_len); strcpy(diff_fn, fr->name); strcat(diff_fn, ".jdiff"); fr->patch = stack_game_json_resolve(diff_fn, &diff_size); VLA_FREE(diff_fn); fr->patch_size += diff_size; } return 1; } static int file_rep_hooks_run(file_rep_t *fr) { return patchhooks_run( fr->hooks, fr->game_buffer, POST_JSON_SIZE(fr), fr->pre_json_size, fr->name, fr->patch ); } int file_rep_clear(file_rep_t *fr) { if(!fr) { return -1; } SAFE_FREE(fr->rep_buffer); fr->patch = json_decref_safe(fr->patch); fr->hooks = json_decref_safe(fr->hooks); fr->patch_size = 0; fr->pre_json_size = 0; fr->offset = -1; fr->orig_size = 0; fr->object = NULL; SAFE_FREE(fr->name); return 0; } /// Thread-local storage /// -------------------- THREAD_LOCAL(file_rep_t, fr_tls, NULL, file_rep_clear); THREAD_LOCAL(file_rep_t*, fr_ptr_tls, NULL, NULL); /// -------------------- /// Replace a file loaded entirely in memory /// ---------------------------------------- int BP_file_name(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); // Parameters // ---------- char **file_name = (char**)json_object_get_register(bp_info, regs, "file_name"); // ---------- if(!file_name) { return 1; } file_rep_init(fr, *file_name); return 1; } int BP_file_size(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); // Parameters // ---------- size_t *file_size = json_object_get_register(bp_info, regs, "file_size"); // ---------- // Other breakpoints // ----------------- BP_file_name(regs, bp_info); // ----------------- // th08 and th09 use their file size variable as the loop counter for LZSS // decompression. Putting anything other than the original file size from // the archive there (by writing to that variable) will result in a few // bytes of corruption at the end of the decompressed file. // Therefore, these games need the POST_JSON_SIZE to be unconditionally // written out to registers three separate times. // However, we *do* check whether we have a file name. If we don't, we // can't possibly have resolved a replacement file that would give us a // custom file size. // This allows this breakpoint to be placed in front of memory allocation // calls that are used for more than just replaceable files, without // affecting unrelated memory allocations. if(file_size && fr->name) { if(!fr->pre_json_size) { fr->pre_json_size = *file_size; } *file_size = POST_JSON_SIZE(fr); } return 1; } int BP_file_buffer(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); // Parameters // ---------- BYTE **file_buffer = (BYTE**)json_object_get_register(bp_info, regs, "file_buffer"); // ---------- if(file_buffer) { fr->game_buffer = *file_buffer; } return 1; } int BP_file_load(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); // Parameters // ---------- size_t *file_buffer_addr_copy = json_object_get_register(bp_info, regs, "file_buffer_addr_copy"); size_t stack_clear_size = json_object_get_hex(bp_info, "stack_clear_size"); size_t eip_jump_dist = json_object_get_hex(bp_info, "eip_jump_dist"); // ---------- // Other breakpoints // ----------------- BP_file_buffer(regs, bp_info); // ----------------- if(!fr->game_buffer || !fr->rep_buffer || !fr->pre_json_size) { return 1; } // Let's do it memcpy(fr->game_buffer, fr->rep_buffer, fr->pre_json_size); file_rep_hooks_run(fr); if(eip_jump_dist) { regs->retaddr += eip_jump_dist; } if(file_buffer_addr_copy) { *file_buffer_addr_copy = (size_t)fr->game_buffer; } if(stack_clear_size) { regs->esp += stack_clear_size; } file_rep_clear(fr); return 0; } // Cool function name. int DumpDatFile(const char *dir, const file_rep_t *fr) { if(!fr || !fr->game_buffer || !fr->name) { return -1; } if(!dir) { dir = "dat"; } { size_t fn_len = strlen(dir) + 1 + strlen(fr->name) + 1; VLA(char, fn, fn_len); sprintf(fn, "%s/%s", dir, fr->name); if(!PathFileExists(fn)) { file_write(fn, fr->game_buffer, fr->pre_json_size); } VLA_FREE(fn); } return 0; } // DumpDatFile, fragmented loading style. int DumpDatFragmentedFile(const char *dir, file_rep_t *fr, HANDLE hFile, fragmented_read_file_hook_t post_read) { if (!fr || !hFile || hFile == INVALID_HANDLE_VALUE || !fr->name || fr->offset != -1) { return -1; } if (!dir) { dir = "dat"; } { size_t fn_len = strlen(dir) + 1 + strlen(fr->name) + 1; VLA(char, fn, fn_len); sprintf(fn, "%s/%s", dir, fr->name); if (!PathFileExists(fn)) { // Read the file DWORD nbOfBytesRead; BYTE* buffer = (BYTE*)malloc(fr->orig_size); ReadFile(hFile, buffer, fr->orig_size, &nbOfBytesRead, NULL); SetFilePointer(hFile, -(LONG)nbOfBytesRead, NULL, FILE_CURRENT); if (post_read) { fr->offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT); // Needed by nsml post_read(fr, buffer, fr->orig_size); fr->offset = -1; } file_write(fn, buffer, fr->orig_size); } VLA_FREE(fn); } return 0; } int BP_file_loaded(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); json_t *dat_dump; // Other breakpoints // ----------------- BP_file_buffer(regs, bp_info); // ----------------- if(!fr->game_buffer) { return 1; } dat_dump = json_object_get(run_cfg, "dat_dump"); if(!json_is_false(dat_dump)) { DumpDatFile(json_string_value(dat_dump), fr); } file_rep_hooks_run(fr); file_rep_clear(fr); return 1; } /// Replace a file loaded by fragments /// ---------------------------------- // For these files, we need to know the full file size beforehand. // So we need a breakpoint in the file header. std::map<std::string, file_rep_t> files_list; file_rep_t *file_rep_get(const char *filename) { auto it = files_list.find(filename); if (it != files_list.end()) { return &it->second; } else { return nullptr; } } int BP_file_header(x86_reg_t *regs, json_t *bp_info) { // Parameters // ---------- const char *filename = (const char*)json_object_get_immediate(bp_info, regs, "file_name"); size_t *size = json_object_get_pointer(bp_info, regs, "file_size"); // ---------- if (!filename || !size) return 1; file_rep_t *fr = file_rep_get(filename); if (fr == nullptr) { fr = &files_list[filename]; memset(fr, 0, sizeof(file_rep_t)); file_rep_clear(fr); } file_rep_init(fr, filename); json_t *dat_dump = json_object_get(run_cfg, "dat_dump"); if (fr->rep_buffer != NULL || fr->patch != NULL || fr->hooks != NULL || !json_is_false(dat_dump)) { fr->orig_size = *size; *size = max(*size, fr->pre_json_size) + fr->patch_size; } else { file_rep_clear(fr); } return 1; } int BP_fragmented_read_file(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = *fr_ptr_tls_get(); // Parameters // ---------- const char *filename = (const char*)json_object_get_immediate(bp_info, regs, "file_name"); int apply = json_boolean_value(json_object_get(bp_info, "apply")); // Stack // ---------- HANDLE hFile = ((HANDLE*) regs->esp)[1]; LPBYTE lpBuffer = ((LPBYTE*) regs->esp)[2]; DWORD nNumberOfBytesToRead = ((DWORD*) regs->esp)[3]; LPDWORD lpNumberOfBytesRead = ((LPDWORD*) regs->esp)[4]; LPOVERLAPPED lpOverlapped = ((LPOVERLAPPED*)regs->esp)[5]; // ---------- if (filename) { fr = file_rep_get(filename); *fr_ptr_tls_get() = fr; } if (!apply || !fr || !fr->name) { return 1; } json_t *dat_dump = json_object_get(run_cfg, "dat_dump"); if (!json_is_false(dat_dump)) { DumpDatFragmentedFile(json_string_value(dat_dump), fr, hFile, (fragmented_read_file_hook_t)json_object_get_immediate(bp_info, regs, "post_read")); } if (!fr->rep_buffer && !fr->patch && !fr->hooks) { return 1; } if (lpOverlapped) { // Overlapped operations are not supported. // We'd better leave that file alone rather than ignoring that. return 1; } bool has_rep = fr->rep_buffer != nullptr; if (fr->offset == -1) { fr->offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT); // Read the original file if we don't have a replacement one if (!fr->rep_buffer) { DWORD nbOfBytesRead; fr->rep_buffer = malloc(fr->orig_size + fr->patch_size); fr->pre_json_size = fr->orig_size; ReadFile(hFile, fr->rep_buffer, fr->orig_size, &nbOfBytesRead, NULL); SetFilePointer(hFile, fr->offset, NULL, FILE_BEGIN); fragmented_read_file_hook_t post_read = (fragmented_read_file_hook_t)json_object_get_immediate(bp_info, regs, "post_read"); if (post_read) { post_read(fr, (BYTE*)fr->rep_buffer, fr->orig_size); } } // Patch the game if (patchhooks_run(fr->hooks, fr->rep_buffer, POST_JSON_SIZE(fr), fr->orig_size, fr->name, fr->patch)) { has_rep = 1; } fragmented_read_file_hook_t post_patch = (fragmented_read_file_hook_t)json_object_get_immediate(bp_info, regs, "post_patch"); if (post_patch) { post_patch(fr, (BYTE*)fr->rep_buffer, POST_JSON_SIZE(fr)); } // If we didn't change the file in any way, we can free the rep buffer. if (!has_rep) { SAFE_FREE(fr->rep_buffer); } } if (!fr->rep_buffer) { return 1; } log_printf("Patching %s\n", fr->name); DWORD offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - fr->offset; if (offset <= POST_JSON_SIZE(fr)) { *lpNumberOfBytesRead = min(POST_JSON_SIZE(fr) - offset, nNumberOfBytesToRead); } else { *lpNumberOfBytesRead = 0; } memcpy(lpBuffer, (BYTE*)fr->rep_buffer + offset, *lpNumberOfBytesRead); SetFilePointer(hFile, *lpNumberOfBytesRead, NULL, FILE_CURRENT); if (offset + *lpNumberOfBytesRead == POST_JSON_SIZE(fr)) { *fr_ptr_tls_get() = nullptr; } regs->eax = 1; regs->esp += 5 * sizeof(DWORD); return 0; } <commit_msg>File breakpoints: Clear the game_buffer pointer in file_rep_clear().<commit_after>/** * Touhou Community Reliant Automatic Patcher * Main DLL * * ---- * * Breakpoints for contiguous files. */ #include "thcrap.h" #include <map> #define POST_JSON_SIZE(fr) (fr)->pre_json_size + (fr)->patch_size int file_rep_init(file_rep_t *fr, const char *file_name) { size_t fn_len; if (fr->name) { file_rep_clear(fr); } fn_len = strlen(file_name) + 1; fr->name = EnsureUTF8(file_name, fn_len); fr->rep_buffer = stack_game_file_resolve(fr->name, &fr->pre_json_size); fr->offset = -1; fr->hooks = patchhooks_build(fr->name); if (fr->hooks) { size_t diff_fn_len = strlen(fr->name) + strlen(".jdiff") + 1; size_t diff_size = 0; VLA(char, diff_fn, diff_fn_len); strcpy(diff_fn, fr->name); strcat(diff_fn, ".jdiff"); fr->patch = stack_game_json_resolve(diff_fn, &diff_size); VLA_FREE(diff_fn); fr->patch_size += diff_size; } return 1; } static int file_rep_hooks_run(file_rep_t *fr) { return patchhooks_run( fr->hooks, fr->game_buffer, POST_JSON_SIZE(fr), fr->pre_json_size, fr->name, fr->patch ); } int file_rep_clear(file_rep_t *fr) { if(!fr) { return -1; } SAFE_FREE(fr->rep_buffer); fr->game_buffer = nullptr; fr->patch = json_decref_safe(fr->patch); fr->hooks = json_decref_safe(fr->hooks); fr->patch_size = 0; fr->pre_json_size = 0; fr->offset = -1; fr->orig_size = 0; fr->object = NULL; SAFE_FREE(fr->name); return 0; } /// Thread-local storage /// -------------------- THREAD_LOCAL(file_rep_t, fr_tls, NULL, file_rep_clear); THREAD_LOCAL(file_rep_t*, fr_ptr_tls, NULL, NULL); /// -------------------- /// Replace a file loaded entirely in memory /// ---------------------------------------- int BP_file_name(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); // Parameters // ---------- char **file_name = (char**)json_object_get_register(bp_info, regs, "file_name"); // ---------- if(!file_name) { return 1; } file_rep_init(fr, *file_name); return 1; } int BP_file_size(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); // Parameters // ---------- size_t *file_size = json_object_get_register(bp_info, regs, "file_size"); // ---------- // Other breakpoints // ----------------- BP_file_name(regs, bp_info); // ----------------- // th08 and th09 use their file size variable as the loop counter for LZSS // decompression. Putting anything other than the original file size from // the archive there (by writing to that variable) will result in a few // bytes of corruption at the end of the decompressed file. // Therefore, these games need the POST_JSON_SIZE to be unconditionally // written out to registers three separate times. // However, we *do* check whether we have a file name. If we don't, we // can't possibly have resolved a replacement file that would give us a // custom file size. // This allows this breakpoint to be placed in front of memory allocation // calls that are used for more than just replaceable files, without // affecting unrelated memory allocations. if(file_size && fr->name) { if(!fr->pre_json_size) { fr->pre_json_size = *file_size; } *file_size = POST_JSON_SIZE(fr); } return 1; } int BP_file_buffer(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); // Parameters // ---------- BYTE **file_buffer = (BYTE**)json_object_get_register(bp_info, regs, "file_buffer"); // ---------- if(file_buffer) { fr->game_buffer = *file_buffer; } return 1; } int BP_file_load(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); // Parameters // ---------- size_t *file_buffer_addr_copy = json_object_get_register(bp_info, regs, "file_buffer_addr_copy"); size_t stack_clear_size = json_object_get_hex(bp_info, "stack_clear_size"); size_t eip_jump_dist = json_object_get_hex(bp_info, "eip_jump_dist"); // ---------- // Other breakpoints // ----------------- BP_file_buffer(regs, bp_info); // ----------------- if(!fr->game_buffer || !fr->rep_buffer || !fr->pre_json_size) { return 1; } // Let's do it memcpy(fr->game_buffer, fr->rep_buffer, fr->pre_json_size); file_rep_hooks_run(fr); if(eip_jump_dist) { regs->retaddr += eip_jump_dist; } if(file_buffer_addr_copy) { *file_buffer_addr_copy = (size_t)fr->game_buffer; } if(stack_clear_size) { regs->esp += stack_clear_size; } file_rep_clear(fr); return 0; } // Cool function name. int DumpDatFile(const char *dir, const file_rep_t *fr) { if(!fr || !fr->game_buffer || !fr->name) { return -1; } if(!dir) { dir = "dat"; } { size_t fn_len = strlen(dir) + 1 + strlen(fr->name) + 1; VLA(char, fn, fn_len); sprintf(fn, "%s/%s", dir, fr->name); if(!PathFileExists(fn)) { file_write(fn, fr->game_buffer, fr->pre_json_size); } VLA_FREE(fn); } return 0; } // DumpDatFile, fragmented loading style. int DumpDatFragmentedFile(const char *dir, file_rep_t *fr, HANDLE hFile, fragmented_read_file_hook_t post_read) { if (!fr || !hFile || hFile == INVALID_HANDLE_VALUE || !fr->name || fr->offset != -1) { return -1; } if (!dir) { dir = "dat"; } { size_t fn_len = strlen(dir) + 1 + strlen(fr->name) + 1; VLA(char, fn, fn_len); sprintf(fn, "%s/%s", dir, fr->name); if (!PathFileExists(fn)) { // Read the file DWORD nbOfBytesRead; BYTE* buffer = (BYTE*)malloc(fr->orig_size); ReadFile(hFile, buffer, fr->orig_size, &nbOfBytesRead, NULL); SetFilePointer(hFile, -(LONG)nbOfBytesRead, NULL, FILE_CURRENT); if (post_read) { fr->offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT); // Needed by nsml post_read(fr, buffer, fr->orig_size); fr->offset = -1; } file_write(fn, buffer, fr->orig_size); } VLA_FREE(fn); } return 0; } int BP_file_loaded(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = fr_tls_get(); json_t *dat_dump; // Other breakpoints // ----------------- BP_file_buffer(regs, bp_info); // ----------------- if(!fr->game_buffer) { return 1; } dat_dump = json_object_get(run_cfg, "dat_dump"); if(!json_is_false(dat_dump)) { DumpDatFile(json_string_value(dat_dump), fr); } file_rep_hooks_run(fr); file_rep_clear(fr); return 1; } /// Replace a file loaded by fragments /// ---------------------------------- // For these files, we need to know the full file size beforehand. // So we need a breakpoint in the file header. std::map<std::string, file_rep_t> files_list; file_rep_t *file_rep_get(const char *filename) { auto it = files_list.find(filename); if (it != files_list.end()) { return &it->second; } else { return nullptr; } } int BP_file_header(x86_reg_t *regs, json_t *bp_info) { // Parameters // ---------- const char *filename = (const char*)json_object_get_immediate(bp_info, regs, "file_name"); size_t *size = json_object_get_pointer(bp_info, regs, "file_size"); // ---------- if (!filename || !size) return 1; file_rep_t *fr = file_rep_get(filename); if (fr == nullptr) { fr = &files_list[filename]; memset(fr, 0, sizeof(file_rep_t)); file_rep_clear(fr); } file_rep_init(fr, filename); json_t *dat_dump = json_object_get(run_cfg, "dat_dump"); if (fr->rep_buffer != NULL || fr->patch != NULL || fr->hooks != NULL || !json_is_false(dat_dump)) { fr->orig_size = *size; *size = max(*size, fr->pre_json_size) + fr->patch_size; } else { file_rep_clear(fr); } return 1; } int BP_fragmented_read_file(x86_reg_t *regs, json_t *bp_info) { file_rep_t *fr = *fr_ptr_tls_get(); // Parameters // ---------- const char *filename = (const char*)json_object_get_immediate(bp_info, regs, "file_name"); int apply = json_boolean_value(json_object_get(bp_info, "apply")); // Stack // ---------- HANDLE hFile = ((HANDLE*) regs->esp)[1]; LPBYTE lpBuffer = ((LPBYTE*) regs->esp)[2]; DWORD nNumberOfBytesToRead = ((DWORD*) regs->esp)[3]; LPDWORD lpNumberOfBytesRead = ((LPDWORD*) regs->esp)[4]; LPOVERLAPPED lpOverlapped = ((LPOVERLAPPED*)regs->esp)[5]; // ---------- if (filename) { fr = file_rep_get(filename); *fr_ptr_tls_get() = fr; } if (!apply || !fr || !fr->name) { return 1; } json_t *dat_dump = json_object_get(run_cfg, "dat_dump"); if (!json_is_false(dat_dump)) { DumpDatFragmentedFile(json_string_value(dat_dump), fr, hFile, (fragmented_read_file_hook_t)json_object_get_immediate(bp_info, regs, "post_read")); } if (!fr->rep_buffer && !fr->patch && !fr->hooks) { return 1; } if (lpOverlapped) { // Overlapped operations are not supported. // We'd better leave that file alone rather than ignoring that. return 1; } bool has_rep = fr->rep_buffer != nullptr; if (fr->offset == -1) { fr->offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT); // Read the original file if we don't have a replacement one if (!fr->rep_buffer) { DWORD nbOfBytesRead; fr->rep_buffer = malloc(fr->orig_size + fr->patch_size); fr->pre_json_size = fr->orig_size; ReadFile(hFile, fr->rep_buffer, fr->orig_size, &nbOfBytesRead, NULL); SetFilePointer(hFile, fr->offset, NULL, FILE_BEGIN); fragmented_read_file_hook_t post_read = (fragmented_read_file_hook_t)json_object_get_immediate(bp_info, regs, "post_read"); if (post_read) { post_read(fr, (BYTE*)fr->rep_buffer, fr->orig_size); } } // Patch the game if (patchhooks_run(fr->hooks, fr->rep_buffer, POST_JSON_SIZE(fr), fr->orig_size, fr->name, fr->patch)) { has_rep = 1; } fragmented_read_file_hook_t post_patch = (fragmented_read_file_hook_t)json_object_get_immediate(bp_info, regs, "post_patch"); if (post_patch) { post_patch(fr, (BYTE*)fr->rep_buffer, POST_JSON_SIZE(fr)); } // If we didn't change the file in any way, we can free the rep buffer. if (!has_rep) { SAFE_FREE(fr->rep_buffer); } } if (!fr->rep_buffer) { return 1; } log_printf("Patching %s\n", fr->name); DWORD offset = SetFilePointer(hFile, 0, NULL, FILE_CURRENT) - fr->offset; if (offset <= POST_JSON_SIZE(fr)) { *lpNumberOfBytesRead = min(POST_JSON_SIZE(fr) - offset, nNumberOfBytesToRead); } else { *lpNumberOfBytesRead = 0; } memcpy(lpBuffer, (BYTE*)fr->rep_buffer + offset, *lpNumberOfBytesRead); SetFilePointer(hFile, *lpNumberOfBytesRead, NULL, FILE_CURRENT); if (offset + *lpNumberOfBytesRead == POST_JSON_SIZE(fr)) { *fr_ptr_tls_get() = nullptr; } regs->eax = 1; regs->esp += 5 * sizeof(DWORD); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2015 The Brick Authors. #include "brick/window_util.h" #include <gtk/gtk.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include "include/internal/cef_linux.h" #include "include/base/cef_logging.h" #include "brick/brick_app.h" namespace { GList *default_icons = NULL; CefWindowHandle leader_window_; double device_scale_factor = 0; const double kCSSDefaultDPI = 96.0; int XErrorHandlerImpl(Display *display, XErrorEvent *event) { LOG(WARNING) << "X error received: " << "type " << event->type << ", " << "serial " << event->serial << ", " << "error_code " << static_cast<int>(event->error_code) << ", " << "request_code " << static_cast<int>(event->request_code) << ", " << "minor_code " << static_cast<int>(event->minor_code); return 0; } int XIOErrorHandlerImpl(Display *display) { return 0; } } // namespace namespace window_util { CefWindowHandle GetParent(CefWindowHandle handle) { ::Window root; ::Window parent; ::Window *children; unsigned int nchildren; XQueryTree(cef_get_xdisplay(), handle, &root, &parent, &children, &nchildren); XFree(children); return parent; } void Resize(CefWindowHandle handle, int width, int height) { XResizeWindow( cef_get_xdisplay(), handle, (unsigned int) width, (unsigned int) height ); } void SetMinSize(CefWindowHandle handle, int width, int height) { XSizeHints *size_hints = XAllocSizeHints(); if (!size_hints) { LOG(ERROR) << "SetMinSize: Can't allocate memory for XAllocSizeHints"; return; } size_hints->flags = PMinSize; size_hints->min_width = width; size_hints->min_height = height; XSetWMNormalHints( cef_get_xdisplay(), handle, size_hints ); XFree(size_hints); } void ConfigureAsDialog(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False); Atom value = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DIALOG", False); XChangeProperty(display, handle, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&value), 1); } void ConfigureAsTopmost(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False); Atom value = XInternAtom(display, "_NET_WM_WINDOW_TYPE_UTILITY", False); XChangeProperty(display, handle, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&value), 1); } void SetGroupByLeader(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); XWMHints base_hints; XWMHints * h = XGetWMHints(display, handle); if (!h) { h = &base_hints; h->flags = 0; } h->flags |= WindowGroupHint; h->window_group = leader_window_; XSetWMHints(display, handle, h); if(h != &base_hints) { XFree(h); } } void SetClientLeader(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "WM_CLIENT_LEADER", False); XChangeProperty(display, handle, type, XA_WINDOW, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&leader_window_), 1); SetGroupByLeader(handle); } void FixSize(CefWindowHandle handle, int width, int height) { XSizeHints *size_hints = XAllocSizeHints(); ::XDisplay *display = cef_get_xdisplay(); if (!size_hints) { LOG(ERROR) << "FixSize: Can't allocate memory for XAllocSizeHints"; return; } if (width && height) { size_hints->flags = PSize | PMinSize | PMaxSize; size_hints->width = width; size_hints->height = height; size_hints->min_width = width; size_hints->min_height = height; size_hints->max_width = width; size_hints->max_height = height; } else { size_hints->flags = PMinSize | PMaxSize; size_hints->max_width = width; size_hints->max_height = height; } XSetWMNormalHints( display, handle, size_hints ); XFree(size_hints); } void InitAsPopup(CefWindowHandle handle) { ConfigureAsDialog(handle); } void Hide(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XUnmapWindow(display, handle); } void Show(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XMapWindow(display, handle); } void CenterPosition(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XSizeHints *size_hints = XAllocSizeHints(); if (!size_hints) { LOG(ERROR) << "CenterPosition: Can't allocate memory for XAllocSizeHints"; return; } size_hints->flags = PWinGravity; size_hints->win_gravity = CenterGravity; XSetWMNormalHints( display, handle, size_hints ); XFree(size_hints); } void SetTitle(CefWindowHandle handle, std::string title) { std::string titleStr(title); // Retrieve the X11 display shared with Chromium. ::Display *display = cef_get_xdisplay(); DCHECK(display); DCHECK(handle != kNullWindowHandle); // Retrieve the atoms required by the below XChangeProperty call. const char *kAtoms[] = { "_NET_WM_NAME", "UTF8_STRING" }; Atom atoms[2]; int result = XInternAtoms(display, const_cast<char **>(kAtoms), 2, false, atoms); if (!result) NOTREACHED(); // Set the window title. XChangeProperty(display, handle, atoms[0], atoms[1], 8, PropModeReplace, reinterpret_cast<const unsigned char *>(titleStr.c_str()), titleStr.size()); // TODO(erg): This is technically wrong. So XStoreName and friends expect // this in Host Portable Character Encoding instead of UTF-8, which I believe // is Compound Text. This shouldn't matter 90% of the time since this is the // fallback to the UTF8 property above. XStoreName(display, handle, titleStr.c_str()); } void SetClassHints(CefWindowHandle handle, char *res_name, char *res_class) { XClassHint *class_hints = XAllocClassHint(); ::XDisplay *display = cef_get_xdisplay(); if (!class_hints) { LOG(ERROR) << "SetClassHints: Can't allocate memory for XAllocClassHint"; return; } class_hints->res_name = res_name; class_hints->res_class = res_class; XSetClassHint(display, handle, class_hints); XFree(class_hints); } void SetLeaderWindow(CefWindowHandle handle) { leader_window_ = handle; } CefWindowHandle GetLeaderWindow() { return leader_window_; } void InitHooks() { XSetErrorHandler(XErrorHandlerImpl); XSetIOErrorHandler(XIOErrorHandlerImpl); } void InitWindow(CefWindowHandle handle, bool is_leader) { if (is_leader) SetLeaderWindow(handle); else SetClientLeader(handle); SetClassHints(handle, const_cast<char *>(APP_COMMON_NAME), const_cast<char *>(APP_NAME)); } GList* GetDefaultIcons() { return default_icons; } void SetDefaultIcons(GList* icons) { if (default_icons) { g_list_foreach(default_icons, (GFunc) g_object_unref, NULL); g_list_free(default_icons); } default_icons = icons; gtk_window_set_default_icon_list(icons); } BrowserWindow* LookupBrowserWindow(CefWindowHandle native_window) { GdkWindow * gdk_window = GDK_WINDOW(gdk_xid_table_lookup(native_window)); return reinterpret_cast<BrowserWindow*>( g_object_get_data(G_OBJECT(gdk_window), "wrapper") ); } BrowserWindow* LookupBrowserWindow(GdkEvent* event) { if (event->type == GDK_NOTHING) { // GDK_NOTHING event doesn't have any windows return NULL; } GObject *object = G_OBJECT(event->any.window); if (!G_IS_OBJECT(object)) { LOG(ERROR) << "Try lookup browser window of bad native window" << ", event type: " << event->type << ", event window: " << event->any.window; return NULL; } return reinterpret_cast<BrowserWindow*>( g_object_get_data(object, "wrapper") ); } void FlushChanges() { ::XDisplay *display = cef_get_xdisplay(); XFlush(display); } CefRect GetDefaultScreenRect() { GdkRectangle monitor_rect; gdk_screen_get_monitor_geometry(gdk_screen_get_default(), 0, &monitor_rect); return CefRect( monitor_rect.x, monitor_rect.y, monitor_rect.width, monitor_rect.height ); } double GetDPI() { GtkSettings* gtk_settings = gtk_settings_get_default(); DCHECK(gtk_settings); gint gtk_dpi = -1; g_object_get(gtk_settings, "gtk-xft-dpi", &gtk_dpi, NULL); // GTK multiplies the DPI by 1024 before storing it. return (gtk_dpi > 0) ? gtk_dpi / 1024.0 : kCSSDefaultDPI; } double GetDeviceScaleFactor() { if (!device_scale_factor) device_scale_factor = floor((GetDPI() / kCSSDefaultDPI) * 100) / 100; return device_scale_factor; } } // namespace window_util <commit_msg>Topmost окошки не должны быть ни на таскбаре ни в pager'е<commit_after>// Copyright (c) 2015 The Brick Authors. #include "brick/window_util.h" #include <gtk/gtk.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include "include/internal/cef_linux.h" #include "include/base/cef_logging.h" #include "brick/brick_app.h" namespace { GList *default_icons = NULL; CefWindowHandle leader_window_; double device_scale_factor = 0; const double kCSSDefaultDPI = 96.0; int XErrorHandlerImpl(Display *display, XErrorEvent *event) { LOG(WARNING) << "X error received: " << "type " << event->type << ", " << "serial " << event->serial << ", " << "error_code " << static_cast<int>(event->error_code) << ", " << "request_code " << static_cast<int>(event->request_code) << ", " << "minor_code " << static_cast<int>(event->minor_code); return 0; } int XIOErrorHandlerImpl(Display *display) { return 0; } } // namespace namespace window_util { CefWindowHandle GetParent(CefWindowHandle handle) { ::Window root; ::Window parent; ::Window *children; unsigned int nchildren; XQueryTree(cef_get_xdisplay(), handle, &root, &parent, &children, &nchildren); XFree(children); return parent; } void Resize(CefWindowHandle handle, int width, int height) { XResizeWindow( cef_get_xdisplay(), handle, (unsigned int) width, (unsigned int) height ); } void SetMinSize(CefWindowHandle handle, int width, int height) { XSizeHints *size_hints = XAllocSizeHints(); if (!size_hints) { LOG(ERROR) << "SetMinSize: Can't allocate memory for XAllocSizeHints"; return; } size_hints->flags = PMinSize; size_hints->min_width = width; size_hints->min_height = height; XSetWMNormalHints( cef_get_xdisplay(), handle, size_hints ); XFree(size_hints); } void ConfigureAsDialog(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False); Atom value = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DIALOG", False); XChangeProperty(display, handle, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&value), 1); } void ConfigureAsTopmost(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False); Atom value = XInternAtom(display, "_NET_WM_WINDOW_TYPE_UTILITY", False); XChangeProperty(display, handle, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&value), 1); Atom state[2]; state[0] = XInternAtom(display, "_NET_WM_STATE_SKIP_TASKBAR", False); state[1] = XInternAtom(display, "_NET_WM_STATE_SKIP_PAGER", False); Atom wm_state = XInternAtom(display, "_NET_WM_STATE", False); XChangeProperty (display, handle, wm_state, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&state), 2); } void SetGroupByLeader(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); XWMHints base_hints; XWMHints * h = XGetWMHints(display, handle); if (!h) { h = &base_hints; h->flags = 0; } h->flags |= WindowGroupHint; h->window_group = leader_window_; XSetWMHints(display, handle, h); if(h != &base_hints) { XFree(h); } } void SetClientLeader(CefWindowHandle handle) { ::XDisplay *display = cef_get_xdisplay(); Atom type = XInternAtom(display, "WM_CLIENT_LEADER", False); XChangeProperty(display, handle, type, XA_WINDOW, 32, PropModeReplace, reinterpret_cast<unsigned char *>(&leader_window_), 1); SetGroupByLeader(handle); } void FixSize(CefWindowHandle handle, int width, int height) { XSizeHints *size_hints = XAllocSizeHints(); ::XDisplay *display = cef_get_xdisplay(); if (!size_hints) { LOG(ERROR) << "FixSize: Can't allocate memory for XAllocSizeHints"; return; } if (width && height) { size_hints->flags = PSize | PMinSize | PMaxSize; size_hints->width = width; size_hints->height = height; size_hints->min_width = width; size_hints->min_height = height; size_hints->max_width = width; size_hints->max_height = height; } else { size_hints->flags = PMinSize | PMaxSize; size_hints->max_width = width; size_hints->max_height = height; } XSetWMNormalHints( display, handle, size_hints ); XFree(size_hints); } void InitAsPopup(CefWindowHandle handle) { ConfigureAsDialog(handle); } void Hide(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XUnmapWindow(display, handle); } void Show(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XMapWindow(display, handle); } void CenterPosition(CefWindowHandle handle) { ::Display *display = cef_get_xdisplay(); DCHECK(display); XSizeHints *size_hints = XAllocSizeHints(); if (!size_hints) { LOG(ERROR) << "CenterPosition: Can't allocate memory for XAllocSizeHints"; return; } size_hints->flags = PWinGravity; size_hints->win_gravity = CenterGravity; XSetWMNormalHints( display, handle, size_hints ); XFree(size_hints); } void SetTitle(CefWindowHandle handle, std::string title) { std::string titleStr(title); // Retrieve the X11 display shared with Chromium. ::Display *display = cef_get_xdisplay(); DCHECK(display); DCHECK(handle != kNullWindowHandle); // Retrieve the atoms required by the below XChangeProperty call. const char *kAtoms[] = { "_NET_WM_NAME", "UTF8_STRING" }; Atom atoms[2]; int result = XInternAtoms(display, const_cast<char **>(kAtoms), 2, false, atoms); if (!result) NOTREACHED(); // Set the window title. XChangeProperty(display, handle, atoms[0], atoms[1], 8, PropModeReplace, reinterpret_cast<const unsigned char *>(titleStr.c_str()), titleStr.size()); // TODO(erg): This is technically wrong. So XStoreName and friends expect // this in Host Portable Character Encoding instead of UTF-8, which I believe // is Compound Text. This shouldn't matter 90% of the time since this is the // fallback to the UTF8 property above. XStoreName(display, handle, titleStr.c_str()); } void SetClassHints(CefWindowHandle handle, char *res_name, char *res_class) { XClassHint *class_hints = XAllocClassHint(); ::XDisplay *display = cef_get_xdisplay(); if (!class_hints) { LOG(ERROR) << "SetClassHints: Can't allocate memory for XAllocClassHint"; return; } class_hints->res_name = res_name; class_hints->res_class = res_class; XSetClassHint(display, handle, class_hints); XFree(class_hints); } void SetLeaderWindow(CefWindowHandle handle) { leader_window_ = handle; } CefWindowHandle GetLeaderWindow() { return leader_window_; } void InitHooks() { XSetErrorHandler(XErrorHandlerImpl); XSetIOErrorHandler(XIOErrorHandlerImpl); } void InitWindow(CefWindowHandle handle, bool is_leader) { if (is_leader) SetLeaderWindow(handle); else SetClientLeader(handle); SetClassHints(handle, const_cast<char *>(APP_COMMON_NAME), const_cast<char *>(APP_NAME)); } GList* GetDefaultIcons() { return default_icons; } void SetDefaultIcons(GList* icons) { if (default_icons) { g_list_foreach(default_icons, (GFunc) g_object_unref, NULL); g_list_free(default_icons); } default_icons = icons; gtk_window_set_default_icon_list(icons); } BrowserWindow* LookupBrowserWindow(CefWindowHandle native_window) { GdkWindow * gdk_window = GDK_WINDOW(gdk_xid_table_lookup(native_window)); return reinterpret_cast<BrowserWindow*>( g_object_get_data(G_OBJECT(gdk_window), "wrapper") ); } BrowserWindow* LookupBrowserWindow(GdkEvent* event) { if (event->type == GDK_NOTHING) { // GDK_NOTHING event doesn't have any windows return NULL; } GObject *object = G_OBJECT(event->any.window); if (!G_IS_OBJECT(object)) { LOG(ERROR) << "Try lookup browser window of bad native window" << ", event type: " << event->type << ", event window: " << event->any.window; return NULL; } return reinterpret_cast<BrowserWindow*>( g_object_get_data(object, "wrapper") ); } void FlushChanges() { ::XDisplay *display = cef_get_xdisplay(); XFlush(display); } CefRect GetDefaultScreenRect() { GdkRectangle monitor_rect; gdk_screen_get_monitor_geometry(gdk_screen_get_default(), 0, &monitor_rect); return CefRect( monitor_rect.x, monitor_rect.y, monitor_rect.width, monitor_rect.height ); } double GetDPI() { GtkSettings* gtk_settings = gtk_settings_get_default(); DCHECK(gtk_settings); gint gtk_dpi = -1; g_object_get(gtk_settings, "gtk-xft-dpi", &gtk_dpi, NULL); // GTK multiplies the DPI by 1024 before storing it. return (gtk_dpi > 0) ? gtk_dpi / 1024.0 : kCSSDefaultDPI; } double GetDeviceScaleFactor() { if (!device_scale_factor) device_scale_factor = floor((GetDPI() / kCSSDefaultDPI) * 100) / 100; return device_scale_factor; } } // namespace window_util <|endoftext|>
<commit_before>#include "chainerx/native/native_device.h" #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include "chainerx/device.h" #include "chainerx/macro.h" namespace chainerx { namespace native { std::shared_ptr<void> NativeDevice::Allocate(size_t bytesize) { if (bytesize == 0) { return std::shared_ptr<void>{nullptr}; } return std::shared_ptr<uint8_t>(new uint8_t[bytesize], std::default_delete<uint8_t[]>()); } void NativeDevice::MemoryCopyFrom(void* dst, const void* src, size_t bytesize, Device& src_device) { CHAINERX_ASSERT(nullptr != dynamic_cast<NativeDevice*>(&src_device) && "Native device only supports copy between native devices"); std::memcpy(dst, src, bytesize); } void NativeDevice::MemoryCopyTo(void* dst, const void* src, size_t bytesize, Device& dst_device) { CHAINERX_ASSERT(nullptr != dynamic_cast<NativeDevice*>(&dst_device) && "Native device only supports copy between native devices"); std::memcpy(dst, src, bytesize); } std::shared_ptr<void> NativeDevice::TransferDataFrom( Device& src_device, const std::shared_ptr<void>& src_ptr, size_t offset, size_t bytesize) { std::shared_ptr<void> dst_ptr = Allocate(bytesize); MemoryCopyFrom(dst_ptr.get(), &(static_cast<int8_t*>(src_ptr.get())[offset]), bytesize, src_device); return dst_ptr; } std::shared_ptr<void> NativeDevice::TransferDataTo( Device& dst_device, const std::shared_ptr<void>& src_ptr, size_t offset, size_t bytesize) { return dst_device.TransferDataFrom(*this, src_ptr, offset, bytesize); } std::shared_ptr<void> NativeDevice::FromHostMemory(const std::shared_ptr<void>& src_ptr, size_t bytesize) { (void)bytesize; // unused return src_ptr; } } // namespace native } // namespace chainerx <commit_msg>Modify to use brace initialization.<commit_after>#include "chainerx/native/native_device.h" #include <cstddef> #include <cstdint> #include <cstring> #include <memory> #include "chainerx/device.h" #include "chainerx/macro.h" namespace chainerx { namespace native { std::shared_ptr<void> NativeDevice::Allocate(size_t bytesize) { if (bytesize == 0) { return std::shared_ptr<void>{nullptr}; } return std::shared_ptr<uint8_t>{new uint8_t[bytesize], std::default_delete<uint8_t[]>()}; } void NativeDevice::MemoryCopyFrom(void* dst, const void* src, size_t bytesize, Device& src_device) { CHAINERX_ASSERT(nullptr != dynamic_cast<NativeDevice*>(&src_device) && "Native device only supports copy between native devices"); std::memcpy(dst, src, bytesize); } void NativeDevice::MemoryCopyTo(void* dst, const void* src, size_t bytesize, Device& dst_device) { CHAINERX_ASSERT(nullptr != dynamic_cast<NativeDevice*>(&dst_device) && "Native device only supports copy between native devices"); std::memcpy(dst, src, bytesize); } std::shared_ptr<void> NativeDevice::TransferDataFrom( Device& src_device, const std::shared_ptr<void>& src_ptr, size_t offset, size_t bytesize) { std::shared_ptr<void> dst_ptr = Allocate(bytesize); MemoryCopyFrom(dst_ptr.get(), &(static_cast<int8_t*>(src_ptr.get())[offset]), bytesize, src_device); return dst_ptr; } std::shared_ptr<void> NativeDevice::TransferDataTo( Device& dst_device, const std::shared_ptr<void>& src_ptr, size_t offset, size_t bytesize) { return dst_device.TransferDataFrom(*this, src_ptr, offset, bytesize); } std::shared_ptr<void> NativeDevice::FromHostMemory(const std::shared_ptr<void>& src_ptr, size_t bytesize) { (void)bytesize; // unused return src_ptr; } } // namespace native } // namespace chainerx <|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include "Memory.hpp" #include "registerAddr.hpp" Memory::Memory(void) {} Memory::~Memory(void) {} void Memory::reset(void) { memset(this->_m_wram, 0xFF, sizeof(_m_wram)); memset(this->_m_vram, 0xFF, sizeof(_m_vram)); memset(this->_m_oam, 0xFF, sizeof(_m_oam)); memset(this->_m_io, 0xFF, sizeof(_m_io)); memset(this->_m_zp, 0xFF, sizeof(_m_zp)); memset(this->_bcp, 0xFF, sizeof(_bcp)); memset(this->_ocp, 0xFF, sizeof(_ocp)); this->_inBios = true; } htype Memory::getRomType(void) { return this->_rom.getHardware(); } htype Memory::getTypeBios(void) { return this->_typeBios; } int Memory::loadRom(const char *file, htype hardware) { int ret; ret = this->_rom.load(file); hardware = (hardware == AUTO) ? this->_rom.getHardware() : hardware; this->_codeBios = this->_bios.load(hardware); this->_typeBios = hardware; return ret; } void Memory::setInBios(bool inBios) { this->_inBios = inBios; } void Memory::transferData(uint16_t startAddr) { int a = 0; for (uint16_t currAddr = startAddr ; currAddr <= (startAddr + 0x8c) ; currAddr++) { write_byte(0xfe00 + a, read_byte(currAddr)); a++; } } void Memory::HDMA() { if (getRomType() == GBC/* && read_byte(0xFF55) & 0x80*/) { uint16_t start = (((uint16_t)(read_byte(0xFF51) & 0xFF) << 4) | (((uint16_t)(read_byte(0xFF52) & 0xF0) >> 4))); uint16_t dest = (((uint16_t)(read_byte(0xFF53) & 0x1F) << 4) | (((uint16_t)(read_byte(0xFF54) & 0xF0) >> 4))); uint16_t len = read_byte(0xFF55) & 0x7F; // * 16 start <<= 4; dest <<= 4; len <<= 4; dest += 0x8000; for (auto curr = start ; curr < start + len ; ++curr, ++dest) write_byte(dest, read_byte(curr)); write_byte(0xFF55, read_byte(0xFF55) | 0x80, true); } } void Memory::handleInput() { if ((read_byte(0xff00) & 0x30) == 0x10) write_byte(0xff00, 0x10 + key[1], true); else if ((read_byte(0xff00) & 0x30) == 0x20) write_byte(0xff00, 0x20 + key[0], true); } t_color15 Memory::getBgColor15(uint8_t palId, uint8_t colorId) { return _bcp[palId][colorId]; } t_color15 Memory::getObjColor15(uint8_t palId, uint8_t colorId) { return _ocp[palId][colorId]; } uint8_t Memory::force_read_vram(uint16_t addr, uint8_t bank) { return this->_m_vram[bank & 0x1][addr & 0x1FFF]; } uint8_t Memory::read_byte(uint16_t addr) { switch (addr & 0xF000){ case 0x0000: if (this->_inBios) { if (addr <= 0xFF) return this->_codeBios[addr]; else if (addr >= 0x200 && addr < 0x900 && getTypeBios() == GBC) return this->_codeBios[addr - 0x100]; else return this->_rom.read(addr); } else { return this->_rom.read(addr); } break; case 0x1000: case 0x2000: case 0x3000: case 0x4000: case 0x5000: case 0x6000: case 0x7000: // ROM return this->_rom.read(addr); break; case 0x8000: case 0x9000: // VRAM return this->_m_vram[(this->_m_io[(VBK & 0xFF)] & 0x01)][(addr & 0x1FFF)]; break; case 0xA000: case 0xB000: // ERAM return this->_rom.read(addr); break; case 0xC000: case 0xD000: // WRAM if ((addr & 0xF000) < 0xD000) return this->_m_wram[0][(addr & 0x1FFF)]; else return this->_m_wram [(this->_m_io[(SVBK & 0xFF)] & 0x07)] [(addr & 0x1FFF)]; break; case 0xF000: switch (addr & 0x0F00){ case 0x0E00: if ((addr & 0xFF) <= 0x9F) { // SPRITE return this->_m_oam[(addr & 0xFF)]; } break; case 0x0F00: if ((addr & 0xFF) <= 0x7F) { // I/O return this->_m_io[(addr & 0xFF)]; } else { // Zero page return this->_m_zp[(addr & 0xFF) - 0x80]; } break; } break; } return 0; } void Memory::write_byte(uint16_t addr, uint8_t val, bool super) { switch (addr & 0xF000){ case 0x0000: case 0x1000: case 0x2000: case 0x3000: case 0x4000: case 0x5000: case 0x6000: case 0x7000: // ROM this->_rom.write(addr, val); break; case 0x8000: case 0x9000: // VRAM this->_m_vram[(this->_m_io[(VBK & 0xFF)] & 0x01)][(addr & 0x1FFF)] = val; break; case 0xA000: case 0xB000: // ERAM this->_rom.write(addr, val); break; case 0xC000: case 0xD000: // WRAM if ((addr & 0xF000) < 0xD000) this->_m_wram[0][(addr & 0x1FFF)] = val; else this->_m_wram[(this->_m_io[(SVBK & 0xFF)] & 0x03)][(addr & 0x1FFF)] = val; break; case 0xF000: switch (addr & 0x0F00){ case 0x0E00: if ((addr & 0xFF) <= 0x9F) { // SPRITE this->_m_oam[(addr & 0xFF)] = val; } break; case 0x0F00: if (!super && addr == 0xFF00) { // P1 this->_m_io[(addr & 0xFF)] = (val & 0xF0) | (this->_m_io[(addr & 0xFF)] & 0x0F); handleInput(); } else if (!super && addr == 0xFF04) { // DIV this->_m_io[(addr & 0xFF)] = 0x00; } else if ((addr & 0xFF) <= 0x7F) { // I/O //protect 3 first byte of register STAT form overwritting if (addr == REGISTER_STAT && !super) { val &= 0xF8; val |= read_byte(REGISTER_STAT) & 0x07; } if ((addr == 0xFF44 || addr == 0xFF45) && read_byte(0xFF40) & 0x80) { if (read_byte(0xFF44) == read_byte(0xFF45)) this->_m_io[0x41] |= 0x04;// Coincidence else this->_m_io[0x41] &= 0xfb; } else if (addr == 0xFF40 && (val & 0x80)) { if (read_byte(0xFF44) == read_byte(0xFF45)) this->_m_io[0x41] |= 0x04; else this->_m_io[0x41] &= 0xfb; } //DMA if (addr == REGISTER_DMA && !super) transferData(val << 8); if (addr == 0xFF55 && !super) { this->_m_io[(addr & 0xFF)] = val; HDMA(); } // BCPS / BCPD if (addr == REGISTER_BCPS) { this->_m_io[REGISTER_BCPD & 0xFF] = ((uint8_t*)_bcp)[val & 0x3F]; } if (addr == REGISTER_BCPD) { ((uint8_t*)_bcp)[read_byte(REGISTER_BCPS) & 0x3F] = val; if (read_byte(REGISTER_BCPS) & 0x80) write_byte(REGISTER_BCPS, ((((read_byte(REGISTER_BCPS) << 2) + 4) & 0xFF) >> 2) | 0x80); } // OCPS / OCPD if (addr == REGISTER_OCPS) { this->_m_io[REGISTER_OCPD & 0xFF] = ((uint8_t*)_ocp)[val & 0x3F]; } if (addr == REGISTER_OCPD) { ((uint8_t*)_ocp)[read_byte(REGISTER_OCPS) & 0x3F] = val; if (read_byte(REGISTER_OCPS) & 0x80) write_byte(REGISTER_OCPS, ((((read_byte(REGISTER_OCPS) << 2) + 4) & 0xFF) >> 2) | 0x80); } this->_m_io[(addr & 0xFF)] = val; } else { // Zero page this->_m_zp[(addr & 0xFF) - 0x80] = val; } break; } break; } } uint16_t Memory::read_word(uint16_t addr) { return this->read_byte(addr) + (this->read_byte(addr + 1) << 8); } void Memory::write_word(uint16_t addr, uint16_t val, bool super) { this->write_byte(addr, (val & 0xFF), super); this->write_byte(addr + 1, ((val & 0xFF00) >> 8), super); } <commit_msg>add 1<commit_after>#include <iostream> #include <cstring> #include "Memory.hpp" #include "registerAddr.hpp" Memory::Memory(void) {} Memory::~Memory(void) {} void Memory::reset(void) { memset(this->_m_wram, 0xFF, sizeof(_m_wram)); memset(this->_m_vram, 0xFF, sizeof(_m_vram)); memset(this->_m_oam, 0xFF, sizeof(_m_oam)); memset(this->_m_io, 0xFF, sizeof(_m_io)); memset(this->_m_zp, 0xFF, sizeof(_m_zp)); memset(this->_bcp, 0xFF, sizeof(_bcp)); memset(this->_ocp, 0xFF, sizeof(_ocp)); this->_inBios = true; } htype Memory::getRomType(void) { return this->_rom.getHardware(); } htype Memory::getTypeBios(void) { return this->_typeBios; } int Memory::loadRom(const char *file, htype hardware) { int ret; ret = this->_rom.load(file); hardware = (hardware == AUTO) ? this->_rom.getHardware() : hardware; this->_codeBios = this->_bios.load(hardware); this->_typeBios = hardware; return ret; } void Memory::setInBios(bool inBios) { this->_inBios = inBios; } void Memory::transferData(uint16_t startAddr) { int a = 0; for (uint16_t currAddr = startAddr ; currAddr <= (startAddr + 0x8c) ; currAddr++) { write_byte(0xfe00 + a, read_byte(currAddr)); a++; } } void Memory::HDMA() { if (getRomType() == GBC/* && read_byte(0xFF55) & 0x80*/) { uint16_t start = (((uint16_t)(read_byte(0xFF51) & 0xFF) << 4) | (((uint16_t)(read_byte(0xFF52) & 0xF0) >> 4))); uint16_t dest = (((uint16_t)(read_byte(0xFF53) & 0x1F) << 4) | (((uint16_t)(read_byte(0xFF54) & 0xF0) >> 4))); uint16_t len = read_byte(0xFF55) & 0x7F; len += 1; start <<= 4; dest <<= 4; len <<= 4; // *16 dest += 0x8000; for (auto curr = start ; curr < start + len ; ++curr, ++dest) write_byte(dest, read_byte(curr)); write_byte(0xFF55, read_byte(0xFF55) | 0x80, true); } } void Memory::handleInput() { if ((read_byte(0xff00) & 0x30) == 0x10) write_byte(0xff00, 0x10 + key[1], true); else if ((read_byte(0xff00) & 0x30) == 0x20) write_byte(0xff00, 0x20 + key[0], true); } t_color15 Memory::getBgColor15(uint8_t palId, uint8_t colorId) { return _bcp[palId][colorId]; } t_color15 Memory::getObjColor15(uint8_t palId, uint8_t colorId) { return _ocp[palId][colorId]; } uint8_t Memory::force_read_vram(uint16_t addr, uint8_t bank) { return this->_m_vram[bank & 0x1][addr & 0x1FFF]; } uint8_t Memory::read_byte(uint16_t addr) { switch (addr & 0xF000){ case 0x0000: if (this->_inBios) { if (addr <= 0xFF) return this->_codeBios[addr]; else if (addr >= 0x200 && addr < 0x900 && getTypeBios() == GBC) return this->_codeBios[addr - 0x100]; else return this->_rom.read(addr); } else { return this->_rom.read(addr); } break; case 0x1000: case 0x2000: case 0x3000: case 0x4000: case 0x5000: case 0x6000: case 0x7000: // ROM return this->_rom.read(addr); break; case 0x8000: case 0x9000: // VRAM return this->_m_vram[(this->_m_io[(VBK & 0xFF)] & 0x01)][(addr & 0x1FFF)]; break; case 0xA000: case 0xB000: // ERAM return this->_rom.read(addr); break; case 0xC000: case 0xD000: // WRAM if ((addr & 0xF000) < 0xD000) return this->_m_wram[0][(addr & 0x1FFF)]; else return this->_m_wram [(this->_m_io[(SVBK & 0xFF)] & 0x07)] [(addr & 0x1FFF)]; break; case 0xF000: switch (addr & 0x0F00){ case 0x0E00: if ((addr & 0xFF) <= 0x9F) { // SPRITE return this->_m_oam[(addr & 0xFF)]; } break; case 0x0F00: if ((addr & 0xFF) <= 0x7F) { // I/O return this->_m_io[(addr & 0xFF)]; } else { // Zero page return this->_m_zp[(addr & 0xFF) - 0x80]; } break; } break; } return 0; } void Memory::write_byte(uint16_t addr, uint8_t val, bool super) { switch (addr & 0xF000){ case 0x0000: case 0x1000: case 0x2000: case 0x3000: case 0x4000: case 0x5000: case 0x6000: case 0x7000: // ROM this->_rom.write(addr, val); break; case 0x8000: case 0x9000: // VRAM this->_m_vram[(this->_m_io[(VBK & 0xFF)] & 0x01)][(addr & 0x1FFF)] = val; break; case 0xA000: case 0xB000: // ERAM this->_rom.write(addr, val); break; case 0xC000: case 0xD000: // WRAM if ((addr & 0xF000) < 0xD000) this->_m_wram[0][(addr & 0x1FFF)] = val; else this->_m_wram[(this->_m_io[(SVBK & 0xFF)] & 0x03)][(addr & 0x1FFF)] = val; break; case 0xF000: switch (addr & 0x0F00){ case 0x0E00: if ((addr & 0xFF) <= 0x9F) { // SPRITE this->_m_oam[(addr & 0xFF)] = val; } break; case 0x0F00: if (!super && addr == 0xFF00) { // P1 this->_m_io[(addr & 0xFF)] = (val & 0xF0) | (this->_m_io[(addr & 0xFF)] & 0x0F); handleInput(); } else if (!super && addr == 0xFF04) { // DIV this->_m_io[(addr & 0xFF)] = 0x00; } else if ((addr & 0xFF) <= 0x7F) { // I/O //protect 3 first byte of register STAT form overwritting if (addr == REGISTER_STAT && !super) { val &= 0xF8; val |= read_byte(REGISTER_STAT) & 0x07; } if ((addr == 0xFF44 || addr == 0xFF45) && read_byte(0xFF40) & 0x80) { if (read_byte(0xFF44) == read_byte(0xFF45)) this->_m_io[0x41] |= 0x04;// Coincidence else this->_m_io[0x41] &= 0xfb; } else if (addr == 0xFF40 && (val & 0x80)) { if (read_byte(0xFF44) == read_byte(0xFF45)) this->_m_io[0x41] |= 0x04; else this->_m_io[0x41] &= 0xfb; } //DMA if (addr == REGISTER_DMA && !super) transferData(val << 8); if (addr == 0xFF55 && !super) { this->_m_io[(addr & 0xFF)] = val; HDMA(); } // BCPS / BCPD if (addr == REGISTER_BCPS) { this->_m_io[REGISTER_BCPD & 0xFF] = ((uint8_t*)_bcp)[val & 0x3F]; } if (addr == REGISTER_BCPD) { ((uint8_t*)_bcp)[read_byte(REGISTER_BCPS) & 0x3F] = val; if (read_byte(REGISTER_BCPS) & 0x80) write_byte(REGISTER_BCPS, ((((read_byte(REGISTER_BCPS) << 2) + 4) & 0xFF) >> 2) | 0x80); } // OCPS / OCPD if (addr == REGISTER_OCPS) { this->_m_io[REGISTER_OCPD & 0xFF] = ((uint8_t*)_ocp)[val & 0x3F]; } if (addr == REGISTER_OCPD) { ((uint8_t*)_ocp)[read_byte(REGISTER_OCPS) & 0x3F] = val; if (read_byte(REGISTER_OCPS) & 0x80) write_byte(REGISTER_OCPS, ((((read_byte(REGISTER_OCPS) << 2) + 4) & 0xFF) >> 2) | 0x80); } this->_m_io[(addr & 0xFF)] = val; } else { // Zero page this->_m_zp[(addr & 0xFF) - 0x80] = val; } break; } break; } } uint16_t Memory::read_word(uint16_t addr) { return this->read_byte(addr) + (this->read_byte(addr + 1) << 8); } void Memory::write_word(uint16_t addr, uint16_t val, bool super) { this->write_byte(addr, (val & 0xFF), super); this->write_byte(addr + 1, ((val & 0xFF00) >> 8), super); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: PolarLabelPositionHelper.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: iha $ $Date: 2004-01-17 13:10:03 $ * * 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: 2003 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CHART2_VIEW_POLARLABELPOSITIONHELPER_HXX #define _CHART2_VIEW_POLARLABELPOSITIONHELPER_HXX #include "LabelPositionHelper.hxx" #ifndef _COM_SUN_STAR_AWT_POINT_HPP_ #include <com/sun/star/awt/Point.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_ #include <com/sun/star/drawing/Position3D.hpp> #endif //............................................................................. namespace chart { //............................................................................. //----------------------------------------------------------------------------- /** */ class PolarPlottingPositionHelper; class PolarLabelPositionHelper : public LabelPositionHelper { public: PolarLabelPositionHelper( PolarPlottingPositionHelper* pPosHelper , sal_Int32 nDimensionCount , const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget , ShapeFactory* pShapeFactory ); virtual ~PolarLabelPositionHelper(); ::com::sun::star::awt::Point getLabelScreenPositionAndAlignment( LabelAlignment& rAlignment, bool bCenteredPosition , double fStartLogicValueOnAngleAxis, double fEndLogicValueOnAngleAxis , double fLogicInnerRadius, double fLogicOuterRadius , double fLogicZ) const; private: PolarPlottingPositionHelper* m_pPosHelper; }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.1.110); FILE MERGED 2005/09/05 18:43:47 rt 1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: PolarLabelPositionHelper.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 01:44:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART2_VIEW_POLARLABELPOSITIONHELPER_HXX #define _CHART2_VIEW_POLARLABELPOSITIONHELPER_HXX #include "LabelPositionHelper.hxx" #ifndef _COM_SUN_STAR_AWT_POINT_HPP_ #include <com/sun/star/awt/Point.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_POSITION3D_HPP_ #include <com/sun/star/drawing/Position3D.hpp> #endif //............................................................................. namespace chart { //............................................................................. //----------------------------------------------------------------------------- /** */ class PolarPlottingPositionHelper; class PolarLabelPositionHelper : public LabelPositionHelper { public: PolarLabelPositionHelper( PolarPlottingPositionHelper* pPosHelper , sal_Int32 nDimensionCount , const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xLogicTarget , ShapeFactory* pShapeFactory ); virtual ~PolarLabelPositionHelper(); ::com::sun::star::awt::Point getLabelScreenPositionAndAlignment( LabelAlignment& rAlignment, bool bCenteredPosition , double fStartLogicValueOnAngleAxis, double fEndLogicValueOnAngleAxis , double fLogicInnerRadius, double fLogicOuterRadius , double fLogicZ) const; private: PolarPlottingPositionHelper* m_pPosHelper; }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>#ifndef DICE_INTERPRETER_HPP_ #define DICE_INTERPRETER_HPP_ #include <array> #include <memory> #include <sstream> #include <cassert> #include "value.hpp" #include "symbols.hpp" #include "environment.hpp" namespace dice { // compute decomposition of a random variable class decomposition_visitor : public value_visitor { public: inline void visit(type_int*) override {} inline void visit(type_double*) override {} inline void visit(type_rand_var* var) override { var->data() = var->data().compute_decomposition(); } }; // count random variables with dependencies class dependencies_visitor : public value_visitor { public: inline void visit(type_int*) override {} inline void visit(type_double*) override {} inline void visit(type_rand_var* var) override { if (var->data().has_dependencies()) ++counter_; } inline std::size_t count() const { return counter_; } private: std::size_t counter_ = 0; }; /** Direct interpreter is a dice expressions interpreter that evaluates * expressions as soon as they are parsed. It does not use any itermediate * representation. */ template<typename Environment> class direct_interpreter { public: using value_type = std::unique_ptr<base_value>; using value_list = std::vector<value_type>; explicit direct_interpreter(Environment* env) : env_(env) {} void enter_assign() { is_definition_ = true; } /** Create a new default value. * This is used when there is a parsing error. * @return default value */ value_type make_default() { return make<type_int>(0); } /** Interpret number as an int or double. * @param token of the number * @return number's value */ value_type number(symbol& token) { assert(token.type == symbol_type::number); return std::move(token.value); } /** Interpret a variable name. * @param name of a variable * @return value of the variable or nullptr if it does not exist */ value_type variable(const std::string& name) { auto value = env_->get_var(name); if (value == nullptr) { throw compiler_error("Unknown variable '" + name + "'"); } return value->clone(); } /** Add left hand side to the right hand side * @param left operand * @param right operand * @return sum */ value_type add(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("+", std::move(left), std::move(right)); } /** Subtract right hand side from the left hand side * @param left operand * @param right operand * @return difference */ value_type sub(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("-", std::move(left), std::move(right)); } /** Multiply left hand side with the right hand side * @param left operand * @param right operand * @return product */ value_type mult(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("*", std::move(left), std::move(right)); } /** Divide left hand side with the right hand side * @param left operand * @param right operand * @return division */ value_type div(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("/", std::move(left), std::move(right)); } /** Negate value. * @param value * @return negation of the value */ value_type unary_minus(value_type value) { return env_->call("unary-", std::move(value)); } /** Compute a binary relational operator. * @param type of the operator (<, <=, ==, !=, >=, >) * @param left operand * @param right operand * @return result */ value_type rel_op( const std::string& type, value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call(type, std::move(left), std::move(right)); } /** Compute relational in operator. * @param value to test * @param lower_bound of the interval * @param upper_bound of the interval * @return result of the in operator */ value_type rel_in( value_type value, value_type lower_bound, value_type upper_bound) { return env_->call("in", std::move(value), std::move(lower_bound), std::move(upper_bound)); } /** Compute a roll operator. * @param left operand * @param right operand * @return result of the operator */ value_type roll(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("roll_op", std::move(left), std::move(right)); } /** Assing value to variable with given name. * If a variable with given name already exists, a compiler_error * exception will be thrown. * @param name of a new variable * @param value of the variable * @return nullptr */ value_type assign(const std::string& name, value_type value) { if (env_->get_var(name) != nullptr) { throw compiler_error("Variable '" + name + "' redefinition."); } decomposition_visitor decomp; value->accept(&decomp); env_->set_var(name, std::move(value)); is_definition_ = false; return nullptr; } /** Call a function with given arguments. * @param name of a function * @param arguments * @return result of the function call */ value_type call(const std::string& name, value_list&& arguments) { if (is_definition_) { // check whether there is a parameter that depends on // a random variable dependencies_visitor deps; for (auto&& arg : arguments) { arg->accept(&deps); if (deps.count() > 0) break; } // if there is such a parameter, compute decomposition for // all random variables in the list if (deps.count() > 0) { decomposition_visitor decomp; for (auto&& arg : arguments) { arg->accept(&decomp); } } } return env_->call_var(name, arguments.begin(), arguments.end()); } private: Environment* env_; bool is_definition_ = false; /** Process children of a binary node. * @param left operand * @param right operand */ void process_children(base_value* left, base_value* right) { // don't convert random variables if we're not in a name definition if (!is_definition_) return; dependencies_visitor deps; left->accept(&deps); right->accept(&deps); if (deps.count() > 0) { decomposition_visitor decomp; left->accept(&decomp); right->accept(&decomp); } } }; } #endif // DICE_INTERPRETER_HPP_<commit_msg>Allow variable redefinition<commit_after>#ifndef DICE_INTERPRETER_HPP_ #define DICE_INTERPRETER_HPP_ #include <array> #include <memory> #include <sstream> #include <cassert> #include "value.hpp" #include "symbols.hpp" #include "environment.hpp" namespace dice { // compute decomposition of a random variable class decomposition_visitor : public value_visitor { public: inline void visit(type_int*) override {} inline void visit(type_double*) override {} inline void visit(type_rand_var* var) override { var->data() = var->data().compute_decomposition(); } }; // count random variables with dependencies class dependencies_visitor : public value_visitor { public: inline void visit(type_int*) override {} inline void visit(type_double*) override {} inline void visit(type_rand_var* var) override { if (var->data().has_dependencies()) ++counter_; } inline std::size_t count() const { return counter_; } private: std::size_t counter_ = 0; }; /** Direct interpreter is a dice expressions interpreter that evaluates * expressions as soon as they are parsed. It does not use any itermediate * representation. */ template<typename Environment> class direct_interpreter { public: using value_type = std::unique_ptr<base_value>; using value_list = std::vector<value_type>; explicit direct_interpreter(Environment* env) : env_(env) {} void enter_assign() { is_definition_ = true; } /** Create a new default value. * This is used when there is a parsing error. * @return default value */ value_type make_default() { return make<type_int>(0); } /** Interpret number as an int or double. * @param token of the number * @return number's value */ value_type number(symbol& token) { assert(token.type == symbol_type::number); return std::move(token.value); } /** Interpret a variable name. * @param name of a variable * @return value of the variable or nullptr if it does not exist */ value_type variable(const std::string& name) { auto value = env_->get_var(name); if (value == nullptr) { throw compiler_error("Unknown variable '" + name + "'"); } return value->clone(); } /** Add left hand side to the right hand side * @param left operand * @param right operand * @return sum */ value_type add(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("+", std::move(left), std::move(right)); } /** Subtract right hand side from the left hand side * @param left operand * @param right operand * @return difference */ value_type sub(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("-", std::move(left), std::move(right)); } /** Multiply left hand side with the right hand side * @param left operand * @param right operand * @return product */ value_type mult(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("*", std::move(left), std::move(right)); } /** Divide left hand side with the right hand side * @param left operand * @param right operand * @return division */ value_type div(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("/", std::move(left), std::move(right)); } /** Negate value. * @param value * @return negation of the value */ value_type unary_minus(value_type value) { return env_->call("unary-", std::move(value)); } /** Compute a binary relational operator. * @param type of the operator (<, <=, ==, !=, >=, >) * @param left operand * @param right operand * @return result */ value_type rel_op( const std::string& type, value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call(type, std::move(left), std::move(right)); } /** Compute relational in operator. * @param value to test * @param lower_bound of the interval * @param upper_bound of the interval * @return result of the in operator */ value_type rel_in( value_type value, value_type lower_bound, value_type upper_bound) { return env_->call("in", std::move(value), std::move(lower_bound), std::move(upper_bound)); } /** Compute a roll operator. * @param left operand * @param right operand * @return result of the operator */ value_type roll(value_type left, value_type right) { process_children(left.get(), right.get()); return env_->call("roll_op", std::move(left), std::move(right)); } /** Assing value to variable with given name. * If a variable with given name already exists, a compiler_error * exception will be thrown. * @param name of a new variable * @param value of the variable * @return nullptr */ value_type assign(const std::string& name, value_type value) { if (!variable_redefinition_ && env_->get_var(name) != nullptr) { throw compiler_error("Variable '" + name + "' redefinition."); } decomposition_visitor decomp; value->accept(&decomp); env_->set_var(name, std::move(value)); is_definition_ = false; return nullptr; } /** Call a function with given arguments. * @param name of a function * @param arguments * @return result of the function call */ value_type call(const std::string& name, value_list&& arguments) { if (is_definition_) { // check whether there is a parameter that depends on // a random variable dependencies_visitor deps; for (auto&& arg : arguments) { arg->accept(&deps); if (deps.count() > 0) break; } // if there is such a parameter, compute decomposition for // all random variables in the list if (deps.count() > 0) { decomposition_visitor decomp; for (auto&& arg : arguments) { arg->accept(&decomp); } } } return env_->call_var(name, arguments.begin(), arguments.end()); } /** Enable/disable variable redefinition. * @param value true iff the redefinition is allowed */ void set_variable_redefinition(bool value) { variable_redefinition_ = value; } /** Check whether the variable redefinition is allowed. * @return true iff the redefinition is allowed */ bool get_variable_redefinition() const { return variable_redefinition_; } private: Environment* env_; bool is_definition_ = false; bool variable_redefinition_ = false; /** Process children of a binary node. * @param left operand * @param right operand */ void process_children(base_value* left, base_value* right) { // don't convert random variables if we're not in a name definition if (!is_definition_) return; dependencies_visitor deps; left->accept(&deps); right->accept(&deps); if (deps.count() > 0) { decomposition_visitor decomp; left->accept(&decomp); right->accept(&decomp); } } }; } #endif // DICE_INTERPRETER_HPP_<|endoftext|>
<commit_before>// Copyright (c) 2010 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 "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.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/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.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" #include "net/test/test_server.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit 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 char kConsoleTestPage[] = "files/devtools/console_test_page.html"; const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html"; const char kJsPage[] = "files/devtools/js_page.html"; const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html"; const char kPauseOnExceptionTestPage[] = "files/devtools/pause_on_exception.html"; const char kPauseWhenLoadingDevTools[] = "files/devtools/pause_when_loading_devtools.html"; const char kPauseWhenScriptIsRunning[] = "files/devtools/pause_when_script_is_running.html"; const char kResourceContentLengthTestPage[] = "files/devtools/image.html"; const char kResourceTestPage[] = "files/devtools/resource_test_page.html"; const char kSimplePage[] = "files/devtools/simple_page.html"; const char kSyntaxErrorTestPage[] = "files/devtools/script_syntax_error.html"; const char kDebuggerClosurePage[] = "files/devtools/debugger_closure.html"; const char kCompletionOnPause[] = "files/devtools/completion_on_pause.html"; const char kPageWithContentScript[] = "files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::string& 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::string& test_page) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->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()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } 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_); // Wait only when DevToolsWindow has a browser. For docked DevTools, this // is NULL and we skip the wait. if (browser) BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Fails after WebKit roll 59365:59477, http://crbug.com/44202. #if defined(OS_LINUX) #define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength #else #define MAYBE_TestResourceContentLength TestResourceContentLength #endif // defined(OS_LINUX) // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests cached resource mime type. // @see http://crbug.com/27364 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) { RunTest("testCachedResourceMimeType", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests heap profiler. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) { RunTest("testHeapProfiler", kHeapProfilerPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Clear inspector settings to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings(); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests pause on exception. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) { RunTest("testPauseOnException", kPauseOnExceptionTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. // The test fails on linux and should be related to Webkit patch // http://trac.webkit.org/changeset/64124/trunk. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } // Tests that scope can be expanded and contains expected variables. // TODO(japhet): Disabled during webkit landing per bug http://crbug.com/52085 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, 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, TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Test that Storage panel can be shown. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) { RunTest("testShowStoragePanel", kDebuggerTestPage); } // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestMessageLoopReentrant) { RunTest("testMessageLoopReentrant", kDebuggerTestPage); } } // namespace <commit_msg>Disable one more test for WebKit roll 65992:66033<commit_after>// Copyright (c) 2010 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 "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.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/extensions/extension_host.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.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" #include "net/test/test_server.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: explicit 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 char kConsoleTestPage[] = "files/devtools/console_test_page.html"; const char kDebuggerTestPage[] = "files/devtools/debugger_test_page.html"; const char kJsPage[] = "files/devtools/js_page.html"; const char kHeapProfilerPage[] = "files/devtools/heap_profiler.html"; const char kPauseOnExceptionTestPage[] = "files/devtools/pause_on_exception.html"; const char kPauseWhenLoadingDevTools[] = "files/devtools/pause_when_loading_devtools.html"; const char kPauseWhenScriptIsRunning[] = "files/devtools/pause_when_script_is_running.html"; const char kResourceContentLengthTestPage[] = "files/devtools/image.html"; const char kResourceTestPage[] = "files/devtools/resource_test_page.html"; const char kSimplePage[] = "files/devtools/simple_page.html"; const char kSyntaxErrorTestPage[] = "files/devtools/script_syntax_error.html"; const char kDebuggerClosurePage[] = "files/devtools/debugger_closure.html"; const char kCompletionOnPause[] = "files/devtools/completion_on_pause.html"; const char kPageWithContentScript[] = "files/devtools/page_with_content_script.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::string& 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::string& test_page) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL(test_page); ui_test_utils::NavigateToURL(browser(), url); inspected_rvh_ = GetInspectedTab()->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()); } TabContents* GetInspectedTab() { return browser()->GetTabContentsAt(0); } 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_); // Wait only when DevToolsWindow has a browser. For docked DevTools, this // is NULL and we skip the wait. if (browser) BrowserClosedObserver close_observer(browser); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; class CancelableQuitTask : public Task { public: explicit CancelableQuitTask(const std::string& timeout_message) : timeout_message_(timeout_message), cancelled_(false) { } void cancel() { cancelled_ = true; } virtual void Run() { if (cancelled_) { return; } FAIL() << timeout_message_; MessageLoop::current()->Quit(); } private: std::string timeout_message_; bool cancelled_; }; // Base class for DevTools tests that test devtools functionality for // extensions and content scripts. class DevToolsExtensionDebugTest : public DevToolsSanityTest, public NotificationObserver { public: DevToolsExtensionDebugTest() : DevToolsSanityTest() { PathService::Get(chrome::DIR_TEST_DATA, &test_extensions_dir_); test_extensions_dir_ = test_extensions_dir_.AppendASCII("devtools"); test_extensions_dir_ = test_extensions_dir_.AppendASCII("extensions"); } protected: // Load an extention from test\data\devtools\extensions\<extension_name> void LoadExtension(const char* extension_name) { FilePath path = test_extensions_dir_.AppendASCII(extension_name); ASSERT_TRUE(LoadExtensionFromPath(path)) << "Failed to load extension."; } private: bool LoadExtensionFromPath(const FilePath& path) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); size_t num_before = service->extensions()->size(); { NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); service->LoadExtension(path); ui_test_utils::RunMessageLoop(); delayed_quit->cancel(); } size_t num_after = service->extensions()->size(); if (num_after != (num_before + 1)) return false; return WaitForExtensionHostsToLoad(); } bool WaitForExtensionHostsToLoad() { // Wait for all the extension hosts that exist to finish loading. // NOTE: This assumes that the extension host list is not changing while // this method is running. NotificationRegistrar registrar; registrar.Add(this, NotificationType::EXTENSION_HOST_DID_STOP_LOADING, NotificationService::AllSources()); CancelableQuitTask* delayed_quit = new CancelableQuitTask("Extension host load timed out."); MessageLoop::current()->PostDelayedTask(FROM_HERE, delayed_quit, 4*1000); ExtensionProcessManager* manager = browser()->profile()->GetExtensionProcessManager(); for (ExtensionProcessManager::const_iterator iter = manager->begin(); iter != manager->end();) { if ((*iter)->did_stop_loading()) ++iter; else ui_test_utils::RunMessageLoop(); } delayed_quit->cancel(); return true; } void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSION_LOADED: case NotificationType::EXTENSION_HOST_DID_STOP_LOADING: MessageLoopForUI::current()->Quit(); break; default: NOTREACHED(); break; } } FilePath test_extensions_dir_; }; // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Fails after WebKit roll 59365:59477, http://crbug.com/44202. #if defined(OS_LINUX) #define MAYBE_TestResourceContentLength FLAKY_TestResourceContentLength #else #define MAYBE_TestResourceContentLength TestResourceContentLength #endif // defined(OS_LINUX) // Tests resources have correct sizes. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, MAYBE_TestResourceContentLength) { RunTest("testResourceContentLength", kResourceContentLengthTestPage); } // Tests resource headers. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestResourceHeaders) { RunTest("testResourceHeaders", kResourceTestPage); } // Tests cached resource mime type. // @see http://crbug.com/27364 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCachedResourceMimeType) { RunTest("testCachedResourceMimeType", kResourceTestPage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests heap profiler. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHeapProfiler) { RunTest("testHeapProfiler", kHeapProfilerPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } // Tests that scripts tab is populated with inspected scripts even if it // hadn't been shown by the moment inspected paged refreshed. // @see http://crbug.com/26312 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestScriptsTabIsPopulatedOnInspectedPageRefresh) { // Clear inspector settings to ensure that Elements will be // current panel when DevTools window is open. GetInspectedTab()->render_view_host()->delegate()->ClearInspectorSettings(); RunTest("testScriptsTabIsPopulatedOnInspectedPageRefresh", kDebuggerTestPage); } // Tests that a content script is in the scripts list. // This test is disabled, see bug 28961. IN_PROC_BROWSER_TEST_F(DevToolsExtensionDebugTest, TestContentScriptIsPresent) { LoadExtension("simple_content_script"); RunTest("testContentScriptIsPresent", kPageWithContentScript); } // Tests that scripts are not duplicated after Scripts Panel switch. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestNoScriptDuplicatesOnPanelSwitch) { RunTest("testNoScriptDuplicatesOnPanelSwitch", kDebuggerTestPage); } // Tests set breakpoint. // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestSetBreakpoint) { RunTest("testSetBreakpoint", kDebuggerTestPage); } // Tests pause on exception. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestPauseOnException) { RunTest("testPauseOnException", kPauseOnExceptionTestPage); } // Tests that debugger works correctly if pause event occurs when DevTools // frontend is being loaded. // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenLoadingDevTools) { RunTest("testPauseWhenLoadingDevTools", kPauseWhenLoadingDevTools); } // Tests that pressing 'Pause' will pause script execution if the script // is already running. // The test fails on linux and should be related to Webkit patch // http://trac.webkit.org/changeset/64124/trunk. // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseWhenScriptIsRunning) { RunTest("testPauseWhenScriptIsRunning", kPauseWhenScriptIsRunning); } // Tests that scope can be expanded and contains expected variables. // TODO(japhet): Disabled during webkit landing per bug http://crbug.com/52085 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, 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, TestAutoContinueOnSyntaxError) { RunTest("testAutoContinueOnSyntaxError", kSyntaxErrorTestPage); } IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestCompletionOnPause) { RunTest("testCompletionOnPause", kCompletionOnPause); } // Tests that 'Pause' button works for eval. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestPauseInEval) { RunTest("testPauseInEval", kDebuggerTestPage); } // Test that Storage panel can be shown. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowStoragePanel) { RunTest("testShowStoragePanel", kDebuggerTestPage); } // Disabled. See http://code.google.com/p/chromium/issues/detail?id=53406 IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestMessageLoopReentrant) { RunTest("testMessageLoopReentrant", kDebuggerTestPage); } } // namespace <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- // E L E N A P r o j e c t: ELENA Compiler // // This file contains ELENA Executive ELF Image class implementation // supported platform: PPC64le // (C)2021, by Aleksey Rakov //--------------------------------------------------------------------------- #include "clicommon.h" // -------------------------------------------------------------------------- #include "elfppcimage.h" #include "ppcrelocation.h" #include <elf.h> // --- ElfPPC64leImageFormatter --- void ElfPPC64leImageFormatter :: fillElfData(ImageProviderBase& provider, ElfData& elfData, pos_t fileAlignment, RelocationMap& importMapping) { pos_t count = fillImportTable(provider.externals(), elfData); Section* code = provider.getTextSection(); Section* data = provider.getDataSection(); Section* import = provider.getImportSection(); MemoryWriter dynamicWriter(data); dynamicWriter.align(fileAlignment, 0); elfData.dynamicOffset = dynamicWriter.position(); // reference to GOT ref_t importRef = (count + 1) | mskImportRef64; ref_t importRelRef = (count + 1) | mskImportRelRef32; importMapping.add(importRef, 0); // reserve got table MemoryWriter gotWriter(import); gotWriter.writeQWord(0); gotWriter.writeQWord(0); pos_t gotStart = gotWriter.position(); gotWriter.writeBytes(0, count * 8); gotWriter.seek(gotStart); // reserve relocation table MemoryWriter reltabWriter(import); pos_t reltabOffset = reltabWriter.position(); reltabWriter.writeBytes(0, count * 24); reltabWriter.seek(reltabOffset); // reserve symbol table MemoryWriter symtabWriter(import); pos_t symtabOffset = symtabWriter.position(); symtabWriter.writeBytes(0, (count + 1) * 24); symtabWriter.seek(symtabOffset + 24); // string table MemoryWriter strWriter(import); pos_t strOffset = strWriter.position(); strWriter.writeChar('\0'); // code writer MemoryWriter codeWriter(code); writePLTStartEntry(codeWriter, importRelRef, gotStart); pos_t pltFirstEntry = codeWriter.position(); int relocateType = getRelocationType(); long long symbolIndex = 1; int pltIndex = 1; for (auto fun = elfData.functions.start(); !fun.eof(); ++fun) { pos_t gotPosition = gotWriter.position(); ref_t funRef = *fun & ~mskAnyRef; importMapping.add(funRef | mskImportRef64, gotPosition); pos_t strIndex = strWriter.position() - strOffset; // symbol table entry symtabWriter.writeDWord(strIndex); symtabWriter.writeByte(0x12); symtabWriter.writeByte(0x60); symtabWriter.writeWord(SHN_UNDEF); symtabWriter.writeQWord(0); symtabWriter.writeQWord(0); // relocation table entry //pos_t relPosition = reltabWriter.position() - reltabOffset; reltabWriter.writeQReference(importRef, gotPosition); reltabWriter.writeQWord((symbolIndex << 32) + relocateType); reltabWriter.writeQWord(0); // string table entry strWriter.writeString(fun.key()); // plt entry writePLTEntry(codeWriter, 0, 0, 0, pltIndex); //gotWriter.writeDWord(); symbolIndex++; pltIndex++; } // write dynamic segment // write libraries needed to be loaded auto dll = elfData.libraries.start(); while (!dll.eof()) { dynamicWriter.writeQWord(DT_NEEDED); dynamicWriter.writeQWord(strWriter.position() - strOffset); strWriter.writeString(*dll); ++dll; } strWriter.writeChar('\0'); pos_t strLength = strWriter.position() - strOffset; dynamicWriter.writeQWord(DT_STRTAB); dynamicWriter.writeQReference(importRef, strOffset); dynamicWriter.writeQWord(DT_SYMTAB); dynamicWriter.writeQReference(importRef, symtabOffset); dynamicWriter.writeQWord(DT_STRSZ); dynamicWriter.writeQWord(strLength); dynamicWriter.writeQWord(DT_SYMENT); dynamicWriter.writeQWord(24); dynamicWriter.writeQWord(DT_PLTGOT); dynamicWriter.writeQReference(importRef, /*gotStart*/0); dynamicWriter.writeQWord(DT_PLTRELSZ); dynamicWriter.writeQWord(count * 24); dynamicWriter.writeQWord(DT_PLTREL); dynamicWriter.writeQWord(DT_RELA); dynamicWriter.writeQWord(DT_JMPREL); dynamicWriter.writeQReference(importRef, reltabOffset); //dynamicWriter.writeQWord(DT_RELA); //dynamicWriter.writeQReference(importRef, reltabOffset); //dynamicWriter.writeQWord(DT_RELASZ); //dynamicWriter.writeQWord(count * 24); //dynamicWriter.writeQWord(DT_RELAENT); //dynamicWriter.writeQWord(24); // NOTE : points to 32 bytes before the .glink lazy link symbol resolver stubs dynamicWriter.writeQWord(DT_PPC64_GLINK); dynamicWriter.writeQReference(mskCodeRef64, pltFirstEntry - 0x20); dynamicWriter.writeQWord(DT_PPC64_OPT); dynamicWriter.writeQWord(1); dynamicWriter.writeQWord(0); dynamicWriter.writeQWord(0); dynamicWriter.align(fileAlignment, 0); elfData.dynamicSize = dynamicWriter.position() - elfData.dynamicOffset; } int ElfPPC64leImageFormatter :: getRelocationType() { return R_PPC64_JMP_SLOT; } void ElfPPC64leImageFormatter :: fixSection(Section* section, AddressSpace& map) { section->fixupReferences<AddressSpace*>(&map, ppc64relocate); } void ElfPPC64leImageFormatter :: fixImportSection(Section* section, AddressSpace& map) { section->fixupReferences<AddressSpace*>(&map, ppc64relocateElf64Import); } void ElfPPC64leImageFormatter :: writePLTStartEntry(MemoryWriter& codeWriter, ref_t gotReference, pos_t disp) { codeWriter.writeQReference(gotReference, disp - 0x1C); // ; r12 holds the address of the res_N stub for the target routine // ; Determine addressability.This sequence works for both PIC // ; #and non - PIC code and does not rely on presence of the TOC pointer. // mflr r0 codeWriter.writeDWord(0x7c0802a6); // bcl 20, 31, 1f codeWriter.writeDWord(0x429F0005); // mflr r11 codeWriter.writeDWord(0x7d6802a6); // mtlr r0 codeWriter.writeDWord(0x7c0803a6); // ; Compute.plt section index from entry point address in r12 // ; .plt section index is placed into r0 as argument to the resolver // ld r0, -10h(r11) codeWriter.writeDWord(0xe80bfff0); // sub r12, r12, r11 codeWriter.writeDWord(0x7d8b6050); // add r11,r0,r11 codeWriter.writeDWord(0x7d605a14); // subi r0, r12, 44, codeWriter.writeDWord(0x380cffd4); // ; Load resolver addressand DSO identifier from the // ; first two doublewords of the PLT // ld r12, 0(r11) codeWriter.writeDWord(0xe98b0000); // rldicl r0, r0, 60, 4 //codeWriter.writeDWord(0x7800F082); codeWriter.writeDWord(0x7800e102); // ; Branch to resolver // mtctr r12 codeWriter.writeDWord(0x7d8903a6); // ld r11, 8(r11) codeWriter.writeDWord(0xe96b0008); // bctr codeWriter.writeDWord(0x4e800420); } pos_t ElfPPC64leImageFormatter :: writePLTEntry(MemoryWriter& codeWriter, pos_t symbolIndex, ref_t gotReference, pos_t gotOffset, int entryIndex) { // NOTE : .glink lazy link symbol resolver stub pos_t position = codeWriter.position(); int offs = -52 - ((entryIndex - 1) * 4); // b PLTStartEntry codeWriter.writeDWord(0x4B000000 | ((unsigned int)offs & 0xFFFFFF)); return position; } <commit_msg>reverting back changes<commit_after>//--------------------------------------------------------------------------- // E L E N A P r o j e c t: ELENA Compiler // // This file contains ELENA Executive ELF Image class implementation // supported platform: PPC64le // (C)2021, by Aleksey Rakov //--------------------------------------------------------------------------- #include "clicommon.h" // -------------------------------------------------------------------------- #include "elfppcimage.h" #include "ppcrelocation.h" #include <elf.h> // --- ElfPPC64leImageFormatter --- void ElfPPC64leImageFormatter :: fillElfData(ImageProviderBase& provider, ElfData& elfData, pos_t fileAlignment, RelocationMap& importMapping) { pos_t count = fillImportTable(provider.externals(), elfData); Section* code = provider.getTextSection(); Section* data = provider.getDataSection(); Section* import = provider.getImportSection(); MemoryWriter dynamicWriter(data); dynamicWriter.align(fileAlignment, 0); elfData.dynamicOffset = dynamicWriter.position(); // reference to GOT ref_t importRef = (count + 1) | mskImportRef64; ref_t importRelRef = (count + 1) | mskImportRelRef32; importMapping.add(importRef, 0); // reserve got table MemoryWriter gotWriter(import); gotWriter.writeQWord(0); gotWriter.writeQWord(0); pos_t gotStart = gotWriter.position(); gotWriter.writeBytes(0, count * 8); gotWriter.seek(gotStart); // reserve relocation table MemoryWriter reltabWriter(import); pos_t reltabOffset = reltabWriter.position(); reltabWriter.writeBytes(0, count * 24); reltabWriter.seek(reltabOffset); // reserve symbol table MemoryWriter symtabWriter(import); pos_t symtabOffset = symtabWriter.position(); symtabWriter.writeBytes(0, (count + 1) * 24); symtabWriter.seek(symtabOffset + 24); // string table MemoryWriter strWriter(import); pos_t strOffset = strWriter.position(); strWriter.writeChar('\0'); // code writer MemoryWriter codeWriter(code); writePLTStartEntry(codeWriter, importRelRef, gotStart); pos_t pltFirstEntry = codeWriter.position(); int relocateType = getRelocationType(); long long symbolIndex = 1; int pltIndex = 1; for (auto fun = elfData.functions.start(); !fun.eof(); ++fun) { pos_t gotPosition = gotWriter.position(); ref_t funRef = *fun & ~mskAnyRef; importMapping.add(funRef | mskImportRef64, gotPosition); pos_t strIndex = strWriter.position() - strOffset; // symbol table entry symtabWriter.writeDWord(strIndex); symtabWriter.writeByte(0x12); symtabWriter.writeByte(0x60); symtabWriter.writeWord(SHN_UNDEF); symtabWriter.writeQWord(0); symtabWriter.writeQWord(0); // relocation table entry //pos_t relPosition = reltabWriter.position() - reltabOffset; reltabWriter.writeQReference(importRef, gotPosition); reltabWriter.writeQWord((symbolIndex << 32) + relocateType); reltabWriter.writeQWord(0); // string table entry strWriter.writeString(fun.key()); // plt entry writePLTEntry(codeWriter, 0, 0, 0, pltIndex); //gotWriter.writeDWord(); symbolIndex++; pltIndex++; } // write dynamic segment // write libraries needed to be loaded auto dll = elfData.libraries.start(); while (!dll.eof()) { dynamicWriter.writeQWord(DT_NEEDED); dynamicWriter.writeQWord(strWriter.position() - strOffset); strWriter.writeString(*dll); ++dll; } strWriter.writeChar('\0'); pos_t strLength = strWriter.position() - strOffset; dynamicWriter.writeQWord(DT_STRTAB); dynamicWriter.writeQReference(importRef, strOffset); dynamicWriter.writeQWord(DT_SYMTAB); dynamicWriter.writeQReference(importRef, symtabOffset); dynamicWriter.writeQWord(DT_STRSZ); dynamicWriter.writeQWord(strLength); dynamicWriter.writeQWord(DT_SYMENT); dynamicWriter.writeQWord(24); dynamicWriter.writeQWord(DT_PLTGOT); dynamicWriter.writeQReference(importRef, /*gotStart*/0); dynamicWriter.writeQWord(DT_PLTRELSZ); dynamicWriter.writeQWord(count * 24); dynamicWriter.writeQWord(DT_PLTREL); dynamicWriter.writeQWord(DT_RELA); dynamicWriter.writeQWord(DT_JMPREL); dynamicWriter.writeQReference(importRef, reltabOffset); //dynamicWriter.writeQWord(DT_RELA); //dynamicWriter.writeQReference(importRef, reltabOffset); //dynamicWriter.writeQWord(DT_RELASZ); //dynamicWriter.writeQWord(count * 24); //dynamicWriter.writeQWord(DT_RELAENT); //dynamicWriter.writeQWord(24); // NOTE : points to 32 bytes before the .glink lazy link symbol resolver stubs dynamicWriter.writeQWord(DT_PPC64_GLINK); dynamicWriter.writeQReference(mskCodeRef64, pltFirstEntry - 0x20); dynamicWriter.writeQWord(DT_PPC64_OPT); dynamicWriter.writeQWord(1); dynamicWriter.writeQWord(0); dynamicWriter.writeQWord(0); dynamicWriter.align(fileAlignment, 0); elfData.dynamicSize = dynamicWriter.position() - elfData.dynamicOffset; } int ElfPPC64leImageFormatter :: getRelocationType() { return R_PPC64_JMP_SLOT; } void ElfPPC64leImageFormatter :: fixSection(Section* section, AddressSpace& map) { section->fixupReferences<AddressSpace*>(&map, ppc64relocate); } void ElfPPC64leImageFormatter :: fixImportSection(Section* section, AddressSpace& map) { section->fixupReferences<AddressSpace*>(&map, ppc64relocateElf64Import); } void ElfPPC64leImageFormatter :: writePLTStartEntry(MemoryWriter& codeWriter, ref_t gotReference, pos_t disp) { codeWriter.writeQReference(gotReference, disp - 0x1C); // ; r12 holds the address of the res_N stub for the target routine // ; Determine addressability.This sequence works for both PIC // ; #and non - PIC code and does not rely on presence of the TOC pointer. // mflr r0 codeWriter.writeDWord(0x7c0802a6); // bcl 20, 31, 1f codeWriter.writeDWord(0x429F0005); // mflr r11 codeWriter.writeDWord(0x7d6802a6); // mtlr r0 codeWriter.writeDWord(0x7c0803a6); // ; Compute.plt section index from entry point address in r12 // ; .plt section index is placed into r0 as argument to the resolver // ld r0, -10h(r11) codeWriter.writeDWord(0xe80bfff0); // sub r12, r12, r11 codeWriter.writeDWord(0x7d8b6050); // add r11,r0,r11 codeWriter.writeDWord(0x7d605a14); // subi r0, r12, 44, codeWriter.writeDWord(0x380cffd4); // ; Load resolver addressand DSO identifier from the // ; first two doublewords of the PLT // ld r12, 0(r11) codeWriter.writeDWord(0xe98b0000); // rldicl r0, r0, 62, 2 codeWriter.writeDWord(0x7800f082); // ; Branch to resolver // mtctr r12 codeWriter.writeDWord(0x7d8903a6); // ld r11, 8(r11) codeWriter.writeDWord(0xe96b0008); // bctr codeWriter.writeDWord(0x4e800420); } pos_t ElfPPC64leImageFormatter :: writePLTEntry(MemoryWriter& codeWriter, pos_t symbolIndex, ref_t gotReference, pos_t gotOffset, int entryIndex) { // NOTE : .glink lazy link symbol resolver stub pos_t position = codeWriter.position(); int offs = -52 - ((entryIndex - 1) * 4); // b PLTStartEntry codeWriter.writeDWord(0x4B000000 | ((unsigned int)offs & 0xFFFFFF)); return position; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief EEPROM ドライバー @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "common/i2c_io.hpp" #include "common/time.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief EEPROM テンプレートクラス @n PORT ポート指定クラス: @n class port { @n public: @n void scl_dir(bool val) const { } @n void scl_out(bool val) const { } @n bool scl_inp() const { return 0; } @n void sda_dir(bool val) const { } @n void sda_out(bool val) const { } @n bool sda_inp() const { return 0; } @n }; @param[in] PORT ポート定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class PORT> class eeprom_io { static const uint8_t EEPROM_ADR_ = 0x50; i2c_io<PORT>& i2c_io_; bool exp_; uint8_t pagen_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] i2c i2c_io クラスを参照で渡す */ //-----------------------------------------------------------------// eeprom_io(i2c_io<PORT>& i2c) : i2c_io_(i2c), exp_(false) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] exp 「true」の場合、2バイトアドレス @param[in] pagen ページサイズ */ //-----------------------------------------------------------------// void start(bool exp, uint8_t pagen) { exp_ = exp; pagen_ = pagen; } //-----------------------------------------------------------------// /*! @brief EEPROM 読み出し @param[in] adr 読み出しアドレス @param[out] dst 先 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool read(uint32_t adr, uint8_t* dst, uint16_t len) const { if(exp_) { uint8_t tmp[2]; tmp[0] = (adr >> 8) & 255; tmp[1] = adr & 255; if(!i2c_io_.send(EEPROM_ADR_ | ((adr >> 16) & 7), tmp, 2)) { return false; } if(!i2c_io_.recv(EEPROM_ADR_ | ((adr >> 16) & 7), dst, len)) { return false; } } else { uint8_t tmp[1]; tmp[0] = adr & 255; if(!i2c_io_.send(EEPROM_ADR_ | ((adr >> 8) & 7), tmp, 1)) { return false; } if(!i2c_io_.recv(EEPROM_ADR_ | ((adr >> 16) & 7), dst, len)) { return false; } } return true; } //-----------------------------------------------------------------// /*! @brief EEPROM 書き込み @param[in] adr 書き込みアドレス @param[out] src 元 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool write(uint32_t adr, const uint8_t* src, uint16_t len) const { if(exp_) { if(!i2c_io_.send(EEPROM_ADR_ | ((adr >> 16) & 7), adr >> 8, adr & 255, src, len)) { return false; } } else { if(!i2c_io_.send(EEPROM_ADR_ | ((adr >> 8) & 7), adr & 255, src, len)) { return false; } } return true; } }; } <commit_msg>update write<commit_after>#pragma once //=====================================================================// /*! @file @brief EEPROM ドライバー @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> #include "common/i2c_io.hpp" #include "common/time.h" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief EEPROM テンプレートクラス @n PORT ポート指定クラス: @n class port { @n public: @n void scl_dir(bool val) const { } @n void scl_out(bool val) const { } @n bool scl_inp() const { return 0; } @n void sda_dir(bool val) const { } @n void sda_out(bool val) const { } @n bool sda_inp() const { return 0; } @n }; @param[in] PORT ポート定義クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class PORT> class eeprom_io { static const uint8_t EEPROM_ADR_ = 0x50; i2c_io<PORT>& i2c_io_; uint8_t ds_; bool exp_; uint8_t pagen_; uint8_t i2c_adr_(bool exta = 0) const { return EEPROM_ADR_ | ds_ | (static_cast<uint8_t>(exta) << 2); } public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] i2c i2c_io クラスを参照で渡す */ //-----------------------------------------------------------------// eeprom_io(i2c_io<PORT>& i2c) : i2c_io_(i2c), ds_(0), exp_(false), pagen_(1) { } //-----------------------------------------------------------------// /*! @brief 開始 @param[in] ds デバイス選択ビット @param[in] exp 「true」の場合、2バイトアドレス @param[in] pagen ページサイズ */ //-----------------------------------------------------------------// void start(uint8_t ds, bool exp, uint8_t pagen) { ds_ = ds & 7; exp_ = exp; pagen_ = pagen; } //-----------------------------------------------------------------// /*! @brief EEPROM 読み出し @param[in] adr 読み出しアドレス @param[out] dst 先 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool read(uint32_t adr, uint8_t* dst, uint16_t len) const { if(exp_) { uint8_t tmp[2]; tmp[0] = (adr >> 8) & 255; tmp[1] = adr & 255; if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), tmp, 2)) { return false; } if(!i2c_io_.recv(i2c_adr_((adr >> 16) & 1), dst, len)) { return false; } } else { uint8_t tmp[1]; tmp[0] = adr & 255; if(!i2c_io_.send(i2c_adr_(), tmp, 1)) { return false; } if(!i2c_io_.recv(i2c_adr_(), dst, len)) { return false; } } return true; } //-----------------------------------------------------------------// /*! @brief EEPROM 書き込み @param[in] adr 書き込みアドレス @param[out] src 元 @param[in] len 長さ @return 成功なら「true」 */ //-----------------------------------------------------------------// bool write(uint32_t adr, const uint8_t* src, uint16_t len) const { const uint8_t* end = src + len; while(src < end) { uint16_t l = pagen_ - static_cast<uint16_t>(src) & (pagen_ - 1); if(exp_) { if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), adr >> 8, adr & 255, src, l)) { return false; } } else { if(!i2c_io_.send(i2c_adr_((adr >> 16) & 1), adr & 255, src, l)) { return false; } } src += l; adr += l; if(src < end) { // 書き込み終了を待つポーリング bool ok = false; for(uint16_t i = 0; i < 600; ++i) { // 最大で6ms待つ utils::delay::micro_second(10); uint8_t tmp[1]; if(read(adr, tmp, 1)) { ok = true; break; } } if(!ok) return false; } } return true; } }; } <|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/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/pref_names.h" #include "net/base/mock_host_resolver.h" // Possible race in ChromeURLDataManager. http://crbug.com/59198 #if defined(OS_MACOSX) || defined(OS_LINUX) #define MAYBE_TabOnRemoved DISABLED_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif // Window resizes are not completed by the time the callback happens, // so these tests fail on linux. http://crbug.com/72369 #if defined(OS_LINUX) #define MAYBE_FocusWindowDoesNotExitFullscreen \ DISABLED_FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen \ DISABLED_UpdateWindowSizeExitsFullscreen #else #define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen #endif // In the touch build, this fails reliably. http://crbug.com/85191 #if defined(TOUCH_UI) #define MAYBE_GetViewsOfCreatedWindow DISABLED_GetViewsOfCreatedWindow #else #define MAYBE_GetViewsOfCreatedWindow GetViewsOfCreatedWindow #endif // In the touch build, this fails unreliably. http://crbug.com/85226 #if defined(TOUCH_UI) #define MAYBE_GetViewsOfCreatedPopup FLAKY_GetViewsOfCreatedPopup #else #define MAYBE_GetViewsOfCreatedPopup GetViewsOfCreatedPopup #endif // In the touch build, this fails reliably. http://crbug.com/85190 #if defined(TOUCH_UI) #define MAYBE_TabEvents DISABLED_TabEvents #else #define MAYBE_TabEvents TabEvents #endif // In the touch build, this fails unreliably. http://crbug.com/85193 #if defined(TOUCH_UI) #define MAYBE_TabMove FLAKY_TabMove #else #define MAYBE_TabMove TabMove #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs) { ASSERT_TRUE(StartTestServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs2) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud2.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabMove) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabEvents) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg #else #define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng #else #define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } // Times out on non-Windows. See http://crbug.com/80212 #if defined(OS_WIN) #define MAYBE_CaptureVisibleTabRace FLAKY_CaptureVisibleTabRace #else #define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_race.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleFile) { ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_file.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleNoFile) { ASSERT_TRUE(RunExtensionSubtestNoFileAccess("tabs/capture_visible_tab", "test_nofile.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_FocusWindowDoesNotExitFullscreen) { browser()->window()->SetFullscreen(true); bool is_fullscreen = browser()->window()->IsFullscreen(); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen()); } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowSizeExitsFullscreen) { browser()->window()->SetFullscreen(true); ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_; ASSERT_FALSE(browser()->window()->IsFullscreen()); } #if defined(OS_WIN) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) { gfx::NativeWindow window = browser()->window()->GetNativeHandle(); ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_TRUE(::IsZoomed(window)); } #endif // OS_WIN IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) { ASSERT_TRUE(StartTestServer()); browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false); // This makes sure that creating an incognito window fails due to pref // (policy) being set. ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViewsOfCreatedPopup) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViewsOfCreatedWindow) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html")) << message_; } <commit_msg>Disable ExtensionApiTest.FLAKY_CaptureVisibleTabRace because it times-out on XP.<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/extensions/extension_apitest.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/pref_names.h" #include "net/base/mock_host_resolver.h" // Possible race in ChromeURLDataManager. http://crbug.com/59198 #if defined(OS_MACOSX) || defined(OS_LINUX) #define MAYBE_TabOnRemoved DISABLED_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif // Window resizes are not completed by the time the callback happens, // so these tests fail on linux. http://crbug.com/72369 #if defined(OS_LINUX) #define MAYBE_FocusWindowDoesNotExitFullscreen \ DISABLED_FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen \ DISABLED_UpdateWindowSizeExitsFullscreen #else #define MAYBE_FocusWindowDoesNotExitFullscreen FocusWindowDoesNotExitFullscreen #define MAYBE_UpdateWindowSizeExitsFullscreen UpdateWindowSizeExitsFullscreen #endif // In the touch build, this fails reliably. http://crbug.com/85191 #if defined(TOUCH_UI) #define MAYBE_GetViewsOfCreatedWindow DISABLED_GetViewsOfCreatedWindow #else #define MAYBE_GetViewsOfCreatedWindow GetViewsOfCreatedWindow #endif // In the touch build, this fails unreliably. http://crbug.com/85226 #if defined(TOUCH_UI) #define MAYBE_GetViewsOfCreatedPopup FLAKY_GetViewsOfCreatedPopup #else #define MAYBE_GetViewsOfCreatedPopup GetViewsOfCreatedPopup #endif // In the touch build, this fails reliably. http://crbug.com/85190 #if defined(TOUCH_UI) #define MAYBE_TabEvents DISABLED_TabEvents #else #define MAYBE_TabEvents TabEvents #endif // In the touch build, this fails unreliably. http://crbug.com/85193 #if defined(TOUCH_UI) #define MAYBE_TabMove FLAKY_TabMove #else #define MAYBE_TabMove TabMove #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs) { ASSERT_TRUE(StartTestServer()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Tabs2) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crud2.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabPinned) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "pinned.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabMove) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "move.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabEvents) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "events.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabRelativeURLs) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "relative_urls.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCrashBrowser) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "crash.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabJpeg DISABLED_CaptureVisibleTabJpeg #else #define MAYBE_CaptureVisibleTabJpeg FLAKY_CaptureVisibleTabJpeg #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabJpeg) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } // Test is timing out on linux and cros and flaky on others. // See http://crbug.com/83876 #if defined(OS_LINUX) #define MAYBE_CaptureVisibleTabPng DISABLED_CaptureVisibleTabPng #else #define MAYBE_CaptureVisibleTabPng FLAKY_CaptureVisibleTabPng #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabPng) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } // Times out on non-Windows. See http://crbug.com/80212 #if defined(OS_WIN) #define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace #else #define MAYBE_CaptureVisibleTabRace DISABLED_CaptureVisibleTabRace #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_CaptureVisibleTabRace) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_race.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleFile) { ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_file.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleNoFile) { ASSERT_TRUE(RunExtensionSubtestNoFileAccess("tabs/capture_visible_tab", "test_nofile.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_FocusWindowDoesNotExitFullscreen) { browser()->window()->SetFullscreen(true); bool is_fullscreen = browser()->window()->IsFullscreen(); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_EQ(is_fullscreen, browser()->window()->IsFullscreen()); } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_UpdateWindowSizeExitsFullscreen) { browser()->window()->SetFullscreen(true); ASSERT_TRUE(RunExtensionTest("window_update/sizing")) << message_; ASSERT_FALSE(browser()->window()->IsFullscreen()); } #if defined(OS_WIN) IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FocusWindowDoesNotUnmaximize) { gfx::NativeWindow window = browser()->window()->GetNativeHandle(); ::SendMessage(window, WM_SYSCOMMAND, SC_MAXIMIZE, 0); ASSERT_TRUE(RunExtensionTest("window_update/focus")) << message_; ASSERT_TRUE(::IsZoomed(window)); } #endif // OS_WIN IN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabledByPref) { ASSERT_TRUE(StartTestServer()); browser()->profile()->GetPrefs()->SetBoolean(prefs::kIncognitoEnabled, false); // This makes sure that creating an incognito window fails due to pref // (policy) being set. ASSERT_TRUE(RunExtensionTest("tabs/incognito_disabled")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViewsOfCreatedPopup) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_popup.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_GetViewsOfCreatedWindow) { ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionSubtest("tabs/basics", "get_views_window.html")) << message_; } <|endoftext|>
<commit_before>#include "dcpdeclwidget.h" #include <QGraphicsLinearLayout> #include <QFile> #include <MSettingsLanguageParser> #include <MSettingsLanguageBinary> #include <MSettingsLanguageWidget> #include <MSettingsLanguageWidgetFactory> #include <MGConfDataStore> #include <MLabel> #include <dcpdebug.h> static const QString defaultPath = "/usr/lib/mcontrolpanel/uidescriptions/"; DcpDeclWidget::DcpDeclWidget(const QString& xmlPath) { QGraphicsLinearLayout* layout = new QGraphicsLinearLayout( Qt::Vertical, this); QString filePath = xmlPath.startsWith('/') ? xmlPath : defaultPath + xmlPath; QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { createErrorLabel( QString("Cannot find applet xml file %1").arg(filePath) ); return; } MSettingsLanguageParser parser; if (!parser.readFrom(file)) { createErrorLabel(QString("Error parsing the ui description %1") .arg(filePath)); return; } MSettingsLanguageBinary* binary = parser.createSettingsBinary(); if (!binary) { createErrorLabel(QString("Error parsing the ui description %1") .arg(filePath)); return; } QString gpath = binary->keys().first(); MGConfDataStore* datastore = 0; if (gpath.startsWith("/")) { // TODO this is only working when all keys are in same dir gpath = gpath.left(gpath.lastIndexOf("/")); datastore = new MGConfDataStore(gpath); } else { DCP_WARNING("Fix gconf key paths in your xml: %s", qPrintable(filePath)); } MSettingsLanguageWidget* widget = MSettingsLanguageWidgetFactory::createWidget(*binary, datastore ); Q_ASSERT(widget); layout->addItem(widget); } void DcpDeclWidget::createErrorLabel(const QString& text) { MLabel* label = new MLabel(this); label->setText("Error parsing the ui description, see log"); DCP_WARNING(qPrintable(text)); ((QGraphicsLinearLayout*)(layout()))->addItem(label); } <commit_msg>A little fix for declarative widgets<commit_after>#include "dcpdeclwidget.h" #include <QGraphicsLinearLayout> #include <QFile> #include <MSettingsLanguageParser> #include <MSettingsLanguageBinary> #include <MSettingsLanguageWidget> #include <MSettingsLanguageWidgetFactory> #include <MGConfDataStore> #include <MLabel> #include <dcpdebug.h> static const QString defaultPath = "/usr/lib/duicontrolpanel/uidescriptions/"; DcpDeclWidget::DcpDeclWidget(const QString& xmlPath) { QGraphicsLinearLayout* layout = new QGraphicsLinearLayout( Qt::Vertical, this); QString filePath = xmlPath.startsWith('/') ? xmlPath : defaultPath + xmlPath; QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { createErrorLabel( QString("Cannot find applet xml file %1").arg(filePath) ); return; } MSettingsLanguageParser parser; if (!parser.readFrom(file)) { createErrorLabel(QString("Error parsing the ui description %1") .arg(filePath)); return; } MSettingsLanguageBinary* binary = parser.createSettingsBinary(); if (!binary) { createErrorLabel(QString("Error parsing the ui description %1") .arg(filePath)); return; } QString gpath = binary->keys().first(); MGConfDataStore* datastore = 0; if (gpath.startsWith("/")) { // TODO this is only working when all keys are in same dir gpath = gpath.left(gpath.lastIndexOf("/")); datastore = new MGConfDataStore(gpath); } else { DCP_WARNING("Fix gconf key paths in your xml: %s", qPrintable(filePath)); } MSettingsLanguageWidget* widget = MSettingsLanguageWidgetFactory::createWidget(*binary, datastore ); Q_ASSERT(widget); layout->addItem(widget); } void DcpDeclWidget::createErrorLabel(const QString& text) { MLabel* label = new MLabel(this); label->setText("Error parsing the ui description, see log"); DCP_WARNING(qPrintable(text)); ((QGraphicsLinearLayout*)(layout()))->addItem(label); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: register.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2003-04-24 13:54:41 $ * * 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): _______________________________________ * * ************************************************************************/ //#include <rtl/unload.h> //#include <osl/time.h> #include "servprov.hxx" #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_ #include <com/sun/star/registry/InvalidRegistryException.hpp> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif using namespace ::com::sun::star; uno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance( const uno::Reference<lang::XMultiServiceFactory> & xSMgr) throw (uno::Exception) { uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr ); return xService; } ::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw() { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.ole.EmbedServer") ); } uno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw() { uno::Sequence< ::rtl::OUString > aServiceNames( 1 ); aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.OleEmbeddedServerRegistration" ) ); return aServiceNames; } extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) ); uno::Reference< lang::XSingleServiceFactory > xFactory; if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) ) { xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager), EmbedServer_getImplementationName(), EmbedServer_createInstance, EmbedServer_getSupportedServiceNames() ); } if (xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if (pRegistryKey) { try { uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) ); uno::Reference< registry::XRegistryKey > xNewKey; xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + EmbedServer_getImplementationName() + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ); uno::Sequence< ::rtl::OUString > &rServices = EmbedServer_getSupportedServiceNames(); for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ ) xNewKey->createKey( rServices.getConstArray()[ind] ); return sal_True; } catch (registry::InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return sal_False; } } // extern "C" <commit_msg>INTEGRATION: CWS ooo19126 (1.2.92); FILE MERGED 2005/09/05 18:46:12 rt 1.2.92.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: register.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:53:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //#include <rtl/unload.h> //#include <osl/time.h> #include "servprov.hxx" #ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_ #include <com/sun/star/lang/XSingleServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_ #include <com/sun/star/registry/InvalidRegistryException.hpp> #endif #ifndef _RTL_USTRING_ #include <rtl/ustring> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif using namespace ::com::sun::star; uno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance( const uno::Reference<lang::XMultiServiceFactory> & xSMgr) throw (uno::Exception) { uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr ); return xService; } ::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw() { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.ole.EmbedServer") ); } uno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw() { uno::Sequence< ::rtl::OUString > aServiceNames( 1 ); aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.OleEmbeddedServerRegistration" ) ); return aServiceNames; } extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) ); uno::Reference< lang::XSingleServiceFactory > xFactory; if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) ) { xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager), EmbedServer_getImplementationName(), EmbedServer_createInstance, EmbedServer_getSupportedServiceNames() ); } if (xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if (pRegistryKey) { try { uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) ); uno::Reference< registry::XRegistryKey > xNewKey; xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + EmbedServer_getImplementationName() + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ); uno::Sequence< ::rtl::OUString > &rServices = EmbedServer_getSupportedServiceNames(); for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ ) xNewKey->createKey( rServices.getConstArray()[ind] ); return sal_True; } catch (registry::InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return sal_False; } } // extern "C" <|endoftext|>
<commit_before>#include "init.hpp" #include <iterator> #include <sstream> #include "ExactMatchRule" using namespace sprout; BOOST_AUTO_TEST_CASE(checkDirectMatch) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Cat"); auto cursor = makeCursor<char>(str); auto tokens = rule.parse(cursor); BOOST_REQUIRE(tokens); BOOST_CHECK_EQUAL("Animal", *tokens); } BOOST_AUTO_TEST_CASE(checkBadMatch) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Dog"); auto cursor = makeCursor<char>(str); BOOST_CHECK(!rule.parse(cursor)); } BOOST_AUTO_TEST_CASE(checkPreemptedMatch) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Ca"); auto cursor = makeCursor<char>(str); BOOST_CHECK(!rule.parse(cursor)); } BOOST_AUTO_TEST_CASE(checkMatchWithTrailing) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Catca"); auto cursor = makeCursor<char>(str); BOOST_CHECK_EQUAL("Animal", *rule.parse(cursor)); } BOOST_AUTO_TEST_CASE(checkIteratorAtNextElementWhenMatchIsGood) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Catde"); auto cursor = makeCursor<char>(str); BOOST_CHECK(true); for (auto i = cursor; i; ++i) { std::cout << *i << std::endl; } BOOST_CHECK(true); auto tokens = rule.parse(cursor); BOOST_REQUIRE(tokens); BOOST_CHECK_EQUAL("Animal", *tokens); BOOST_CHECK_EQUAL('d', *cursor); } BOOST_AUTO_TEST_CASE(checkIteratorAtFirstElementIfMatchFails) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Calf"); auto cursor = makeCursor<char>(str); rule.parse(cursor); BOOST_CHECK_EQUAL('C', *cursor); ExactMatchRule<char, std::string> calfRule; calfRule.setTarget("Calf"); calfRule.setToken("Part"); BOOST_CHECK_EQUAL("Part", *calfRule.parse(cursor)); BOOST_CHECK(!cursor); } // vim: set ts=4 sw=4 : <commit_msg>Ensure rules can use other rules as input<commit_after>#include "init.hpp" #include <iterator> #include <sstream> #include "ExactMatchRule" using namespace sprout; BOOST_AUTO_TEST_CASE(checkDirectMatch) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Cat"); auto cursor = makeCursor<char>(str); auto tokens = rule.parse(cursor); BOOST_REQUIRE(tokens); BOOST_CHECK_EQUAL("Animal", *tokens); } BOOST_AUTO_TEST_CASE(checkBadMatch) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Dog"); auto cursor = makeCursor<char>(str); BOOST_CHECK(!rule.parse(cursor)); } BOOST_AUTO_TEST_CASE(checkPreemptedMatch) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Ca"); auto cursor = makeCursor<char>(str); BOOST_CHECK(!rule.parse(cursor)); } BOOST_AUTO_TEST_CASE(checkMatchWithTrailing) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Catca"); auto cursor = makeCursor<char>(str); BOOST_CHECK_EQUAL("Animal", *rule.parse(cursor)); } BOOST_AUTO_TEST_CASE(checkIteratorAtNextElementWhenMatchIsGood) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Catde"); auto cursor = makeCursor<char>(str); BOOST_CHECK(true); for (auto i = cursor; i; ++i) { std::cout << *i << std::endl; } BOOST_CHECK(true); auto tokens = rule.parse(cursor); BOOST_REQUIRE(tokens); BOOST_CHECK_EQUAL("Animal", *tokens); BOOST_CHECK_EQUAL('d', *cursor); } BOOST_AUTO_TEST_CASE(checkIteratorAtFirstElementIfMatchFails) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Calf"); auto cursor = makeCursor<char>(str); rule.parse(cursor); BOOST_CHECK_EQUAL('C', *cursor); ExactMatchRule<char, std::string> calfRule; calfRule.setTarget("Calf"); calfRule.setToken("Part"); BOOST_CHECK_EQUAL("Part", *calfRule.parse(cursor)); BOOST_CHECK(!cursor); } BOOST_AUTO_TEST_CASE(rulesCanBeNested) { ExactMatchRule<char, std::string> rule; rule.setTarget("Cat"); rule.setToken("Animal"); std::stringstream str("Cat"); auto cursor = makeCursor<char>(str); auto tokens = rule.parse(cursor); Cursor<decltype(tokens)> tokenCursor(tokens); BOOST_CHECK_EQUAL(std::string("Animal"), *tokenCursor); } // vim: set ts=4 sw=4 : <|endoftext|>
<commit_before>#include "drivers/h3lis331dl.hpp" #include "unit_config.hpp" #include "chprintf.h" void H3LIS331DL::init() { // Configure (DS p. 24-28) txbuf[0] = h3lis331dl::CTRL_REG1 | (1<<6); // Auto-increment write address txbuf[1] = 0b00111111; // PM: normal mode, DR: 1000Hz, XYZ: enabled txbuf[2] = 0b00000000; // Defaults txbuf[3] = 0b00000000; // Defaults txbuf[4] = 0b11000000; // BDU: on, BLE: data MSB at lower addr, FS: 100g txbuf[5] = 0b00000011; // Turned on exchange(6); } AccelerometerReading H3LIS331DL::readAccel() { AccelerometerReading reading; // Poll status // TODO(yoos): Do something useful with this txbuf[0] = h3lis331dl::STATUS_REG | (1<<7); exchange(2); uint8_t status = rxbuf[1]; // Poll accel txbuf[0] = h3lis331dl::OUT_X_L | (1<<7) | (1<<6); // Auto-increment read address exchange(7); reading.axes[0] = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2]))/16 * 0.049 + accOffsets[0]; reading.axes[1] = ((int16_t) ((rxbuf[3]<<8) | rxbuf[4]))/16 * 0.049 + accOffsets[1]; reading.axes[2] = ((int16_t) ((rxbuf[5]<<8) | rxbuf[6]))/16 * 0.049 + accOffsets[2]; // DEBUG //BaseSequentialStream* chp = (BaseSequentialStream*)&SD4; //static int i=0; //if ((i++)%10 == 0) { // chprintf(chp, "H3: %8f %8f %8f\r\n", reading.axes[0], reading.axes[1], reading.axes[2]); //} return reading; } bool H3LIS331DL::healthy() { txbuf[0] = h3lis331dl::WHO_AM_I | (1<<7); txbuf[1] = 0x00; exchange(2); if (rxbuf[1] != 0x32) { return false; } return true; } <commit_msg>Flip X and Y on high-g accelerometer driver.<commit_after>#include "drivers/h3lis331dl.hpp" #include "unit_config.hpp" #include "chprintf.h" void H3LIS331DL::init() { // Configure (DS p. 24-28) txbuf[0] = h3lis331dl::CTRL_REG1 | (1<<6); // Auto-increment write address txbuf[1] = 0b00111111; // PM: normal mode, DR: 1000Hz, XYZ: enabled txbuf[2] = 0b00000000; // Defaults txbuf[3] = 0b00000000; // Defaults txbuf[4] = 0b11000000; // BDU: on, BLE: data MSB at lower addr, FS: 100g txbuf[5] = 0b00000011; // Turned on exchange(6); } AccelerometerReading H3LIS331DL::readAccel() { AccelerometerReading reading; // Poll status // TODO(yoos): Do something useful with this txbuf[0] = h3lis331dl::STATUS_REG | (1<<7); exchange(2); uint8_t status = rxbuf[1]; // Poll accel txbuf[0] = h3lis331dl::OUT_X_L | (1<<7) | (1<<6); // Auto-increment read address exchange(7); reading.axes[0] = -((int16_t) ((rxbuf[1]<<8) | rxbuf[2]))/16 * 0.049 + accOffsets[0]; reading.axes[1] = -((int16_t) ((rxbuf[3]<<8) | rxbuf[4]))/16 * 0.049 + accOffsets[1]; reading.axes[2] = ((int16_t) ((rxbuf[5]<<8) | rxbuf[6]))/16 * 0.049 + accOffsets[2]; // DEBUG //BaseSequentialStream* chp = (BaseSequentialStream*)&SD4; //static int i=0; //if ((i++)%10 == 0) { // chprintf(chp, "H3: %8f %8f %8f\r\n", reading.axes[0], reading.axes[1], reading.axes[2]); //} return reading; } bool H3LIS331DL::healthy() { txbuf[0] = h3lis331dl::WHO_AM_I | (1<<7); txbuf[1] = 0x00; exchange(2); if (rxbuf[1] != 0x32) { return false; } return true; } <|endoftext|>
<commit_before>/* Sirikata Kernel -- Task scheduling system * Time.cpp * * Copyright (c) 2008, Patrick Reiter Horn * 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 Sirikata 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 "util/Standard.hh" #include "Time.hpp" #ifndef _WIN32 #include <sys/time.h> #endif #include <stdlib.h> #ifdef _WIN32 #include <windows.h> // probably something like this function Sirikata::Task::AbsTime Sirikata::Task::AbsTime::now() { FILETIME ft; GetSystemTimeAsFileTime(&ft); ULARGE_INTEGER uli; uli.LowPart = ft.dwLowDateTime; uli.HighPart = ft.dwHighDateTime; __int64 time64 = uli.QuadPart; return AbsTime(((double)time64)/10000000); // 100-nanosecond. } #else Sirikata::Task::AbsTime Sirikata::Task::AbsTime::now() { struct timeval tv = {0, 0}; gettimeofday(&tv, NULL); return AbsTime((double)tv.tv_sec + ((double)tv.tv_usec)/1000000); } #endif <commit_msg>Windows silently switches the FPU into single precision mode as soon as DX loads, so therefore the simple time computation fails. We should switch to int64's soon anyway to preserve time stamps across servers and make serialization nice and lossless<commit_after>/* Sirikata Kernel -- Task scheduling system * Time.cpp * * Copyright (c) 2008, Patrick Reiter Horn * 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 Sirikata 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 "util/Standard.hh" #include "Time.hpp" #ifndef _WIN32 #include <sys/time.h> #endif #include <stdlib.h> #ifdef _WIN32 #include <windows.h> // probably something like this function Sirikata::Task::AbsTime Sirikata::Task::AbsTime::now() { FILETIME ft; GetSystemTimeAsFileTime(&ft); ULARGE_INTEGER uli; uli.LowPart = ft.dwLowDateTime; uli.HighPart = ft.dwHighDateTime; ULONGLONG time64 = uli.QuadPart; ULONGLONG wholeTime= time64/10000000-12884268218;//HACK until we switch officially to int64's ULONGLONG partTime=time64%10000000; double doubleTime=wholeTime; doubleTime+=partTime/10000000.; return AbsTime(doubleTime); // 100-nanosecond. } #else Sirikata::Task::AbsTime Sirikata::Task::AbsTime::now() { struct timeval tv = {0, 0}; gettimeofday(&tv, NULL); return AbsTime((double)tv.tv_sec + ((double)tv.tv_usec)/1000000); } #endif <|endoftext|>
<commit_before>// Copyright 2021 The CFU-Playground Authors // // 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 "tflite.h" #include "perf.h" #include "playground_util/random.h" #include "proj_tflite.h" #include "tensorflow/lite/micro/all_ops_resolver.h" #include "tensorflow/lite/micro/micro_error_reporter.h" #include "tensorflow/lite/micro/micro_interpreter.h" #include "tensorflow/lite/micro/micro_mutable_op_resolver.h" #include "tensorflow/lite/micro/micro_profiler.h" #include "tensorflow/lite/schema/schema_generated.h" #ifdef TF_LITE_SHOW_MEMORY_USE #include "tensorflow/lite/micro/recording_micro_interpreter.h" #define INTERPRETER_TYPE RecordingMicroInterpreter #else #define INTERPRETER_TYPE MicroInterpreter #endif // For C++ exceptions void* __dso_handle = &__dso_handle; // // TfLM global objects namespace { tflite::ErrorReporter* error_reporter = nullptr; tflite::MicroOpResolver* op_resolver = nullptr; tflite::MicroProfiler* profiler = nullptr; const tflite::Model* model = nullptr; tflite::INTERPRETER_TYPE* interpreter = nullptr; // C++ 11 does not have a constexpr std::max. // For this reason, a small implementation is written. template <typename T> constexpr T const& const_max(const T& x) { return x; } template <typename T, typename... Args> constexpr T const& const_max(const T& x, const T& y, const Args&... rest) { return const_max(x > y ? x : y, rest...); } // Get the smallest kTensorArenaSize possible. constexpr int kTensorArenaSize = const_max<int>( #ifdef INCLUDE_MODEL_PDTI8 81 * 1024, #endif #ifdef INCLUDE_MODEL_MICRO_SPEECH 7 * 1024, #endif #ifdef INCLUDE_MODEL_MAGIC_WAND 5 * 1024, #endif #ifdef INCLUDE_MODEL_MNV2 800 * 1024, #endif #ifdef INCLUDE_MODEL_HPS 1024 * 1024, #endif #ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_ANOMD 3 * 1024, #endif #ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_IMGC 53 * 1024, #endif #ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_KWS 23 * 1024, #endif #ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_VWW 99 * 1024, #endif 0 /* When no models defined, we don't need a tensor arena. */ ); static uint8_t tensor_arena[kTensorArenaSize]; } // anonymous namespace static void tflite_init() { static bool initialized = false; if (initialized) { return; } initialized = true; // Sets up error reporting etc static tflite::MicroErrorReporter micro_error_reporter; error_reporter = &micro_error_reporter; TF_LITE_REPORT_ERROR(error_reporter, "Error_reporter OK!"); // Pull in only the operation implementations we need. // This relies on a complete list of all the ops needed by this graph. // An easier approach is to just use the AllOpsResolver, but this will // incur some penalty in code space for op implementations that are not // needed by this graph. // static tflite::AllOpsResolver resolver; op_resolver = &resolver; // // NOLINTNEXTLINE(runtime-global-variables) // static tflite::MicroMutableOpResolver<8> micro_op_resolver; // micro_op_resolver.AddAveragePool2D(); // micro_op_resolver.AddConv2D(); // micro_op_resolver.AddDepthwiseConv2D(); // micro_op_resolver.AddReshape(); // micro_op_resolver.AddSoftmax(); // // needed for jon's model conv2d/relu, maxpool2d, reshape, fullyconnected, // logistic micro_op_resolver.AddMaxPool2D(); // micro_op_resolver.AddFullyConnected(); // micro_op_resolver.AddLogistic(); // // needed for MODEL=magic_wand_full_i8 // // micro_op_resolver.AddQuantize(); // op_resolver = &micro_op_resolver; // profiler static tflite::MicroProfiler micro_profiler; profiler = &micro_profiler; } void tflite_load_model(const unsigned char* model_data, unsigned int model_length) { tflite_init(); tflite_preload(model_data, model_length); if (interpreter) { interpreter->~INTERPRETER_TYPE(); interpreter = nullptr; } // Map the model into a usable data structure. This doesn't involve any // copying or parsing, it's a very lightweight operation. model = tflite::GetModel(model_data); // Build an interpreter to run the model with. // NOLINTNEXTLINE(runtime-global-variables) alignas(tflite::INTERPRETER_TYPE) static unsigned char buf[sizeof(tflite::INTERPRETER_TYPE)]; interpreter = new (buf) tflite::INTERPRETER_TYPE(model, *op_resolver, tensor_arena, kTensorArenaSize, error_reporter, profiler); // Allocate memory from the tensor_arena for the model's tensors. TfLiteStatus allocate_status = interpreter->AllocateTensors(); if (allocate_status != kTfLiteOk) { TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed"); return; } #ifdef TF_LITE_SHOW_MEMORY_USE interpreter->GetMicroAllocator().PrintAllocations(); #endif // Get information about the memory area to use for the model's input. auto input = interpreter->input(0); auto dims = input->dims; printf("Input: %d bytes, %d dims:", input->bytes, dims->size); for (int ii = 0; ii < dims->size; ++ii) { printf(" %d", dims->data[ii]); } puts("\n"); } void tflite_set_input_zeros(void) { auto input = interpreter->input(0); memset(input->data.int8, 0, input->bytes); printf("Zeroed %d bytes at 0x%p\n", input->bytes, input->data.int8); } void tflite_set_input_zeros_float() { auto input = interpreter->input(0); memset(input->data.f, 0, input->bytes); printf("Zeroed %d bytes at 0x%p\n", input->bytes, input->data.f); } void tflite_set_input(const void* data) { auto input = interpreter->input(0); memcpy(input->data.int8, data, input->bytes); printf("Copied %d bytes at 0x%p\n", input->bytes, input->data.int8); } void tflite_set_input_unsigned(const unsigned char* data) { auto input = interpreter->input(0); for (size_t i = 0; i < input->bytes; i++) { input->data.int8[i] = (int)data[i] - 127; } printf("Set %d bytes at 0x%p\n", input->bytes, input->data.int8); } void tflite_set_input_float(const float* data) { auto input = interpreter->input(0); memcpy(input->data.f, data, input->bytes); printf("Copied %d bytes at 0x%p\n", input->bytes, input->data.f); } void tflite_randomize_input(int64_t seed) { int64_t r = seed; auto input = interpreter->input(0); for (size_t i = 0; i < input->bytes; i++) { input->data.int8[i] = static_cast<int8_t>(next_pseudo_random(&r)); } printf("Set %d bytes at 0x%p\n", input->bytes, input->data.int8); } void tflite_set_grid_input(void) { auto input = interpreter->input(0); size_t height = input->dims->data[1]; size_t width = input->dims->data[2]; for (size_t y = 0; y < height; y++) { for (size_t x = 0; x < width; x++) { int8_t val = (y & 0x20) & (x & 0x20) ? -128 : 127; input->data.int8[x + y * width] = val; } } printf("Set %d bytes at 0x%p\n", input->bytes, input->data.int8); } int8_t* tflite_get_output() { return interpreter->output(0)->data.int8; } float* tflite_get_output_float() { return interpreter->output(0)->data.f; } void tflite_classify() { // Run the model on this input and make sure it succeeds. profiler->ClearEvents(); perf_reset_all_counters(); perf_set_mcycle(0); if (kTfLiteOk != interpreter->Invoke()) { puts("Invoke failed."); } unsigned int cyc = perf_get_mcycle(); #ifndef NPROFILE profiler->Log(); #endif perf_print_all_counters(); perf_print_value(cyc); printf(" cycles total\n"); } int8_t* get_input() { return interpreter->input(0)->data.int8; } <commit_msg>Avoid usage of perf_set_mcycle in tflite.cc because not all boards support it.<commit_after>// Copyright 2021 The CFU-Playground Authors // // 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 "tflite.h" #include <cstdint> #include "perf.h" #include "playground_util/random.h" #include "proj_tflite.h" #include "tensorflow/lite/micro/all_ops_resolver.h" #include "tensorflow/lite/micro/micro_error_reporter.h" #include "tensorflow/lite/micro/micro_interpreter.h" #include "tensorflow/lite/micro/micro_mutable_op_resolver.h" #include "tensorflow/lite/micro/micro_profiler.h" #include "tensorflow/lite/schema/schema_generated.h" #ifdef TF_LITE_SHOW_MEMORY_USE #include "tensorflow/lite/micro/recording_micro_interpreter.h" #define INTERPRETER_TYPE RecordingMicroInterpreter #else #define INTERPRETER_TYPE MicroInterpreter #endif // For C++ exceptions void* __dso_handle = &__dso_handle; // // TfLM global objects namespace { tflite::ErrorReporter* error_reporter = nullptr; tflite::MicroOpResolver* op_resolver = nullptr; tflite::MicroProfiler* profiler = nullptr; const tflite::Model* model = nullptr; tflite::INTERPRETER_TYPE* interpreter = nullptr; // C++ 11 does not have a constexpr std::max. // For this reason, a small implementation is written. template <typename T> constexpr T const& const_max(const T& x) { return x; } template <typename T, typename... Args> constexpr T const& const_max(const T& x, const T& y, const Args&... rest) { return const_max(x > y ? x : y, rest...); } // Get the smallest kTensorArenaSize possible. constexpr int kTensorArenaSize = const_max<int>( #ifdef INCLUDE_MODEL_PDTI8 81 * 1024, #endif #ifdef INCLUDE_MODEL_MICRO_SPEECH 7 * 1024, #endif #ifdef INCLUDE_MODEL_MAGIC_WAND 5 * 1024, #endif #ifdef INCLUDE_MODEL_MNV2 800 * 1024, #endif #ifdef INCLUDE_MODEL_HPS 1024 * 1024, #endif #ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_ANOMD 3 * 1024, #endif #ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_IMGC 53 * 1024, #endif #ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_KWS 23 * 1024, #endif #ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_VWW 99 * 1024, #endif 0 /* When no models defined, we don't need a tensor arena. */ ); static uint8_t tensor_arena[kTensorArenaSize]; } // anonymous namespace static void tflite_init() { static bool initialized = false; if (initialized) { return; } initialized = true; // Sets up error reporting etc static tflite::MicroErrorReporter micro_error_reporter; error_reporter = &micro_error_reporter; TF_LITE_REPORT_ERROR(error_reporter, "Error_reporter OK!"); // Pull in only the operation implementations we need. // This relies on a complete list of all the ops needed by this graph. // An easier approach is to just use the AllOpsResolver, but this will // incur some penalty in code space for op implementations that are not // needed by this graph. // static tflite::AllOpsResolver resolver; op_resolver = &resolver; // // NOLINTNEXTLINE(runtime-global-variables) // static tflite::MicroMutableOpResolver<8> micro_op_resolver; // micro_op_resolver.AddAveragePool2D(); // micro_op_resolver.AddConv2D(); // micro_op_resolver.AddDepthwiseConv2D(); // micro_op_resolver.AddReshape(); // micro_op_resolver.AddSoftmax(); // // needed for jon's model conv2d/relu, maxpool2d, reshape, fullyconnected, // logistic micro_op_resolver.AddMaxPool2D(); // micro_op_resolver.AddFullyConnected(); // micro_op_resolver.AddLogistic(); // // needed for MODEL=magic_wand_full_i8 // // micro_op_resolver.AddQuantize(); // op_resolver = &micro_op_resolver; // profiler static tflite::MicroProfiler micro_profiler; profiler = &micro_profiler; } void tflite_load_model(const unsigned char* model_data, unsigned int model_length) { tflite_init(); tflite_preload(model_data, model_length); if (interpreter) { interpreter->~INTERPRETER_TYPE(); interpreter = nullptr; } // Map the model into a usable data structure. This doesn't involve any // copying or parsing, it's a very lightweight operation. model = tflite::GetModel(model_data); // Build an interpreter to run the model with. // NOLINTNEXTLINE(runtime-global-variables) alignas(tflite::INTERPRETER_TYPE) static unsigned char buf[sizeof(tflite::INTERPRETER_TYPE)]; interpreter = new (buf) tflite::INTERPRETER_TYPE(model, *op_resolver, tensor_arena, kTensorArenaSize, error_reporter, profiler); // Allocate memory from the tensor_arena for the model's tensors. TfLiteStatus allocate_status = interpreter->AllocateTensors(); if (allocate_status != kTfLiteOk) { TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed"); return; } #ifdef TF_LITE_SHOW_MEMORY_USE interpreter->GetMicroAllocator().PrintAllocations(); #endif // Get information about the memory area to use for the model's input. auto input = interpreter->input(0); auto dims = input->dims; printf("Input: %d bytes, %d dims:", input->bytes, dims->size); for (int ii = 0; ii < dims->size; ++ii) { printf(" %d", dims->data[ii]); } puts("\n"); } void tflite_set_input_zeros(void) { auto input = interpreter->input(0); memset(input->data.int8, 0, input->bytes); printf("Zeroed %d bytes at 0x%p\n", input->bytes, input->data.int8); } void tflite_set_input_zeros_float() { auto input = interpreter->input(0); memset(input->data.f, 0, input->bytes); printf("Zeroed %d bytes at 0x%p\n", input->bytes, input->data.f); } void tflite_set_input(const void* data) { auto input = interpreter->input(0); memcpy(input->data.int8, data, input->bytes); printf("Copied %d bytes at 0x%p\n", input->bytes, input->data.int8); } void tflite_set_input_unsigned(const unsigned char* data) { auto input = interpreter->input(0); for (size_t i = 0; i < input->bytes; i++) { input->data.int8[i] = (int)data[i] - 127; } printf("Set %d bytes at 0x%p\n", input->bytes, input->data.int8); } void tflite_set_input_float(const float* data) { auto input = interpreter->input(0); memcpy(input->data.f, data, input->bytes); printf("Copied %d bytes at 0x%p\n", input->bytes, input->data.f); } void tflite_randomize_input(int64_t seed) { int64_t r = seed; auto input = interpreter->input(0); for (size_t i = 0; i < input->bytes; i++) { input->data.int8[i] = static_cast<int8_t>(next_pseudo_random(&r)); } printf("Set %d bytes at 0x%p\n", input->bytes, input->data.int8); } void tflite_set_grid_input(void) { auto input = interpreter->input(0); size_t height = input->dims->data[1]; size_t width = input->dims->data[2]; for (size_t y = 0; y < height; y++) { for (size_t x = 0; x < width; x++) { int8_t val = (y & 0x20) & (x & 0x20) ? -128 : 127; input->data.int8[x + y * width] = val; } } printf("Set %d bytes at 0x%p\n", input->bytes, input->data.int8); } int8_t* tflite_get_output() { return interpreter->output(0)->data.int8; } float* tflite_get_output_float() { return interpreter->output(0)->data.f; } void tflite_classify() { // Run the model on this input and make sure it succeeds. profiler->ClearEvents(); perf_reset_all_counters(); // perf_set_mcycle is a no-op for some boards, start and end used instead. uint32_t start = perf_get_mcycle(); if (kTfLiteOk != interpreter->Invoke()) { puts("Invoke failed."); } uint32_t end = perf_get_mcycle(); #ifndef NPROFILE profiler->Log(); #endif perf_print_all_counters(); perf_print_value(end - start); // Possible overflow is intentional here. printf(" cycles total\n"); } int8_t* get_input() { return interpreter->input(0)->data.int8; } <|endoftext|>
<commit_before>// @(#)root/tmva $Id$ // Author: Attila Krasznahorkay /********************************************************************************** * Project: TMVA - a Root-integrated toolkit for multivariate data analysis * * Package: TMVA * * Class : MsgLogger * * Web : http://tmva.sourceforge.net * * * * Description: * * Implementation (see header for description) * * * * Author: * * Attila Krasznahorkay <Attila.Krasznahorkay@cern.ch> - CERN, Switzerland * * * * Copyright (c) 2005: * * CERN, Switzerland * * MPI-K Heidelberg, Germany * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in LICENSE * * (http://tmva.sourceforge.net/LICENSE) * **********************************************************************************/ // Local include(s): #include "TMVA/MsgLogger.h" #include "TMVA/Config.h" // STL include(s): #include <iomanip> #include <cstdlib> // ROOT include(s): ClassImp(TMVA::MsgLogger) // this is the hard-coded maximum length of the source names UInt_t TMVA::MsgLogger::fgMaxSourceSize = 25; Bool_t TMVA::MsgLogger::fgInhibitOutput = kFALSE; const std::string TMVA::MsgLogger::fgPrefix="--- "; const std::string TMVA::MsgLogger::fgSuffix=": "; std::map<TMVA::EMsgType, std::string> TMVA::MsgLogger::fgTypeMap=std::map<TMVA::EMsgType, std::string>(); std::map<TMVA::EMsgType, std::string> TMVA::MsgLogger::fgColorMap=std::map<TMVA::EMsgType, std::string>(); void TMVA::MsgLogger::InhibitOutput() { fgInhibitOutput = kTRUE; } void TMVA::MsgLogger::EnableOutput() { fgInhibitOutput = kFALSE; } //_______________________________________________________________________ TMVA::MsgLogger::MsgLogger( const TObject* source, EMsgType minType ) : fObjSource ( source ), fStrSource ( "" ), fActiveType( kINFO ), fMinType ( minType ) { // constructor } //_______________________________________________________________________ TMVA::MsgLogger::MsgLogger( const std::string& source, EMsgType minType ) : fObjSource ( 0 ), fStrSource ( source ), fActiveType( kINFO ), fMinType ( minType ) { // constructor } //_______________________________________________________________________ TMVA::MsgLogger::MsgLogger( EMsgType minType ) : fObjSource ( 0 ), fStrSource ( "Unknown" ), fActiveType( kINFO ), fMinType ( minType ) { // constructor } //_______________________________________________________________________ TMVA::MsgLogger::MsgLogger( const MsgLogger& parent ) : std::basic_ios<MsgLogger::char_type, MsgLogger::traits_type>(), std::ostringstream(), TObject() { // copy constructor *this = parent; } //_______________________________________________________________________ TMVA::MsgLogger::~MsgLogger() { // destructor } //_______________________________________________________________________ TMVA::MsgLogger& TMVA::MsgLogger::operator= ( const MsgLogger& parent ) { // assingment operator if (&parent != this) { fObjSource = parent.fObjSource; fStrSource = parent.fStrSource; fActiveType = parent.fActiveType; fMinType = parent.fMinType; } return *this; } //_______________________________________________________________________ std::string TMVA::MsgLogger::GetFormattedSource() const { // make sure the source name is no longer than fgMaxSourceSize: std::string source_name; if (fObjSource) source_name = fObjSource->GetName(); else source_name = fStrSource; if (source_name.size() > fgMaxSourceSize) { source_name = source_name.substr( 0, fgMaxSourceSize - 3 ); source_name += "..."; } return source_name; } //_______________________________________________________________________ std::string TMVA::MsgLogger::GetPrintedSource() const { // the full logger prefix std::string source_name = GetFormattedSource(); if (source_name.size() < fgMaxSourceSize) for (std::string::size_type i=source_name.size(); i<fgMaxSourceSize; i++) source_name.push_back( ' ' ); return fgPrefix + source_name + fgSuffix; } //_______________________________________________________________________ void TMVA::MsgLogger::Send() { // activates the logger writer // make sure the source name is no longer than fgMaxSourceSize: std::string source_name = GetFormattedSource(); std::string message = this->str(); std::string::size_type previous_pos = 0, current_pos = 0; // slice the message into lines: while (kTRUE) { current_pos = message.find( '\n', previous_pos ); std::string line = message.substr( previous_pos, current_pos - previous_pos ); std::ostringstream message_to_send; // must call the modifiers like this, otherwise g++ get's confused with the operators... message_to_send.setf( std::ios::adjustfield, std::ios::left ); message_to_send.width( fgMaxSourceSize ); message_to_send << source_name << fgSuffix << line; this->WriteMsg( fActiveType, message_to_send.str() ); if (current_pos == message.npos) break; previous_pos = current_pos + 1; } // reset the stream buffer: this->str( "" ); fActiveType = kINFO; // To always print messages that have no level specified... return; } //_______________________________________________________________________ void TMVA::MsgLogger::WriteMsg( EMsgType type, const std::string& line ) const { // putting the output string, the message type, and the color // switcher together into a single string if (type < fMinType || (fgInhibitOutput && type!=kFATAL)) return; // no output InitMaps(); std::map<EMsgType, std::string>::const_iterator stype; if ((stype = fgTypeMap.find( type )) == fgTypeMap.end()) return; if (!gConfig().IsSilent() || type==kFATAL) { if (gConfig().UseColor()) { // no text for INFO or VERBOSE if (type == kINFO || type == kVERBOSE) std::cout << fgPrefix << line << std::endl; // no color for info else std::cout << fgColorMap.find( type )->second << fgPrefix << "<" << stype->second << "> " << line << "\033[0m" << std::endl; } else { if (type == kINFO) std::cout << fgPrefix << line << std::endl; else std::cout << fgPrefix << "<" << stype->second << "> " << line << std::endl; } } // take decision to stop if fatal error if (type == kFATAL) { std::cout << "***> abort program execution" << std::endl; std::exit(1); } } //_______________________________________________________________________ TMVA::MsgLogger& TMVA::MsgLogger::Endmsg( MsgLogger& logger ) { // end line logger.Send(); return logger; } //_______________________________________________________________________ void TMVA::MsgLogger::InitMaps() { if (fgTypeMap.size()>0 && fgColorMap.size()>0 ) return; // fill maps that assign a string and a color to echo message level fgTypeMap[kVERBOSE] = std::string("VERBOSE"); fgTypeMap[kDEBUG] = std::string("DEBUG"); fgTypeMap[kINFO] = std::string("INFO"); fgTypeMap[kWARNING] = std::string("WARNING"); fgTypeMap[kERROR] = std::string("ERROR"); fgTypeMap[kFATAL] = std::string("FATAL"); fgTypeMap[kSILENT] = std::string("SILENT"); fgColorMap[kVERBOSE] = std::string(""); fgColorMap[kDEBUG] = std::string("\033[34m"); fgColorMap[kINFO] = std::string(""); fgColorMap[kWARNING] = std::string("\033[1;31m"); fgColorMap[kERROR] = std::string("\033[31m"); fgColorMap[kFATAL] = std::string("\033[37;41;1m"); fgColorMap[kSILENT] = std::string("\033[30m"); } <commit_msg>Exit at FATAL was masked in SILENCE mode<commit_after>// @(#)root/tmva $Id$ // Author: Attila Krasznahorkay /********************************************************************************** * Project: TMVA - a Root-integrated toolkit for multivariate data analysis * * Package: TMVA * * Class : MsgLogger * * Web : http://tmva.sourceforge.net * * * * Description: * * Implementation (see header for description) * * * * Author: * * Attila Krasznahorkay <Attila.Krasznahorkay@cern.ch> - CERN, Switzerland * * * * Copyright (c) 2005: * * CERN, Switzerland * * MPI-K Heidelberg, Germany * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in LICENSE * * (http://tmva.sourceforge.net/LICENSE) * **********************************************************************************/ // Local include(s): #include "TMVA/MsgLogger.h" #include "TMVA/Config.h" // STL include(s): #include <iomanip> #include <cstdlib> // ROOT include(s): ClassImp(TMVA::MsgLogger) // this is the hard-coded maximum length of the source names UInt_t TMVA::MsgLogger::fgMaxSourceSize = 25; Bool_t TMVA::MsgLogger::fgInhibitOutput = kFALSE; const std::string TMVA::MsgLogger::fgPrefix="--- "; const std::string TMVA::MsgLogger::fgSuffix=": "; std::map<TMVA::EMsgType, std::string> TMVA::MsgLogger::fgTypeMap=std::map<TMVA::EMsgType, std::string>(); std::map<TMVA::EMsgType, std::string> TMVA::MsgLogger::fgColorMap=std::map<TMVA::EMsgType, std::string>(); void TMVA::MsgLogger::InhibitOutput() { fgInhibitOutput = kTRUE; } void TMVA::MsgLogger::EnableOutput() { fgInhibitOutput = kFALSE; } //_______________________________________________________________________ TMVA::MsgLogger::MsgLogger( const TObject* source, EMsgType minType ) : fObjSource ( source ), fStrSource ( "" ), fActiveType( kINFO ), fMinType ( minType ) { // constructor } //_______________________________________________________________________ TMVA::MsgLogger::MsgLogger( const std::string& source, EMsgType minType ) : fObjSource ( 0 ), fStrSource ( source ), fActiveType( kINFO ), fMinType ( minType ) { // constructor } //_______________________________________________________________________ TMVA::MsgLogger::MsgLogger( EMsgType minType ) : fObjSource ( 0 ), fStrSource ( "Unknown" ), fActiveType( kINFO ), fMinType ( minType ) { // constructor } //_______________________________________________________________________ TMVA::MsgLogger::MsgLogger( const MsgLogger& parent ) : std::basic_ios<MsgLogger::char_type, MsgLogger::traits_type>(), std::ostringstream(), TObject() { // copy constructor *this = parent; } //_______________________________________________________________________ TMVA::MsgLogger::~MsgLogger() { // destructor } //_______________________________________________________________________ TMVA::MsgLogger& TMVA::MsgLogger::operator= ( const MsgLogger& parent ) { // assingment operator if (&parent != this) { fObjSource = parent.fObjSource; fStrSource = parent.fStrSource; fActiveType = parent.fActiveType; fMinType = parent.fMinType; } return *this; } //_______________________________________________________________________ std::string TMVA::MsgLogger::GetFormattedSource() const { // make sure the source name is no longer than fgMaxSourceSize: std::string source_name; if (fObjSource) source_name = fObjSource->GetName(); else source_name = fStrSource; if (source_name.size() > fgMaxSourceSize) { source_name = source_name.substr( 0, fgMaxSourceSize - 3 ); source_name += "..."; } return source_name; } //_______________________________________________________________________ std::string TMVA::MsgLogger::GetPrintedSource() const { // the full logger prefix std::string source_name = GetFormattedSource(); if (source_name.size() < fgMaxSourceSize) for (std::string::size_type i=source_name.size(); i<fgMaxSourceSize; i++) source_name.push_back( ' ' ); return fgPrefix + source_name + fgSuffix; } //_______________________________________________________________________ void TMVA::MsgLogger::Send() { // activates the logger writer // make sure the source name is no longer than fgMaxSourceSize: std::string source_name = GetFormattedSource(); std::string message = this->str(); std::string::size_type previous_pos = 0, current_pos = 0; // slice the message into lines: while (kTRUE) { current_pos = message.find( '\n', previous_pos ); std::string line = message.substr( previous_pos, current_pos - previous_pos ); std::ostringstream message_to_send; // must call the modifiers like this, otherwise g++ get's confused with the operators... message_to_send.setf( std::ios::adjustfield, std::ios::left ); message_to_send.width( fgMaxSourceSize ); message_to_send << source_name << fgSuffix << line; this->WriteMsg( fActiveType, message_to_send.str() ); if (current_pos == message.npos) break; previous_pos = current_pos + 1; } // reset the stream buffer: this->str( "" ); fActiveType = kINFO; // To always print messages that have no level specified... return; } //_______________________________________________________________________ void TMVA::MsgLogger::WriteMsg( EMsgType type, const std::string& line ) const { // putting the output string, the message type, and the color // switcher together into a single string if ( (type < fMinType || fgInhibitOutput) && type!=kFATAL ) return; // no output InitMaps(); std::map<EMsgType, std::string>::const_iterator stype; if ((stype = fgTypeMap.find( type )) == fgTypeMap.end()) return; if (!gConfig().IsSilent() || type==kFATAL) { if (gConfig().UseColor()) { // no text for INFO or VERBOSE if (type == kINFO || type == kVERBOSE) std::cout << fgPrefix << line << std::endl; // no color for info else std::cout << fgColorMap.find( type )->second << fgPrefix << "<" << stype->second << "> " << line << "\033[0m" << std::endl; } else { if (type == kINFO) std::cout << fgPrefix << line << std::endl; else std::cout << fgPrefix << "<" << stype->second << "> " << line << std::endl; } } // take decision to stop if fatal error if (type == kFATAL) { std::cout << "***> abort program execution" << std::endl; std::exit(1); } } //_______________________________________________________________________ TMVA::MsgLogger& TMVA::MsgLogger::Endmsg( MsgLogger& logger ) { // end line logger.Send(); return logger; } //_______________________________________________________________________ void TMVA::MsgLogger::InitMaps() { if (fgTypeMap.size()>0 && fgColorMap.size()>0 ) return; // fill maps that assign a string and a color to echo message level fgTypeMap[kVERBOSE] = std::string("VERBOSE"); fgTypeMap[kDEBUG] = std::string("DEBUG"); fgTypeMap[kINFO] = std::string("INFO"); fgTypeMap[kWARNING] = std::string("WARNING"); fgTypeMap[kERROR] = std::string("ERROR"); fgTypeMap[kFATAL] = std::string("FATAL"); fgTypeMap[kSILENT] = std::string("SILENT"); fgColorMap[kVERBOSE] = std::string(""); fgColorMap[kDEBUG] = std::string("\033[34m"); fgColorMap[kINFO] = std::string(""); fgColorMap[kWARNING] = std::string("\033[1;31m"); fgColorMap[kERROR] = std::string("\033[31m"); fgColorMap[kFATAL] = std::string("\033[37;41;1m"); fgColorMap[kSILENT] = std::string("\033[30m"); } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pelagicore AB * All rights reserved. */ #include <iostream> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <errno.h> #include <cstring> #include <stdio.h> #include <stdlib.h> #include "fifoipc.h" static const int BUF_SIZE = 1024; FifoIPC::FifoIPC(IPCMessage &message): m_message(message), m_fifoPath(""), m_fifoCreated(false) { } FifoIPC::~FifoIPC() { int ret = unlink(m_fifoPath.c_str()); if (ret == -1) { perror("unlink: "); } } bool FifoIPC::initialize(const std::string &fifoPath) { m_fifoPath = fifoPath; if (m_fifoCreated == false) { if (createFifo() == false) { std::cout << "Could not create FIFO!" << std::endl; return false; } } return loop(); } bool FifoIPC::loop() { int fd = open(m_fifoPath.c_str(), O_RDONLY); if (fd == -1) { perror("Error opening fifo: "); return false; } char buf[BUF_SIZE]; char c; bool shouldContinue = true; while (shouldContinue) { // Read next message in pipe, it should be null terminated int i = 0; do { int status = read(fd, &c, 1); if (status > 0) { buf[i++] = c; } // Look for end of message or end of storage buffer } while ((c != '\0') && (i != sizeof(buf) - 1)); buf[i] = '\0'; std::string messageString(buf); int status; shouldContinue = m_message.handleMessage(messageString, &status); if (status == -1) { // The message was not understood by IPCMessage std::cout << "Warning: IPC message to Controller was not sent" << std::endl; } } return true; } bool FifoIPC::createFifo() { int ret = mkfifo(m_fifoPath.c_str(), 0666); // All errors except for when fifo already exist are bad if ((ret == -1) && (errno != EEXIST)) { perror("Error creating fifo: "); return false; } m_fifoCreated = true; return true; } <commit_msg>fifoipc.cpp: Do not pass along empty messages to Controller.<commit_after>/* * Copyright (C) 2014 Pelagicore AB * All rights reserved. */ #include <iostream> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <errno.h> #include <cstring> #include <stdio.h> #include <stdlib.h> #include "fifoipc.h" static const int BUF_SIZE = 1024; FifoIPC::FifoIPC(IPCMessage &message): m_message(message), m_fifoPath(""), m_fifoCreated(false) { } FifoIPC::~FifoIPC() { int ret = unlink(m_fifoPath.c_str()); if (ret == -1) { perror("unlink: "); } } bool FifoIPC::initialize(const std::string &fifoPath) { m_fifoPath = fifoPath; if (m_fifoCreated == false) { if (createFifo() == false) { std::cout << "Could not create FIFO!" << std::endl; return false; } } return loop(); } bool FifoIPC::loop() { int fd = open(m_fifoPath.c_str(), O_RDONLY); if (fd == -1) { perror("FifoIPC open: "); return false; } char buf[BUF_SIZE]; char c; bool shouldContinue = true; while (shouldContinue) { // Read next message in pipe, it should be null terminated int i = 0; do { int status = read(fd, &c, 1); if (status > 0) { buf[i++] = c; } else if (status == 0) { // We've read 'end of file', just ignore it break; } else if (status == -1) { perror("FifoIPC read: "); return false; } else { std::cout << "Error: Unknown problem reading fifo" << std::endl; return false; } // Look for end of message or end of storage buffer } while ((c != '\0') && (i != sizeof(buf) - 1)); buf[i] = '\0'; std::string messageString(buf); int messageStatus = 0; // If message is empty we don't need to handle it if (messageString.size() > 0) shouldContinue = m_message.handleMessage(messageString, &messageStatus); if (messageStatus == -1) // The message was not understood by IPCMessage std::cout << "Warning: IPC message to Controller was not sent" << std::endl; } return true; } bool FifoIPC::createFifo() { int ret = mkfifo(m_fifoPath.c_str(), 0666); // All errors except for when fifo already exist are bad if ((ret == -1) && (errno != EEXIST)) { perror("Error creating fifo: "); return false; } m_fifoCreated = true; return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pelagicore AB * All rights reserved. */ #include <iostream> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include "errno.h" #include <cstring> #include "fifoipc.h" FifoIPC::FifoIPC(AbstractController *controller): m_controller(controller), m_fifoPath(""), m_fifo(0) { } FifoIPC::~FifoIPC() { int ret = unlink(m_fifoPath.c_str()); if (ret == -1) std::cout << "Error removing fifo!" << std::endl; } bool FifoIPC::initialize(const std::string &fifoPath) { m_fifoPath = fifoPath; if (m_fifo == 0) { bool created = createFifo(); if (!created) { std::cout << "Could not create FIFO!" << std::endl; return false; } } return loop(); } bool FifoIPC::loop() { int fd = open(m_fifoPath.c_str(), O_RDONLY); if (fd == -1) { perror("Error opening fifo: "); return false; } char buf[1024]; for (;;) { memset(buf, 0, sizeof(buf)); // Leave the last element for null termination int status = read(fd, buf, sizeof(buf)-1); if (status > 0) { std::cout << buf << std::endl; if (buf[0] == '1') { m_controller->runApp(); continue; } else if (buf[0] == '2') { m_controller->killApp(); // When app is shut down, we exit the loop and return // all the way back to main where we exit the program break; } else if (buf[0] == '\n') { // Ignore newlines continue; } else { buf[1023] = '\0'; m_controller->systemCall(std::string(buf)); } } } return true; } bool FifoIPC::createFifo() { int ret = mkfifo(m_fifoPath.c_str(), 0666); // All errors except for when fifo already exist are bad if ((ret == -1) && (errno != EEXIST)) { perror("Error creating fifo: "); return false; } m_fifo = 1; return true; } <commit_msg>fifoipc.cpp: Minor update. Changed to relative array indexing when null terminating char buffer.<commit_after>/* * Copyright (C) 2014 Pelagicore AB * All rights reserved. */ #include <iostream> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include "errno.h" #include <cstring> #include "fifoipc.h" FifoIPC::FifoIPC(AbstractController *controller): m_controller(controller), m_fifoPath(""), m_fifo(0) { } FifoIPC::~FifoIPC() { int ret = unlink(m_fifoPath.c_str()); if (ret == -1) std::cout << "Error removing fifo!" << std::endl; } bool FifoIPC::initialize(const std::string &fifoPath) { m_fifoPath = fifoPath; if (m_fifo == 0) { bool created = createFifo(); if (!created) { std::cout << "Could not create FIFO!" << std::endl; return false; } } return loop(); } bool FifoIPC::loop() { int fd = open(m_fifoPath.c_str(), O_RDONLY); if (fd == -1) { perror("Error opening fifo: "); return false; } char buf[1024]; for (;;) { memset(buf, 0, sizeof(buf)); // Leave the last element for null termination int status = read(fd, buf, sizeof(buf)-1); if (status > 0) { std::cout << buf << std::endl; if (buf[0] == '1') { m_controller->runApp(); continue; } else if (buf[0] == '2') { m_controller->killApp(); // When app is shut down, we exit the loop and return // all the way back to main where we exit the program break; } else if (buf[0] == '\n') { // Ignore newlines continue; } else { buf[sizeof(buf)-1] = '\0'; m_controller->systemCall(std::string(buf)); } } } return true; } bool FifoIPC::createFifo() { int ret = mkfifo(m_fifoPath.c_str(), 0666); // All errors except for when fifo already exist are bad if ((ret == -1) && (errno != EEXIST)) { perror("Error creating fifo: "); return false; } m_fifo = 1; return true; } <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQExpressionWidget.cpp,v $ // $Revision: 1.26 $ // $Name: $ // $Author: shoops $ // $Date: 2008/07/10 20:40:09 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <iostream> #include "CQExpressionWidget.h" #include "CQMessageBox.h" #include "CCopasiSelectionDialog.h" #include "qtUtilities.h" #include "copasi.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "function/CExpression.h" CQExpressionHighlighter::CQExpressionHighlighter(CQExpressionWidget* ew) : QSyntaxHighlighter(ew) {} int CQExpressionHighlighter::highlightParagraph (const QString & text, int /* endStateOfLastPara */) { int pos = 0; int oldpos = -1; int delta; while (true) { pos = text.find("<", pos); if (pos == -1) delta = 0; else delta = pos - oldpos - 1; setFormat(oldpos + 1, delta, QColor(0, 0, 0)); if (pos == -1) break; oldpos = pos; pos = text.find(">", pos); while (pos > 0 && text[pos - 1] == '\\') pos = text.find(">", pos + 1); if (pos == -1) delta = 0; else delta = pos - oldpos + 1; setFormat(oldpos, delta, QColor(100, 0, 200)); if (pos == -1) break; oldpos = pos; } return 0; } //*********************************************************************** CQValidatorExpression::CQValidatorExpression(QTextEdit * parent, const char * name, bool isBoolean): CQValidator< QTextEdit >(parent, name), mExpression() { mExpression.setBoolean(isBoolean); } /** * This function ensures that any characters on Expression Widget are validated * to go to further processes. */ QValidator::State CQValidatorExpression::validate(QString & input, int & pos) const { if (const_cast< CExpression * >(&mExpression)->setInfix((const char *) input.utf8()) && const_cast< CExpression * >(&mExpression)->compile()) { QString Input = mpLineEdit->text(); return CQValidator< QTextEdit >::validate(Input, pos); } setColor(Invalid); return Intermediate; } /** * Function to get CExpression object */ CExpression *CQValidatorExpression::getExpression() { // return const_cast< CExpression * >(&mExpression); return &mExpression; } //*********************************************************************** CQExpressionWidget::CQExpressionWidget(QWidget * parent, const char * name, bool isBoolean) : QTextEdit(parent, name), mOldPar(0), mOldPos(0), mExpressionType(CCopasiSimpleSelectionTree::TRANSIENT_EXPRESSION), mpCurrentObject(NULL), mNewName("") { setTextFormat(PlainText); setTabChangesFocus(true); new CQExpressionHighlighter(this); int h, s, v; mSavedColor = paletteBackgroundColor(); mSavedColor.getHsv(&h, &s, &v); if (s < 20) s = 20; mChangedColor.setHsv(240, s, v); mpValidator = new CQValidatorExpression(this, "", isBoolean); mpValidator->revalidate(); connect(this, SIGNAL(cursorPositionChanged(int, int)), this, SLOT(slotCursorPositionChanged(int, int))); connect(this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged())); connect(this, SIGNAL(textChanged()), this, SLOT(slotTextChanged())); } void CQExpressionWidget::keyPressEvent (QKeyEvent * e) { //filter "<" and ">" if (e->text() == "<") return; if (e->text() == ">") return; QTextEdit::keyPressEvent(e); } void CQExpressionWidget::slotSelectionChanged() { int par1, par2, pos1, pos2; getSelection(&par1, &pos1, &par2, &pos2); if (par1 == -1) //no selection, do nothing { getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2); return; } //make sure a selection contains an object completely or not at all //TODO bool iio1 = isInObject(par1, pos1); bool iio2 = isInObject(par2, pos2); //if both borders are outside do nothing. //if at least one is inside clear selection if (iio1 || iio2) removeSelection(); //TODO: right now the any invalid selection is just cleared. //in some cases it would be nicer for the user if it would be //extended instead getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2); } /** * This slot checks any characters that are newly typed on Expression Widget. */ void CQExpressionWidget::slotTextChanged() { int pos = 0; QString Expression = FROM_UTF8(getExpression()); emit valid(mpValidator->validate(Expression, pos) == QValidator::Acceptable); } void CQExpressionWidget::slotCursorPositionChanged(int para, int pos) { //check if we are inside an object if (isInObject(para, pos)) { int newpos; //first decide in which direction we want to leave the object if (compareCursorPositions(mOldPar, mOldPos, para, pos)) { //move right newpos = text(para).find(">", pos); if (newpos != -1) setCursorPosition(para, newpos + 1); } else { //move left newpos = text(para).findRev("<", pos); if (newpos != -1) setCursorPosition(para, newpos); } } getCursorPosition(&mOldPar, &mOldPos); } bool CQExpressionWidget::isInObject() { int para, pos; getCursorPosition(&para, &pos); return isInObject(para, pos); /* //the following code assumes the presence of the syntax highlighter if (color() == QColor(0,0,0)) return false; if (pos==0) return false; QString t = text(para); if (t[pos-1] == '>') return false; return true;*/ } bool CQExpressionWidget::isInObject(int par, int pos) { if (pos == 0) return false; bool result = false; QString tmp = text(par); //first look to the left int lo, lc; lo = tmp.findRev('<', pos - 1); lc = tmp.findRev('>', pos - 1); while (lc > 0 && tmp[lc - 1] == '\\') lc = tmp.findRev('>', lc - 1); if ((lo == -1) && (lc == -1)) result = false; else if (lc == -1) result = true; else if (lo == -1) { result = false; } else if (lo < lc) result = false; else // lo > lc result = true; //TODO: we could implement a consistency check by trying to find the same //information from looking to the right. return result; } bool CQExpressionWidget::compareCursorPositions(int parold, int posold, int par, int pos) { if (par > parold) return true; if (par < parold) return false; //we are in the same paragraph if (pos > posold) return true; return false; } void CQExpressionWidget::doKeyboardAction(QTextEdit::KeyboardAction action) { int para, pos; getCursorPosition(&para, &pos); //handle backspace and delete. All other actions are ignored switch (action) { case QTextEdit::ActionBackspace: if (pos == 0) return; if (text(para)[pos - 1] == '>') { QString tmp = text(para); int left = tmp.findRev('<', pos); setSelection(para, left, para, pos); removeSelectedText(); } else QTextEdit::doKeyboardAction(action); break; case QTextEdit::ActionDelete: if ((unsigned int) pos == text().length()) return; if (text(para)[pos] == '<') { QString tmp = text(para); int right = tmp.find('>', pos); setSelection(para, pos, para, right + 1); removeSelectedText(); } else QTextEdit::doKeyboardAction(action); break; default: QTextEdit::doKeyboardAction(action); break; } } void CQExpressionWidget::setExpression(const std::string & expression) { // Reset the parse list. mParseList.clear(); std::string Expression = expression; std::string out_str = ""; unsigned C_INT32 i = 0; while (i < Expression.length()) { if (Expression[i] == '<') { i++; std::string objectName = ""; while (Expression[i] != '>' && i < Expression.length()) { if (Expression[i] == '\\') objectName += Expression[i++]; objectName += Expression[i]; i++; } CCopasiObjectName temp_CN(objectName); CCopasiObject * temp_object = const_cast<CCopasiObject *>(RootContainer.getObject(temp_CN)); if (temp_object != NULL) { std::string DisplayName = temp_object->getObjectDisplayName(); mParseList[DisplayName] = temp_object; // We need to escape > std::string::size_type pos = DisplayName.find_first_of("\\>"); while (pos != std::string::npos) { DisplayName.insert(pos, "\\"); pos += 2; pos = DisplayName.find_first_of("\\>", pos); } out_str += "<" + DisplayName + ">"; } continue; } else if (Expression[i] == '>') { //do nothing } else { out_str += Expression[i]; } i++; } setText(FROM_UTF8(out_str)); mpValidator->saved(); return; } std::string CQExpressionWidget::getExpression() const { std::string DisplayName = ""; std::string InfixCN = ""; std::string InfixDispayName = (const char *)text().utf8(); std::map< std::string, const CCopasiObject *>::const_iterator it; unsigned int i; for (i = 0; i < InfixDispayName.length(); i++) { InfixCN += InfixDispayName[i]; DisplayName = ""; if (InfixDispayName[i] == '<') { i++; while (i < InfixDispayName.length() && InfixDispayName[i] != '>') { if (InfixDispayName[i] == '\\') // '\' is an escape character. i++; DisplayName += InfixDispayName[i++]; } it = mParseList.find(DisplayName); if (it != mParseList.end()) InfixCN += it->second->getCN() + ">"; else InfixCN = InfixCN.substr(0, InfixCN.length() - 1); } } return InfixCN; } /* CExpression *CQExpressionWidget::getExpression() { // return const_cast< CExpression * >(&mExpression); return &(mpValidator->mExpression); }*/ void CQExpressionWidget::setExpressionType(const CCopasiSimpleSelectionTree::SelectionFlag & expressionType) { mExpressionType = expressionType; } void CQExpressionWidget::slotSelectObject() { const CCopasiObject * pObject = CCopasiSelectionDialog::getObjectSingle(this, mExpressionType); if (pObject) { // Check whether the object is valid if (!CCopasiSimpleSelectionTree::filter(mExpressionType, pObject)) { CQMessageBox::critical(this, "Invalid Selection", "The use of the selected object is not allowed in this type of expression."); return; } std::string Insert = pObject->getObjectDisplayName(); mParseList[Insert] = pObject; // We need to escape > std::string::size_type pos = Insert.find_first_of("\\>"); while (pos != std::string::npos) { Insert.insert(pos, "\\"); pos += 2; pos = Insert.find_first_of("\\>", pos); } insert(FROM_UTF8("<" + Insert + ">")); } } <commit_msg>Add ability to choose a cell matrix in slotSelectObject<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQExpressionWidget.cpp,v $ // $Revision: 1.27 $ // $Name: $ // $Author: pwilly $ // $Date: 2008/07/29 10:53:36 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <iostream> #include <qlabel.h> #include <qcombobox.h> #include "CQExpressionWidget.h" #include "CQMessageBox.h" #include "CCopasiSelectionDialog.h" #include "qtUtilities.h" #include "copasi.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "function/CExpression.h" #include "utilities/CAnnotatedMatrix.h" #include "model/CModel.h" #include "CQMatrixDialog.h" #include "qtUtilities.h" CQExpressionHighlighter::CQExpressionHighlighter(CQExpressionWidget* ew) : QSyntaxHighlighter(ew) {} int CQExpressionHighlighter::highlightParagraph (const QString & text, int /* endStateOfLastPara */) { int pos = 0; int oldpos = -1; int delta; while (true) { pos = text.find("<", pos); if (pos == -1) delta = 0; else delta = pos - oldpos - 1; setFormat(oldpos + 1, delta, QColor(0, 0, 0)); if (pos == -1) break; oldpos = pos; pos = text.find(">", pos); while (pos > 0 && text[pos - 1] == '\\') pos = text.find(">", pos + 1); if (pos == -1) delta = 0; else delta = pos - oldpos + 1; setFormat(oldpos, delta, QColor(100, 0, 200)); if (pos == -1) break; oldpos = pos; } return 0; } //*********************************************************************** CQValidatorExpression::CQValidatorExpression(QTextEdit * parent, const char * name, bool isBoolean): CQValidator< QTextEdit >(parent, name), mExpression() { mExpression.setBoolean(isBoolean); } /** * This function ensures that any characters on Expression Widget are validated * to go to further processes. */ QValidator::State CQValidatorExpression::validate(QString & input, int & pos) const { if (const_cast< CExpression * >(&mExpression)->setInfix((const char *) input.utf8()) && const_cast< CExpression * >(&mExpression)->compile()) { QString Input = mpLineEdit->text(); return CQValidator< QTextEdit >::validate(Input, pos); } setColor(Invalid); return Intermediate; } /** * Function to get CExpression object */ CExpression *CQValidatorExpression::getExpression() { // return const_cast< CExpression * >(&mExpression); return &mExpression; } //*********************************************************************** CQExpressionWidget::CQExpressionWidget(QWidget * parent, const char * name, bool isBoolean) : QTextEdit(parent, name), mOldPar(0), mOldPos(0), mExpressionType(CCopasiSimpleSelectionTree::TRANSIENT_EXPRESSION), mpCurrentObject(NULL), mNewName("") { setTextFormat(PlainText); setTabChangesFocus(true); new CQExpressionHighlighter(this); int h, s, v; mSavedColor = paletteBackgroundColor(); mSavedColor.getHsv(&h, &s, &v); if (s < 20) s = 20; mChangedColor.setHsv(240, s, v); mpValidator = new CQValidatorExpression(this, "", isBoolean); mpValidator->revalidate(); connect(this, SIGNAL(cursorPositionChanged(int, int)), this, SLOT(slotCursorPositionChanged(int, int))); connect(this, SIGNAL(selectionChanged()), this, SLOT(slotSelectionChanged())); connect(this, SIGNAL(textChanged()), this, SLOT(slotTextChanged())); } void CQExpressionWidget::keyPressEvent (QKeyEvent * e) { //filter "<" and ">" if (e->text() == "<") return; if (e->text() == ">") return; QTextEdit::keyPressEvent(e); } void CQExpressionWidget::slotSelectionChanged() { int par1, par2, pos1, pos2; getSelection(&par1, &pos1, &par2, &pos2); if (par1 == -1) //no selection, do nothing { getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2); return; } //make sure a selection contains an object completely or not at all //TODO bool iio1 = isInObject(par1, pos1); bool iio2 = isInObject(par2, pos2); //if both borders are outside do nothing. //if at least one is inside clear selection if (iio1 || iio2) removeSelection(); //TODO: right now the any invalid selection is just cleared. //in some cases it would be nicer for the user if it would be //extended instead getSelection(&mOldPar1, &mOldPos1, &mOldPar2, &mOldPos2); } /** * This slot checks any characters that are newly typed on Expression Widget. */ void CQExpressionWidget::slotTextChanged() { int pos = 0; QString Expression = FROM_UTF8(getExpression()); emit valid(mpValidator->validate(Expression, pos) == QValidator::Acceptable); } void CQExpressionWidget::slotCursorPositionChanged(int para, int pos) { //check if we are inside an object if (isInObject(para, pos)) { int newpos; //first decide in which direction we want to leave the object if (compareCursorPositions(mOldPar, mOldPos, para, pos)) { //move right newpos = text(para).find(">", pos); if (newpos != -1) setCursorPosition(para, newpos + 1); } else { //move left newpos = text(para).findRev("<", pos); if (newpos != -1) setCursorPosition(para, newpos); } } getCursorPosition(&mOldPar, &mOldPos); } bool CQExpressionWidget::isInObject() { int para, pos; getCursorPosition(&para, &pos); return isInObject(para, pos); /* //the following code assumes the presence of the syntax highlighter if (color() == QColor(0,0,0)) return false; if (pos==0) return false; QString t = text(para); if (t[pos-1] == '>') return false; return true;*/ } bool CQExpressionWidget::isInObject(int par, int pos) { if (pos == 0) return false; bool result = false; QString tmp = text(par); //first look to the left int lo, lc; lo = tmp.findRev('<', pos - 1); lc = tmp.findRev('>', pos - 1); while (lc > 0 && tmp[lc - 1] == '\\') lc = tmp.findRev('>', lc - 1); if ((lo == -1) && (lc == -1)) result = false; else if (lc == -1) result = true; else if (lo == -1) { result = false; } else if (lo < lc) result = false; else // lo > lc result = true; //TODO: we could implement a consistency check by trying to find the same //information from looking to the right. return result; } bool CQExpressionWidget::compareCursorPositions(int parold, int posold, int par, int pos) { if (par > parold) return true; if (par < parold) return false; //we are in the same paragraph if (pos > posold) return true; return false; } void CQExpressionWidget::doKeyboardAction(QTextEdit::KeyboardAction action) { int para, pos; getCursorPosition(&para, &pos); //handle backspace and delete. All other actions are ignored switch (action) { case QTextEdit::ActionBackspace: if (pos == 0) return; if (text(para)[pos - 1] == '>') { QString tmp = text(para); int left = tmp.findRev('<', pos); setSelection(para, left, para, pos); removeSelectedText(); } else QTextEdit::doKeyboardAction(action); break; case QTextEdit::ActionDelete: if ((unsigned int) pos == text().length()) return; if (text(para)[pos] == '<') { QString tmp = text(para); int right = tmp.find('>', pos); setSelection(para, pos, para, right + 1); removeSelectedText(); } else QTextEdit::doKeyboardAction(action); break; default: QTextEdit::doKeyboardAction(action); break; } } void CQExpressionWidget::setExpression(const std::string & expression) { // Reset the parse list. mParseList.clear(); std::string Expression = expression; std::string out_str = ""; unsigned C_INT32 i = 0; while (i < Expression.length()) { if (Expression[i] == '<') { i++; std::string objectName = ""; while (Expression[i] != '>' && i < Expression.length()) { if (Expression[i] == '\\') objectName += Expression[i++]; objectName += Expression[i]; i++; } CCopasiObjectName temp_CN(objectName); CCopasiObject * temp_object = const_cast<CCopasiObject *>(RootContainer.getObject(temp_CN)); if (temp_object != NULL) { std::string DisplayName = temp_object->getObjectDisplayName(); mParseList[DisplayName] = temp_object; // We need to escape > std::string::size_type pos = DisplayName.find_first_of("\\>"); while (pos != std::string::npos) { DisplayName.insert(pos, "\\"); pos += 2; pos = DisplayName.find_first_of("\\>", pos); } out_str += "<" + DisplayName + ">"; } continue; } else if (Expression[i] == '>') { //do nothing } else { out_str += Expression[i]; } i++; } setText(FROM_UTF8(out_str)); mpValidator->saved(); return; } std::string CQExpressionWidget::getExpression() const { std::string DisplayName = ""; std::string InfixCN = ""; std::string InfixDispayName = (const char *)text().utf8(); std::map< std::string, const CCopasiObject *>::const_iterator it; unsigned int i; for (i = 0; i < InfixDispayName.length(); i++) { InfixCN += InfixDispayName[i]; DisplayName = ""; if (InfixDispayName[i] == '<') { i++; while (i < InfixDispayName.length() && InfixDispayName[i] != '>') { if (InfixDispayName[i] == '\\') // '\' is an escape character. i++; DisplayName += InfixDispayName[i++]; } it = mParseList.find(DisplayName); if (it != mParseList.end()) InfixCN += it->second->getCN() + ">"; else InfixCN = InfixCN.substr(0, InfixCN.length() - 1); } } return InfixCN; } /* CExpression *CQExpressionWidget::getExpression() { // return const_cast< CExpression * >(&mExpression); return &(mpValidator->mExpression); }*/ void CQExpressionWidget::setExpressionType(const CCopasiSimpleSelectionTree::SelectionFlag & expressionType) { mExpressionType = expressionType; } void CQExpressionWidget::slotSelectObject() { const CCopasiObject * pObject = CCopasiSelectionDialog::getObjectSingle(this, mExpressionType); if (pObject->getObjectType() == "Array") { QString str = pObject->getObjectType() + "=" + pObject->getObjectName(); const CModel* pModel = CCopasiDataModel::Global->getModel(); const CArrayAnnotation * tmp; tmp = dynamic_cast<const CArrayAnnotation *> (pModel->getObject(CCopasiObjectName("Array=Stoichiometry(ann)"))); CQMatrixDialog *dialog = new CQMatrixDialog(); int i; dialog->mpLabelRow->setText("Rows : " + tmp->getDimensionDescription(0)); int nRows = tmp->getAnnotationsCN(0).size(); for (i = 0; i < nRows; i++) { dialog->mpCBRow->insertItem(FROM_UTF8(tmp->getAnnotationsString(0, true)[i])); } dialog->mpLabelColumn->setText("Columns : " + tmp->getDimensionDescription(1)); int nCols = tmp->getAnnotationsCN(1).size(); for (i = 0; i < nCols; i++) { dialog->mpCBColumn->insertItem(FROM_UTF8(tmp->getAnnotationsString(1, true)[i])); } if (tmp->dimensionality() == 2) { dialog->mpLabelDim3->hide(); dialog->mpCBDim3->hide(); } else if (tmp->dimensionality() == 3) { dialog->mpLabelDim3->setText("Dimension : " + tmp->getDimensionDescription(2)); int nDims = tmp->getAnnotationsCN(2).size(); for (i = 0; i < nDims; i++) dialog->mpCBDim3->insertItem(FROM_UTF8(tmp->getAnnotationsString(2, true)[i])); } int Result = dialog->exec(); if (Result == QDialog::Rejected) return; else if (Result == QDialog::Accepted) { std::cout << dialog->mpCBRow->currentText() << " AND " << dialog->mpCBColumn->currentText() << std::endl; } } if (pObject) { // Check whether the object is valid if (!CCopasiSimpleSelectionTree::filter(mExpressionType, pObject)) { CQMessageBox::critical(this, "Invalid Selection", "The use of the selected object is not allowed in this type of expression."); return; } std::string Insert = pObject->getObjectDisplayName(); mParseList[Insert] = pObject; // We need to escape > std::string::size_type pos = Insert.find_first_of("\\>"); while (pos != std::string::npos) { Insert.insert(pos, "\\"); pos += 2; pos = Insert.find_first_of("\\>", pos); } insert(FROM_UTF8("<" + Insert + ">")); } } <|endoftext|>
<commit_before>// @(#)root/proofplayer:$Id$ // Author: Maarten Ballintijn 7/06/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TStatus // // // // This class holds the status of an ongoing operation and collects // // error messages. It provides a Merge() operation allowing it to // // be used in PROOF to monitor status in the slaves. // // No messages indicates success. // // // ////////////////////////////////////////////////////////////////////////// #include "TStatus.h" #include "Riostream.h" #include "TClass.h" #include "TList.h" ClassImp(TStatus) //______________________________________________________________________________ TStatus::TStatus() : fVirtMemMax(-1), fResMemMax(-1) { // Deafult constructor. SetName("PROOF_Status"); fIter = fMsgs.begin(); } //______________________________________________________________________________ void TStatus::Add(const char *mesg) { // Add an error message. fMsgs.insert(mesg); Reset(); } //______________________________________________________________________________ Int_t TStatus::Merge(TCollection *li) { // PROOF Merge() function. TIter stats(li); Info("Merge", "Start: Max virtual memory: %.2f MB \tMax resident memory: %.2f MB ", GetVirtMemMax()/1024., GetResMemMax()/1024.); while (TObject *obj = stats()) { TStatus *s = dynamic_cast<TStatus*>(obj); if (s == 0) continue; MsgIter_t i = s->fMsgs.begin(); MsgIter_t end = s->fMsgs.end(); for (; i != end; i++) Add(i->c_str()); SetMemValues(s->GetVirtMemMax(), s->GetResMemMax()); Info("Merge", "During: Max virtual memory: %.2f MB \tMax resident memory: %.2f MB ", GetVirtMemMax()/1024., GetResMemMax()/1024.); } Info("Merge", "End: Max virtual memory: %.2f MB \tMax resident memory: %.2f MB ", GetVirtMemMax()/1024., GetResMemMax()/1024.); return fMsgs.size(); } //______________________________________________________________________________ void TStatus::Print(Option_t * /*option*/) const { // Standard print function. Printf("OBJ: %s\t%s\t%s", IsA()->GetName(), GetName(), (IsOk() ? "OK" : "ERROR")); MsgIter_t i = fMsgs.begin(); for (; i != fMsgs.end(); i++) Printf("\t%s", (*i).c_str()); Printf(" Max virtual memory: %.2f MB \tMax resident memory: %.2f MB ", GetVirtMemMax()/1024., GetResMemMax()/1024.); } //______________________________________________________________________________ void TStatus::Reset() { // Reset the iterator on the messages. fIter = fMsgs.begin(); } //______________________________________________________________________________ const char *TStatus::NextMesg() { // Return the next message or 0. if (fIter != fMsgs.end()) { return (*fIter++).c_str(); } else { return 0; } } //______________________________________________________________________________ void TStatus::SetMemValues(Long_t vmem, Long_t rmem) { // Set max memory values if (vmem > 0. && (fVirtMemMax < 0. || vmem > fVirtMemMax)) fVirtMemMax = vmem; if (rmem > 0. && (fResMemMax < 0. || rmem > fResMemMax)) fResMemMax = rmem; } <commit_msg>Remove debug statements<commit_after>// @(#)root/proofplayer:$Id$ // Author: Maarten Ballintijn 7/06/2004 /************************************************************************* * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TStatus // // // // This class holds the status of an ongoing operation and collects // // error messages. It provides a Merge() operation allowing it to // // be used in PROOF to monitor status in the slaves. // // No messages indicates success. // // // ////////////////////////////////////////////////////////////////////////// #include "TStatus.h" #include "Riostream.h" #include "TClass.h" #include "TList.h" #include "TProofDebug.h" ClassImp(TStatus) //______________________________________________________________________________ TStatus::TStatus() : fVirtMemMax(-1), fResMemMax(-1) { // Deafult constructor. SetName("PROOF_Status"); fIter = fMsgs.begin(); } //______________________________________________________________________________ void TStatus::Add(const char *mesg) { // Add an error message. fMsgs.insert(mesg); Reset(); } //______________________________________________________________________________ Int_t TStatus::Merge(TCollection *li) { // PROOF Merge() function. TIter stats(li); PDB(kOutput,1) Info("Merge", "start: max virtual memory: %.2f MB \tmax resident memory: %.2f MB ", GetVirtMemMax()/1024., GetResMemMax()/1024.); while (TObject *obj = stats()) { TStatus *s = dynamic_cast<TStatus*>(obj); if (s == 0) continue; MsgIter_t i = s->fMsgs.begin(); MsgIter_t end = s->fMsgs.end(); for (; i != end; i++) Add(i->c_str()); SetMemValues(s->GetVirtMemMax(), s->GetResMemMax()); PDB(kOutput,1) Info("Merge", "during: max virtual memory: %.2f MB \t" "max resident memory: %.2f MB ", GetVirtMemMax()/1024., GetResMemMax()/1024.); } return fMsgs.size(); } //______________________________________________________________________________ void TStatus::Print(Option_t * /*option*/) const { // Standard print function. Printf("OBJ: %s\t%s\t%s", IsA()->GetName(), GetName(), (IsOk() ? "OK" : "ERROR")); MsgIter_t i = fMsgs.begin(); for (; i != fMsgs.end(); i++) Printf("\t%s", (*i).c_str()); Printf(" Max virtual memory: %.2f MB \tMax resident memory: %.2f MB ", GetVirtMemMax()/1024., GetResMemMax()/1024.); } //______________________________________________________________________________ void TStatus::Reset() { // Reset the iterator on the messages. fIter = fMsgs.begin(); } //______________________________________________________________________________ const char *TStatus::NextMesg() { // Return the next message or 0. if (fIter != fMsgs.end()) { return (*fIter++).c_str(); } else { return 0; } } //______________________________________________________________________________ void TStatus::SetMemValues(Long_t vmem, Long_t rmem) { // Set max memory values if (vmem > 0. && (fVirtMemMax < 0. || vmem > fVirtMemMax)) fVirtMemMax = vmem; if (rmem > 0. && (fResMemMax < 0. || rmem > fResMemMax)) fResMemMax = rmem; } <|endoftext|>
<commit_before>/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include <boost/algorithm/string.hpp> #include "chartclass.h" #include <ostream> namespace cpdoccore { namespace odf_types { std::wostream & operator << (std::wostream & _Wostream, const chart_class & _Val) { std::wstring res = L""; switch(_Val.get_type()) { case chart_class::area: _Wostream << L"chart:area"; break; case chart_class::bubble: _Wostream << L"chart:bubble"; break; case chart_class::circle: _Wostream << L"chart:circle"; break; case chart_class::filled_radar: _Wostream << L"chart:filled-radar"; break; case chart_class::gantt: _Wostream << L"chart:gantt"; break; case chart_class::line: _Wostream << L"chart:line"; break; case chart_class::radar: _Wostream << L"chart:radar"; break; case chart_class::ring: _Wostream << L"chart:ring"; break; case chart_class::scatter: _Wostream << L"chart:scatter"; break; case chart_class::stock: _Wostream << L"chart:stock"; break; case chart_class::surface: _Wostream << L"chart:surface"; break; case chart_class::bar: _Wostream << L"chart:bar"; default: _Wostream << L"chart:bar"; } return _Wostream; } chart_class chart_class::parse(const std::wstring & Str) { std::wstring tmp = Str; boost::algorithm::to_lower(tmp); if (tmp == L"chart:area") return chart_class(area); else if (tmp == L"chart:bar") return chart_class(bar); else if (tmp == L"chart:bubble") return chart_class(bubble); else if (tmp == L"chart:circle") return chart_class(circle); else if (tmp == L"chart:filled-radar") return chart_class(filled_radar); else if (tmp == L"chart:gantt") return chart_class(gantt); else if (tmp == L"chart:line") return chart_class(line); else if (tmp == L"chart:radar") return chart_class(radar); else if (tmp == L"chart:ring") return chart_class(ring); else if (tmp == L"chart:scatter") return chart_class(scatter); else if (tmp == L"chart:stock") return chart_class(stock); else if (tmp == L"chart:surface") return chart_class(surface); else { return chart_class(bar); } } } } <commit_msg>OdfFormat - fix bug #47146<commit_after>/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include <boost/algorithm/string.hpp> #include "chartclass.h" #include <ostream> namespace cpdoccore { namespace odf_types { std::wostream & operator << (std::wostream & _Wostream, const chart_class & _Val) { std::wstring res = L""; switch(_Val.get_type()) { case chart_class::area: _Wostream << L"chart:area"; break; case chart_class::bubble: _Wostream << L"chart:bubble"; break; case chart_class::circle: _Wostream << L"chart:circle"; break; case chart_class::filled_radar: _Wostream << L"chart:filled-radar"; break; case chart_class::gantt: _Wostream << L"chart:gantt"; break; case chart_class::line: _Wostream << L"chart:line"; break; case chart_class::radar: _Wostream << L"chart:radar"; break; case chart_class::ring: _Wostream << L"chart:ring"; break; case chart_class::scatter: _Wostream << L"chart:scatter"; break; case chart_class::stock: _Wostream << L"chart:stock"; break; case chart_class::surface: _Wostream << L"chart:surface"; break; case chart_class::bar: default: _Wostream << L"chart:bar"; } return _Wostream; } chart_class chart_class::parse(const std::wstring & Str) { std::wstring tmp = Str; boost::algorithm::to_lower(tmp); if (tmp == L"chart:area") return chart_class(area); else if (tmp == L"chart:bar") return chart_class(bar); else if (tmp == L"chart:bubble") return chart_class(bubble); else if (tmp == L"chart:circle") return chart_class(circle); else if (tmp == L"chart:filled-radar") return chart_class(filled_radar); else if (tmp == L"chart:gantt") return chart_class(gantt); else if (tmp == L"chart:line") return chart_class(line); else if (tmp == L"chart:radar") return chart_class(radar); else if (tmp == L"chart:ring") return chart_class(ring); else if (tmp == L"chart:scatter") return chart_class(scatter); else if (tmp == L"chart:stock") return chart_class(stock); else if (tmp == L"chart:surface") return chart_class(surface); else { return chart_class(bar); } } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkBoostGraphAdapter.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkBoostBetweennessClustering.h" #include "vtkBoostConnectedComponents.h" #include "vtkBoostGraphAdapter.h" #include "vtkDataSetAttributes.h" #include "vtkDirectedGraph.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkMutableUndirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" #include "vtkUndirectedGraph.h" #include <boost/graph/bc_clustering.hpp> // @note: This piece of code is modification of algorithm from boost graph // library. This modified version allows the user to pass edge weight map namespace boost { // Graph clustering based on edge betweenness centrality. // // This algorithm implements graph clustering based on edge // betweenness centrality. It is an iterative algorithm, where in each // step it compute the edge betweenness centrality (via @ref // brandes_betweenness_centrality) and removes the edge with the // maximum betweenness centrality. The @p done function object // determines when the algorithm terminates (the edge found when the // algorithm terminates will not be removed). // // @param g The graph on which clustering will be performed. The type // of this parameter (@c MutableGraph) must be a model of the // VertexListGraph, IncidenceGraph, EdgeListGraph, and Mutable Graph // concepts. // // @param done The function object that indicates termination of the // algorithm. It must be a ternary function object thats accepts the // maximum centrality, the descriptor of the edge that will be // removed, and the graph @p g. // // @param edge_centrality (UTIL/out2) The property map that will store // the betweenness centrality for each edge. When the algorithm // terminates, it will contain the edge centralities for the // graph. The type of this property map must model the // ReadWritePropertyMap concept. Defaults to an @c // iterator_property_map whose value type is // @c Done::centrality_type and using @c get(edge_index, g) for the // index map. // // @param vertex_index (IN) The property map that maps vertices to // indices in the range @c [0, num_vertices(g)). This type of this // property map must model the ReadablePropertyMap concept and its // value type must be an integral type. Defaults to // @c get(vertex_index, g). template<typename MutableGraph, typename Done, typename EdgeCentralityMap, typename EdgeWeightMap, typename VertexIndexMap> void betweenness_centrality_clustering(MutableGraph& g, Done done, EdgeCentralityMap edge_centrality, EdgeWeightMap edge_weight_map, VertexIndexMap vertex_index) { typedef typename property_traits<EdgeCentralityMap>::value_type centrality_type; typedef typename graph_traits<MutableGraph>::edge_iterator edge_iterator; typedef typename graph_traits<MutableGraph>::edge_descriptor edge_descriptor; typedef typename graph_traits<MutableGraph>::vertices_size_type vertices_size_type; if (has_no_edges(g)) return; // Function object that compares the centrality of edges indirect_cmp<EdgeCentralityMap, std::less<centrality_type> > cmp(edge_centrality); bool is_done; do { brandes_betweenness_centrality(g,edge_centrality_map(edge_centrality) .vertex_index_map(vertex_index) .weight_map(edge_weight_map)); std::pair<edge_iterator, edge_iterator> edges_iters = edges(g); edge_descriptor e = *max_element(edges_iters.first, edges_iters.second, cmp); is_done = done(get(edge_centrality, e), e, g); if (!is_done) remove_edge(e, g); } while (!is_done && !has_no_edges(g)); } } vtkStandardNewMacro(vtkBoostBetweennessClustering); //----------------------------------------------------------------------------- vtkBoostBetweennessClustering::vtkBoostBetweennessClustering() : vtkGraphAlgorithm (), Threshold (0), UseEdgeWeightArray (false), InvertEdgeWeightArray (false), EdgeWeightArrayName (0), EdgeCentralityArrayName (0) { this->SetNumberOfOutputPorts(2); } //----------------------------------------------------------------------------- vtkBoostBetweennessClustering::~vtkBoostBetweennessClustering() { } //----------------------------------------------------------------------------- void vtkBoostBetweennessClustering::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Threshold: " << this->Threshold << endl; os << indent << "UseEdgeWeightArray: " << this->UseEdgeWeightArray << endl; os << indent << "InvertEdgeWeightArray: " << this->InvertEdgeWeightArray << endl; (EdgeWeightArrayName) ? os << indent << "EdgeWeightArrayName: " << this->EdgeWeightArrayName << endl : os << indent << "EdgeWeightArrayName: NULL" << endl; (EdgeCentralityArrayName) ? os << indent << "EdgeCentralityArrayName: " << this->EdgeCentralityArrayName << endl : os << indent << "EdgeCentralityArrayName: NULL" << endl; } //----------------------------------------------------------------------------- int vtkBoostBetweennessClustering::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // Helpful vars. bool isDirectedGraph (false); // Get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); if(!inInfo) { vtkErrorMacro("Failed to get input information.") return 1; } vtkInformation* outInfo1 = outputVector->GetInformationObject(0); if(!outInfo1) { vtkErrorMacro("Failed get output1 on information first port.") } vtkInformation* outInfo2 = outputVector->GetInformationObject(1); if(!outInfo2) { vtkErrorMacro("Failed to get output2 information on second port.") return 1; } // Get the input, output1 and output2. vtkGraph* input = vtkGraph::SafeDownCast(inInfo->Get( vtkDataObject::DATA_OBJECT())); if(!input) { vtkErrorMacro("Failed to get input graph.") return 1; } if(vtkDirectedGraph::SafeDownCast(input)) { isDirectedGraph = true; } vtkGraph* output1 = vtkGraph::SafeDownCast( outInfo1->Get(vtkDataObject::DATA_OBJECT())); if(!output1) { vtkErrorMacro("Failed to get output1 graph.") return 1; } vtkGraph* output2 = vtkGraph::SafeDownCast( outInfo2->Get(vtkDataObject::DATA_OBJECT())); if(!output2) { vtkErrorMacro("Failed to get output2 graph.") return 1; } vtkSmartPointer<vtkFloatArray> edgeCM = vtkSmartPointer<vtkFloatArray>::New(); if(this->EdgeCentralityArrayName) { edgeCM->SetName(this->EdgeCentralityArrayName); } else { edgeCM->SetName("edge_centrality"); } boost::vtkGraphEdgePropertyMapHelper<vtkFloatArray*> helper(edgeCM); vtkSmartPointer<vtkDataArray> edgeWeight (0); if(this->UseEdgeWeightArray && this->EdgeWeightArrayName) { if(!this->InvertEdgeWeightArray) { edgeWeight = input->GetEdgeData()->GetArray(this->EdgeWeightArrayName); } else { vtkDataArray* weights = input->GetEdgeData()->GetArray(this->EdgeWeightArrayName); edgeWeight.TakeReference( vtkDataArray::CreateDataArray(weights->GetDataType())); double range[2]; weights->GetRange(range); if(weights->GetNumberOfComponents() > 1) { vtkErrorMacro("Expecting single component array."); return 1; } for(int i=0; i < weights->GetDataSize(); ++i) { edgeWeight->InsertNextTuple1(range[1] - weights->GetTuple1(i)); } } if(!edgeWeight) { vtkErrorMacro(<<"Error: Edge weight array " << this->EdgeWeightArrayName << " is set but not found.\n"); return 1; } } // First compute the second output and the result will be used // as input for the first output. if(isDirectedGraph) { vtkMutableDirectedGraph* out2 = vtkMutableDirectedGraph::New(); // Copy the data to the second output (as this algorithm most likely // going to removed edges (and hence modifies the graph). out2->DeepCopy(input); if(edgeWeight) { boost::vtkGraphEdgePropertyMapHelper<vtkDataArray*> helper2(edgeWeight); boost::betweenness_centrality_clustering(out2, boost::bc_clustering_threshold<double>(this->Threshold, out2, false), helper, helper2, boost::get(boost::vertex_index, out2)); } else { boost::betweenness_centrality_clustering(out2, boost::bc_clustering_threshold<double>( this->Threshold, out2, false), helper); } out2->GetEdgeData()->AddArray(edgeCM); // Finally copy the results to the output. output2->ShallowCopy(out2); out2->Delete(); } else { vtkMutableUndirectedGraph* out2 = vtkMutableUndirectedGraph::New(); // Send the data to output2. out2->DeepCopy(input); if(edgeWeight) { boost::vtkGraphEdgePropertyMapHelper<vtkDataArray*> helper2(edgeWeight); boost::betweenness_centrality_clustering(out2, boost::bc_clustering_threshold<double>(this->Threshold, out2,false), helper, helper2, boost::get(boost::vertex_index, out2)); } else { boost::betweenness_centrality_clustering(out2, boost::bc_clustering_threshold<double>(this->Threshold, out2,false), helper); } out2->GetEdgeData()->AddArray(edgeCM); // Finally copy the results to the output. output2->ShallowCopy(out2); out2->Delete(); } // Now take care of the first output. vtkSmartPointer<vtkBoostConnectedComponents> bcc ( vtkSmartPointer<vtkBoostConnectedComponents>::New()); vtkSmartPointer<vtkGraph> output2Copy(0); if(isDirectedGraph) { output2Copy = vtkSmartPointer<vtkDirectedGraph>::New(); } else { output2Copy = vtkSmartPointer<vtkUndirectedGraph>::New(); } output2Copy->ShallowCopy(output2); bcc->SetInput(0, output2Copy); bcc->Update(); vtkSmartPointer<vtkGraph> bccOut = bcc->GetOutput(0); vtkSmartPointer<vtkAbstractArray> compArray (0); if(isDirectedGraph) { vtkSmartPointer<vtkDirectedGraph> out1 (vtkSmartPointer<vtkDirectedGraph>::New()); out1->ShallowCopy(input); compArray = bccOut->GetVertexData()->GetAbstractArray("component"); if(!compArray) { vtkErrorMacro("Unable to get component array.") return 1; } out1->GetVertexData()->AddArray(compArray); // Finally copy the output to the algorithm output. output1->ShallowCopy(out1); } else { vtkSmartPointer<vtkUndirectedGraph> out1 (vtkSmartPointer<vtkUndirectedGraph>::New()); out1->ShallowCopy(input); compArray = bccOut->GetVertexData()->GetAbstractArray("component"); if(!compArray) { vtkErrorMacro("Unable to get component array.") return 1; } out1->GetVertexData()->AddArray(compArray); // Finally copy the output to the algorithm output. output1->ShallowCopy(out1); } // Also add the components array to the second output. output2->GetVertexData()->AddArray(compArray); return 1; } //----------------------------------------------------------------------------- int vtkBoostBetweennessClustering::FillOutputPortInformation( int port, vtkInformation* info) { if(port == 0 || port == 1) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkGraph"); } return 1; } <commit_msg>BUG: Fixed the crash when user selected a non data array for edge weight.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkBoostGraphAdapter.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkBoostBetweennessClustering.h" #include "vtkBoostConnectedComponents.h" #include "vtkBoostGraphAdapter.h" #include "vtkDataSetAttributes.h" #include "vtkDirectedGraph.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkMutableUndirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkSmartPointer.h" #include "vtkUndirectedGraph.h" #include <boost/graph/bc_clustering.hpp> // @note: This piece of code is modification of algorithm from boost graph // library. This modified version allows the user to pass edge weight map namespace boost { // Graph clustering based on edge betweenness centrality. // // This algorithm implements graph clustering based on edge // betweenness centrality. It is an iterative algorithm, where in each // step it compute the edge betweenness centrality (via @ref // brandes_betweenness_centrality) and removes the edge with the // maximum betweenness centrality. The @p done function object // determines when the algorithm terminates (the edge found when the // algorithm terminates will not be removed). // // @param g The graph on which clustering will be performed. The type // of this parameter (@c MutableGraph) must be a model of the // VertexListGraph, IncidenceGraph, EdgeListGraph, and Mutable Graph // concepts. // // @param done The function object that indicates termination of the // algorithm. It must be a ternary function object thats accepts the // maximum centrality, the descriptor of the edge that will be // removed, and the graph @p g. // // @param edge_centrality (UTIL/out2) The property map that will store // the betweenness centrality for each edge. When the algorithm // terminates, it will contain the edge centralities for the // graph. The type of this property map must model the // ReadWritePropertyMap concept. Defaults to an @c // iterator_property_map whose value type is // @c Done::centrality_type and using @c get(edge_index, g) for the // index map. // // @param vertex_index (IN) The property map that maps vertices to // indices in the range @c [0, num_vertices(g)). This type of this // property map must model the ReadablePropertyMap concept and its // value type must be an integral type. Defaults to // @c get(vertex_index, g). template<typename MutableGraph, typename Done, typename EdgeCentralityMap, typename EdgeWeightMap, typename VertexIndexMap> void betweenness_centrality_clustering(MutableGraph& g, Done done, EdgeCentralityMap edge_centrality, EdgeWeightMap edge_weight_map, VertexIndexMap vertex_index) { typedef typename property_traits<EdgeCentralityMap>::value_type centrality_type; typedef typename graph_traits<MutableGraph>::edge_iterator edge_iterator; typedef typename graph_traits<MutableGraph>::edge_descriptor edge_descriptor; typedef typename graph_traits<MutableGraph>::vertices_size_type vertices_size_type; if (has_no_edges(g)) return; // Function object that compares the centrality of edges indirect_cmp<EdgeCentralityMap, std::less<centrality_type> > cmp(edge_centrality); bool is_done; do { brandes_betweenness_centrality(g,edge_centrality_map(edge_centrality) .vertex_index_map(vertex_index) .weight_map(edge_weight_map)); std::pair<edge_iterator, edge_iterator> edges_iters = edges(g); edge_descriptor e = *max_element(edges_iters.first, edges_iters.second, cmp); is_done = done(get(edge_centrality, e), e, g); if (!is_done) remove_edge(e, g); } while (!is_done && !has_no_edges(g)); } } vtkStandardNewMacro(vtkBoostBetweennessClustering); //----------------------------------------------------------------------------- vtkBoostBetweennessClustering::vtkBoostBetweennessClustering() : vtkGraphAlgorithm (), Threshold (0), UseEdgeWeightArray (false), InvertEdgeWeightArray (false), EdgeWeightArrayName (0), EdgeCentralityArrayName (0) { this->SetNumberOfOutputPorts(2); } //----------------------------------------------------------------------------- vtkBoostBetweennessClustering::~vtkBoostBetweennessClustering() { } //----------------------------------------------------------------------------- void vtkBoostBetweennessClustering::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Threshold: " << this->Threshold << endl; os << indent << "UseEdgeWeightArray: " << this->UseEdgeWeightArray << endl; os << indent << "InvertEdgeWeightArray: " << this->InvertEdgeWeightArray << endl; (EdgeWeightArrayName) ? os << indent << "EdgeWeightArrayName: " << this->EdgeWeightArrayName << endl : os << indent << "EdgeWeightArrayName: NULL" << endl; (EdgeCentralityArrayName) ? os << indent << "EdgeCentralityArrayName: " << this->EdgeCentralityArrayName << endl : os << indent << "EdgeCentralityArrayName: NULL" << endl; } //----------------------------------------------------------------------------- int vtkBoostBetweennessClustering::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // Helpful vars. bool isDirectedGraph (false); // Get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); if(!inInfo) { vtkErrorMacro("Failed to get input information.") return 1; } vtkInformation* outInfo1 = outputVector->GetInformationObject(0); if(!outInfo1) { vtkErrorMacro("Failed get output1 on information first port.") } vtkInformation* outInfo2 = outputVector->GetInformationObject(1); if(!outInfo2) { vtkErrorMacro("Failed to get output2 information on second port.") return 1; } // Get the input, output1 and output2. vtkGraph* input = vtkGraph::SafeDownCast(inInfo->Get( vtkDataObject::DATA_OBJECT())); if(!input) { vtkErrorMacro("Failed to get input graph.") return 1; } if(vtkDirectedGraph::SafeDownCast(input)) { isDirectedGraph = true; } vtkGraph* output1 = vtkGraph::SafeDownCast( outInfo1->Get(vtkDataObject::DATA_OBJECT())); if(!output1) { vtkErrorMacro("Failed to get output1 graph.") return 1; } vtkGraph* output2 = vtkGraph::SafeDownCast( outInfo2->Get(vtkDataObject::DATA_OBJECT())); if(!output2) { vtkErrorMacro("Failed to get output2 graph.") return 1; } vtkSmartPointer<vtkFloatArray> edgeCM = vtkSmartPointer<vtkFloatArray>::New(); if(this->EdgeCentralityArrayName) { edgeCM->SetName(this->EdgeCentralityArrayName); } else { edgeCM->SetName("edge_centrality"); } boost::vtkGraphEdgePropertyMapHelper<vtkFloatArray*> helper(edgeCM); vtkSmartPointer<vtkDataArray> edgeWeight (0); if(this->UseEdgeWeightArray && this->EdgeWeightArrayName) { if(!this->InvertEdgeWeightArray) { edgeWeight = input->GetEdgeData()->GetArray(this->EdgeWeightArrayName); } else { vtkDataArray* weights = input->GetEdgeData()->GetArray(this->EdgeWeightArrayName); if(!weights) { vtkErrorMacro("Edge weight array " << this->EdgeWeightArrayName << " is not found or not a data array"); return 1; } edgeWeight.TakeReference( vtkDataArray::CreateDataArray(weights->GetDataType())); double range[2]; weights->GetRange(range); if(weights->GetNumberOfComponents() > 1) { vtkErrorMacro("Expecting single component array."); return 1; } for(int i=0; i < weights->GetDataSize(); ++i) { edgeWeight->InsertNextTuple1(range[1] - weights->GetTuple1(i)); } } if(!edgeWeight) { vtkErrorMacro(<<"Error: Edge weight array " << this->EdgeWeightArrayName << " is set but not found.\n"); return 1; } } // First compute the second output and the result will be used // as input for the first output. if(isDirectedGraph) { vtkMutableDirectedGraph* out2 = vtkMutableDirectedGraph::New(); // Copy the data to the second output (as this algorithm most likely // going to removed edges (and hence modifies the graph). out2->DeepCopy(input); if(edgeWeight) { boost::vtkGraphEdgePropertyMapHelper<vtkDataArray*> helper2(edgeWeight); boost::betweenness_centrality_clustering(out2, boost::bc_clustering_threshold<double>(this->Threshold, out2, false), helper, helper2, boost::get(boost::vertex_index, out2)); } else { boost::betweenness_centrality_clustering(out2, boost::bc_clustering_threshold<double>( this->Threshold, out2, false), helper); } out2->GetEdgeData()->AddArray(edgeCM); // Finally copy the results to the output. output2->ShallowCopy(out2); out2->Delete(); } else { vtkMutableUndirectedGraph* out2 = vtkMutableUndirectedGraph::New(); // Send the data to output2. out2->DeepCopy(input); if(edgeWeight) { boost::vtkGraphEdgePropertyMapHelper<vtkDataArray*> helper2(edgeWeight); boost::betweenness_centrality_clustering(out2, boost::bc_clustering_threshold<double>(this->Threshold, out2,false), helper, helper2, boost::get(boost::vertex_index, out2)); } else { boost::betweenness_centrality_clustering(out2, boost::bc_clustering_threshold<double>(this->Threshold, out2,false), helper); } out2->GetEdgeData()->AddArray(edgeCM); // Finally copy the results to the output. output2->ShallowCopy(out2); out2->Delete(); } // Now take care of the first output. vtkSmartPointer<vtkBoostConnectedComponents> bcc ( vtkSmartPointer<vtkBoostConnectedComponents>::New()); vtkSmartPointer<vtkGraph> output2Copy(0); if(isDirectedGraph) { output2Copy = vtkSmartPointer<vtkDirectedGraph>::New(); } else { output2Copy = vtkSmartPointer<vtkUndirectedGraph>::New(); } output2Copy->ShallowCopy(output2); bcc->SetInput(0, output2Copy); bcc->Update(); vtkSmartPointer<vtkGraph> bccOut = bcc->GetOutput(0); vtkSmartPointer<vtkAbstractArray> compArray (0); if(isDirectedGraph) { vtkSmartPointer<vtkDirectedGraph> out1 (vtkSmartPointer<vtkDirectedGraph>::New()); out1->ShallowCopy(input); compArray = bccOut->GetVertexData()->GetAbstractArray("component"); if(!compArray) { vtkErrorMacro("Unable to get component array.") return 1; } out1->GetVertexData()->AddArray(compArray); // Finally copy the output to the algorithm output. output1->ShallowCopy(out1); } else { vtkSmartPointer<vtkUndirectedGraph> out1 (vtkSmartPointer<vtkUndirectedGraph>::New()); out1->ShallowCopy(input); compArray = bccOut->GetVertexData()->GetAbstractArray("component"); if(!compArray) { vtkErrorMacro("Unable to get component array.") return 1; } out1->GetVertexData()->AddArray(compArray); // Finally copy the output to the algorithm output. output1->ShallowCopy(out1); } // Also add the components array to the second output. output2->GetVertexData()->AddArray(compArray); return 1; } //----------------------------------------------------------------------------- int vtkBoostBetweennessClustering::FillOutputPortInformation( int port, vtkInformation* info) { if(port == 0 || port == 1) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkGraph"); } return 1; } <|endoftext|>
<commit_before>// @(#)root/cont:$Id$ // Author: Fons Rademakers 04/08/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSeqCollection // // // // Sequenceable collection abstract base class. TSeqCollection's have // // an ordering relation, i.e. there is a first and last element. // // // ////////////////////////////////////////////////////////////////////////// #include "TSeqCollection.h" #include "TCollection.h" #include "TVirtualMutex.h" #include "TClass.h" #include "TMethodCall.h" ClassImp(TSeqCollection) //______________________________________________________________________________ Int_t TSeqCollection::IndexOf(const TObject *obj) const { // Return index of object in collection. Returns -1 when object not found. // Uses member IsEqual() to find object. Int_t idx = 0; TIter next(this); TObject *ob; while ((ob = next())) { if (ob->IsEqual(obj)) return idx; idx++; } return -1; } //______________________________________________________________________________ Int_t TSeqCollection::ObjCompare(TObject *a, TObject *b) { // Compare to objects in the collection. Use member Compare() of object a. if (a == 0 && b == 0) return 0; if (a == 0) return 1; if (b == 0) return -1; return a->Compare(b); } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t first, Int_t last) { // Sort array of TObject pointers using a quicksort algorithm. // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp; static int i; // "static" to save stack space int j; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) ; while (--j > first && ObjCompare(a[j], a[first]) > 0) ; if (i >= j) break; tmp = a[i]; a[i] = a[j]; a[j] = tmp; } if (j == first) { ++first; continue; } tmp = a[first]; a[first] = a[j]; a[j] = tmp; if (j - first < last - (j + 1)) { QSort(a, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, j + 1, last); last = j; // QSort(first, j); } } } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t nBs, TObject ***b, Int_t first, Int_t last) { // Sort array a of TObject pointers using a quicksort algorithm. // Arrays b will be sorted just like a (a determines the sort). // nBs is the number of TObject** arrays in b. // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp1, **tmp2; static int i; // "static" to save stack space int j,k; static int depth = 0; if(depth == 0 && nBs > 0) tmp2 = new TObject*[nBs]; depth++; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) {} while (--j > first && ObjCompare(a[j], a[first]) > 0) {} if (i >= j) break; tmp1 = a[i]; for(k=0;k<nBs;k++) tmp2[k] = b[k][i]; a[i] = a[j]; for(k=0;k<nBs;k++) b[k][i] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; } if (j == first) { ++first; continue; } tmp1 = a[first]; for(k=0;k<nBs;k++) tmp2[k] = b[k][first]; a[first] = a[j]; for(k=0;k<nBs;k++) b[k][first] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; if (j - first < last - (j + 1)) { QSort(a, nBs, b, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, nBs, b, j + 1, last); last = j; // QSort(first, j); } } depth--; if(depth == 0 && nBs > 0) delete [] tmp2; } //______________________________________________________________________________ Long64_t TSeqCollection::Merge(TCollection *list) { // Merge this collection with all collections coming in the input list. The // input list must contain other collections of objects compatible with the // ones in this collection and ordered in the same manner. For example, if this // collection contains a TH1 object and a tree, all collections in the input // list have to contain a histogram and a tree. In case the list contains // collections, the objects in the input lists must also be collections with // the same structure and number of objects. // // Example // ========= // this list // ____________ ---------------------| // | A (TH1F) | __________ | L1 (TSeqCollection)|- [A1, B1(C1,D1,E1)] // | B (TList)|-| C (TTree)| | L1 (TSeqCollection)|- [A2, B2(C2,D2,E2)] // |__________| | D (TH1F) | | ... |- [...] // | E (TH1F) | |____________________| // |__________| Long64_t nmerged = 0; if (IsEmpty() || !list) { Warning("Merge", "list is empty - nothing to merge"); return 0; } if (list->IsEmpty()) { Warning("Merge", "input list is empty - nothing to merge with"); return 0; } TIter nextobject(this); TIter nextlist(list); TObject *object; TObject *objtomerge; TObject *collcrt; TSeqCollection *templist; TMethodCall callEnv; Int_t indobj = 0; while ((object = nextobject())) { // loop objects in this collection // If current object is not mergeable just skip it if (!object->IsA()) { indobj++; // current object non-mergeable, go to next object continue; } callEnv.InitWithPrototype(object->IsA(), "Merge", "TCollection*"); if (!callEnv.IsValid()) { indobj++; // no Merge() interface, go to next object continue; } // Current object mergeable - get corresponding objects in input lists templist = (TSeqCollection*)IsA()->New(); nextlist.Reset(); while ((collcrt = nextlist())) { // loop input lists if (!collcrt->InheritsFrom(TSeqCollection::Class())) { Error("Merge", "some objects in the input list are not collections - merging aborted"); delete templist; return 0; } // The next object to be merged with is a collection // the iterator skips the 'holes' the collections, we also need to do so. objtomerge = ((TSeqCollection*)collcrt)->At(indobj); while (objtomerge == 0 && indobj < ((TSeqCollection*)collcrt)->LastIndex() ) { ++indobj; objtomerge = ((TSeqCollection*)collcrt)->At(indobj); } if (object->IsA() != objtomerge->IsA()) { Error("Merge", "object of type %s at index %d not matching object of type %s in input list", object->ClassName(), indobj, objtomerge->ClassName()); delete templist; return 0; } // Add object at index indobj in the temporary list templist->Add(objtomerge); nmerged++; } // Merge current object with objects in the temporary list callEnv.SetParam((Long_t) templist); callEnv.Execute(object); delete templist; indobj++; } return nmerged; } <commit_msg>From Andrei: Adds a protection in the Merge function when the object to merge is missing.<commit_after>// @(#)root/cont:$Id$ // Author: Fons Rademakers 04/08/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TSeqCollection // // // // Sequenceable collection abstract base class. TSeqCollection's have // // an ordering relation, i.e. there is a first and last element. // // // ////////////////////////////////////////////////////////////////////////// #include "TSeqCollection.h" #include "TCollection.h" #include "TVirtualMutex.h" #include "TClass.h" #include "TMethodCall.h" ClassImp(TSeqCollection) //______________________________________________________________________________ Int_t TSeqCollection::IndexOf(const TObject *obj) const { // Return index of object in collection. Returns -1 when object not found. // Uses member IsEqual() to find object. Int_t idx = 0; TIter next(this); TObject *ob; while ((ob = next())) { if (ob->IsEqual(obj)) return idx; idx++; } return -1; } //______________________________________________________________________________ Int_t TSeqCollection::ObjCompare(TObject *a, TObject *b) { // Compare to objects in the collection. Use member Compare() of object a. if (a == 0 && b == 0) return 0; if (a == 0) return 1; if (b == 0) return -1; return a->Compare(b); } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t first, Int_t last) { // Sort array of TObject pointers using a quicksort algorithm. // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp; static int i; // "static" to save stack space int j; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) ; while (--j > first && ObjCompare(a[j], a[first]) > 0) ; if (i >= j) break; tmp = a[i]; a[i] = a[j]; a[j] = tmp; } if (j == first) { ++first; continue; } tmp = a[first]; a[first] = a[j]; a[j] = tmp; if (j - first < last - (j + 1)) { QSort(a, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, j + 1, last); last = j; // QSort(first, j); } } } //______________________________________________________________________________ void TSeqCollection::QSort(TObject **a, Int_t nBs, TObject ***b, Int_t first, Int_t last) { // Sort array a of TObject pointers using a quicksort algorithm. // Arrays b will be sorted just like a (a determines the sort). // nBs is the number of TObject** arrays in b. // Uses ObjCompare() to compare objects. R__LOCKGUARD2(gCollectionMutex); static TObject *tmp1, **tmp2; static int i; // "static" to save stack space int j,k; static int depth = 0; if(depth == 0 && nBs > 0) tmp2 = new TObject*[nBs]; depth++; while (last - first > 1) { i = first; j = last; for (;;) { while (++i < last && ObjCompare(a[i], a[first]) < 0) {} while (--j > first && ObjCompare(a[j], a[first]) > 0) {} if (i >= j) break; tmp1 = a[i]; for(k=0;k<nBs;k++) tmp2[k] = b[k][i]; a[i] = a[j]; for(k=0;k<nBs;k++) b[k][i] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; } if (j == first) { ++first; continue; } tmp1 = a[first]; for(k=0;k<nBs;k++) tmp2[k] = b[k][first]; a[first] = a[j]; for(k=0;k<nBs;k++) b[k][first] = b[k][j]; a[j] = tmp1; for(k=0;k<nBs;k++) b[k][j] = tmp2[k]; if (j - first < last - (j + 1)) { QSort(a, nBs, b, first, j); first = j + 1; // QSort(j + 1, last); } else { QSort(a, nBs, b, j + 1, last); last = j; // QSort(first, j); } } depth--; if(depth == 0 && nBs > 0) delete [] tmp2; } //______________________________________________________________________________ Long64_t TSeqCollection::Merge(TCollection *list) { // Merge this collection with all collections coming in the input list. The // input list must contain other collections of objects compatible with the // ones in this collection and ordered in the same manner. For example, if this // collection contains a TH1 object and a tree, all collections in the input // list have to contain a histogram and a tree. In case the list contains // collections, the objects in the input lists must also be collections with // the same structure and number of objects. // // Example // ========= // this list // ____________ ---------------------| // | A (TH1F) | __________ | L1 (TSeqCollection)|- [A1, B1(C1,D1,E1)] // | B (TList)|-| C (TTree)| | L1 (TSeqCollection)|- [A2, B2(C2,D2,E2)] // |__________| | D (TH1F) | | ... |- [...] // | E (TH1F) | |____________________| // |__________| Long64_t nmerged = 0; if (IsEmpty() || !list) { Warning("Merge", "list is empty - nothing to merge"); return 0; } if (list->IsEmpty()) { Warning("Merge", "input list is empty - nothing to merge with"); return 0; } TIter nextobject(this); TIter nextlist(list); TObject *object; TObject *objtomerge; TObject *collcrt; TSeqCollection *templist; TMethodCall callEnv; Int_t indobj = 0; while ((object = nextobject())) { // loop objects in this collection // If current object is not mergeable just skip it if (!object->IsA()) { indobj++; // current object non-mergeable, go to next object continue; } callEnv.InitWithPrototype(object->IsA(), "Merge", "TCollection*"); if (!callEnv.IsValid()) { indobj++; // no Merge() interface, go to next object continue; } // Current object mergeable - get corresponding objects in input lists templist = (TSeqCollection*)IsA()->New(); nextlist.Reset(); Int_t indcoll = 0; while ((collcrt = nextlist())) { // loop input lists if (!collcrt->InheritsFrom(TSeqCollection::Class())) { Error("Merge", "some objects in the input list are not collections - merging aborted"); delete templist; return 0; } // The next object to be merged with is a collection // the iterator skips the 'holes' the collections, we also need to do so. objtomerge = ((TSeqCollection*)collcrt)->At(indobj); if (!objtomerge) { Warning("Merge", "Object of type %s (position %d in list) not found in list %d. Continuing...", object->ClassName(), indobj, indcoll); continue; } /* // Dangerous - may try to merge non-corresponding histograms (A.G) while (objtomerge == 0 && indobj < ((TSeqCollection*)collcrt)->LastIndex() ) { ++indobj; objtomerge = ((TSeqCollection*)collcrt)->At(indobj); } */ if (object->IsA() != objtomerge->IsA()) { Error("Merge", "object of type %s at index %d not matching object of type %s in input list", object->ClassName(), indobj, objtomerge->ClassName()); delete templist; return 0; } // Add object at index indobj in the temporary list templist->Add(objtomerge); nmerged++; } // Merge current object with objects in the temporary list callEnv.SetParam((Long_t) templist); callEnv.Execute(object); delete templist; indobj++; } return nmerged; } <|endoftext|>
<commit_before><commit_msg>control: add planning seq number into control estop reason.<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/control/control_component.h" #include <iomanip> #include <string> #include "modules/common/adapters/adapter_gflags.h" #include "cybertron/common/log.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/control/common/control_gflags.h" namespace apollo { namespace control { using apollo::canbus::Chassis; using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleStateProvider; using apollo::common::time::Clock; using apollo::control::ControlCommand; using apollo::control::PadMessage; using apollo::localization::LocalizationEstimate; using apollo::planning::ADCTrajectory; ControlComponent::ControlComponent() : monitor_logger_buffer_(common::monitor::MonitorMessageItem::CONTROL) {} bool ControlComponent::Init() { // init_time_ = Clock::NowInSeconds(); AINFO << "Control init, starting ..."; AINFO << "Loading gflag from file: " << ConfigFilePath(); google::SetCommandLineOption("flagfile", ConfigFilePath().c_str()); CHECK(apollo::common::util::GetProtoFromFile(FLAGS_control_conf_file, &control_conf_)) << "Unable to load control conf file: " + FLAGS_control_conf_file; AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded."; AINFO << "Conf file: " << ConfigFilePath() << " is loaded."; // set controller if (!controller_agent_.Init(&control_conf_).ok()) { monitor_logger_buffer_.ERROR("Control init controller failed! Stopping..."); return false; } chassis_reader_ = node_->CreateReader<Chassis>( control_conf_.chassis_channel(), [this](const std::shared_ptr<Chassis> &chassis) { ADEBUG << "Received chassis data: run chassis callback."; std::lock_guard<std::mutex> lock(mutex_); chassis_.CopyFrom(*chassis); }); trajectory_reader_ = node_->CreateReader<ADCTrajectory>( control_conf_.chassis_channel(), [this](const std::shared_ptr<ADCTrajectory> &trajectory) { ADEBUG << "Received chassis data: run trajectory callback."; std::lock_guard<std::mutex> lock(mutex_); trajectory_.CopyFrom(*trajectory); }); localization_reader_ = node_->CreateReader<LocalizationEstimate>( control_conf_.localization_channel(), [this](const std::shared_ptr<LocalizationEstimate> &localization) { ADEBUG << "Received control data: run localization message callback."; std::lock_guard<std::mutex> lock(mutex_); localization_.CopyFrom(*localization); }); pad_msg_reader_ = node_->CreateReader<PadMessage>( control_conf_.pad_msg_channel(), [this](const std::shared_ptr<PadMessage> &pad_msg) { ADEBUG << "Received control data: run pad message callback."; OnPad(*pad_msg); }); control_cmd_writer_ = node_->CreateWriter<ControlCommand>( control_conf_.control_command_channel()); return true; } void ControlComponent::OnPad(const PadMessage &pad) { pad_msg_ = pad; ADEBUG << "Received Pad Msg:" << pad.DebugString(); AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!"; // do something according to pad message if (pad_msg_.action() == DrivingAction::RESET) { AINFO << "Control received RESET action!"; estop_ = false; estop_reason_.clear(); } pad_received_ = true; } void ControlComponent::OnMonitor( const common::monitor::MonitorMessage &monitor_message) { for (const auto &item : monitor_message.item()) { if (item.log_level() == common::monitor::MonitorMessageItem::FATAL) { estop_ = true; return; } } } Status ControlComponent::ProduceControlCommand( ControlCommand *control_command) { Status status = CheckInput(); // check data if (!status.ok()) { AERROR_EVERY(100) << "Control input data failed: " << status.error_message(); control_command->mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::DISALLOW_ENGAGE); control_command->mutable_engage_advice()->set_reason( status.error_message()); estop_ = true; estop_reason_ = status.error_message(); } else { Status status_ts = CheckTimestamp(); if (!status_ts.ok()) { AERROR << "Input messages timeout"; // estop_ = true; status = status_ts; if (chassis_.driving_mode() != apollo::canbus::Chassis::COMPLETE_AUTO_DRIVE) { control_command->mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::DISALLOW_ENGAGE); control_command->mutable_engage_advice()->set_reason( status.error_message()); } } else { control_command->mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::READY_TO_ENGAGE); } } // check estop estop_ = control_conf_.enable_persistent_estop() ? estop_ || trajectory_.estop().is_estop() : trajectory_.estop().is_estop(); if (trajectory_.estop().is_estop()) { estop_reason_ = "estop from planning"; } // if planning set estop, then no control process triggered if (!estop_) { if (chassis_.driving_mode() == Chassis::COMPLETE_MANUAL) { controller_agent_.Reset(); AINFO_EVERY(100) << "Reset Controllers in Manual Mode"; } auto debug = control_command->mutable_debug()->mutable_input_debug(); debug->mutable_localization_header()->CopyFrom(localization_.header()); debug->mutable_canbus_header()->CopyFrom(chassis_.header()); debug->mutable_trajectory_header()->CopyFrom(trajectory_.header()); Status status_compute = controller_agent_.ComputeControlCommand( &localization_, &chassis_, &trajectory_, control_command); if (!status_compute.ok()) { AERROR << "Control main function failed" << " with localization: " << localization_.ShortDebugString() << " with chassis: " << chassis_.ShortDebugString() << " with trajectory: " << trajectory_.ShortDebugString() << " with cmd: " << control_command->ShortDebugString() << " status:" << status_compute.error_message(); estop_ = true; estop_reason_ = status_compute.error_message(); status = status_compute; } } if (estop_) { AWARN_EVERY(100) << "Estop triggered! No control core method executed!"; // set Estop command control_command->set_speed(0); control_command->set_throttle(0); control_command->set_brake(control_conf_.soft_estop_brake()); control_command->set_gear_location(Chassis::GEAR_DRIVE); } // check signal if (trajectory_.decision().has_vehicle_signal()) { control_command->mutable_signal()->CopyFrom( trajectory_.decision().vehicle_signal()); } return status; } bool ControlComponent::Proc() { // set initial vehicle state by cmd // need to sleep, because advertised channel is not ready immediately // simple test shows a short delay of 80 ms or so AINFO << "Control resetting vehicle state, sleeping for 1000 ms ..."; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // should init_vehicle first, let car enter work status, then use status msg // trigger control AINFO << "Control default driving action is " << DrivingAction_Name(control_conf_.action()); pad_msg_.set_action(control_conf_.action()); double start_timestamp = Clock::NowInSeconds(); if (control_conf_.is_control_test_mode() && control_conf_.control_test_duration() > 0 && (start_timestamp - init_time_) > control_conf_.control_test_duration()) { AERROR << "Control finished testing. exit"; return false; } ControlCommand control_command; Status status = ProduceControlCommand(&control_command); AERROR_IF(!status.ok()) << "Failed to produce control command:" << status.error_message(); double end_timestamp = Clock::NowInSeconds(); if (pad_received_) { control_command.mutable_pad_msg()->CopyFrom(pad_msg_); pad_received_ = false; } const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms); control_command.mutable_latency_stats()->set_total_time_exceeded( time_diff_ms < control_conf_.control_period()); ADEBUG << "control cycle time is: " << time_diff_ms << " ms."; status.Save(control_command.mutable_header()->mutable_status()); // forward estop reason among following control frames. if (estop_) { control_command.mutable_header()->mutable_status()->set_msg(estop_reason_); } // set header control_command.mutable_header()->set_lidar_timestamp( trajectory_.header().lidar_timestamp()); control_command.mutable_header()->set_camera_timestamp( trajectory_.header().camera_timestamp()); control_command.mutable_header()->set_radar_timestamp( trajectory_.header().radar_timestamp()); common::util::FillHeader(node_->Name(), &control_command); ADEBUG << control_command.ShortDebugString(); if (control_conf_.is_control_test_mode()) { ADEBUG << "Skip publish control command in test mode"; return true; } control_cmd_writer_->Write(std::make_shared<ControlCommand>(control_command)); return true; } Status ControlComponent::CheckInput() { if (localization_reader_ == nullptr) { AWARN_EVERY(100) << "No Localization msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No localization msg"); } ADEBUG << "Received localization:" << localization_.ShortDebugString(); if (chassis_reader_ == nullptr) { AWARN_EVERY(100) << "No Chassis msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No chassis msg"); } ADEBUG << "Received chassis:" << chassis_.ShortDebugString(); if (trajectory_reader_ == nullptr) { AWARN_EVERY(100) << "No planning msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No planning msg"); } if (!trajectory_.estop().is_estop() && trajectory_.trajectory_point_size() == 0) { AWARN_EVERY(100) << "planning has no trajectory point. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "planning has no trajectory point."); } for (auto &trajectory_point : *trajectory_.mutable_trajectory_point()) { if (trajectory_point.v() < control_conf_.minimum_speed_resolution()) { trajectory_point.set_v(0.0); trajectory_point.set_a(0.0); } } VehicleStateProvider::Instance()->Update(localization_, chassis_); return Status::OK(); } Status ControlComponent::CheckTimestamp() { if (!control_conf_.enable_input_timestamp_check() || control_conf_.is_control_test_mode()) { ADEBUG << "Skip input timestamp check by gflags."; return Status::OK(); } double current_timestamp = Clock::NowInSeconds(); double localization_diff = current_timestamp - localization_.header().timestamp_sec(); if (localization_diff > (control_conf_.max_localization_miss_num() * control_conf_.localization_period())) { AERROR << "Localization msg lost for " << std::setprecision(6) << localization_diff << "s"; monitor_logger_buffer_.ERROR("Localization msg lost"); return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout"); } double chassis_diff = current_timestamp - chassis_.header().timestamp_sec(); if (chassis_diff > (control_conf_.max_chassis_miss_num() * control_conf_.chassis_period())) { AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff << "s"; monitor_logger_buffer_.ERROR("Chassis msg lost"); return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout"); } double trajectory_diff = current_timestamp - trajectory_.header().timestamp_sec(); if (trajectory_diff > (control_conf_.max_planning_miss_num() * control_conf_.trajectory_period())) { AERROR << "Trajectory msg lost for " << std::setprecision(6) << trajectory_diff << "s"; monitor_logger_buffer_.ERROR("Trajectory msg lost"); return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout"); } return Status::OK(); } } // namespace control } // namespace apollo <commit_msg>Control : move logic from Proc() to Init()<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/control/control_component.h" #include <iomanip> #include <string> #include "cybertron/common/log.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/control/common/control_gflags.h" namespace apollo { namespace control { using apollo::canbus::Chassis; using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::VehicleStateProvider; using apollo::common::time::Clock; using apollo::control::ControlCommand; using apollo::control::PadMessage; using apollo::localization::LocalizationEstimate; using apollo::planning::ADCTrajectory; ControlComponent::ControlComponent() : monitor_logger_buffer_(common::monitor::MonitorMessageItem::CONTROL) {} bool ControlComponent::Init() { // init_time_ = Clock::NowInSeconds(); AINFO << "Control init, starting ..."; AINFO << "Loading gflag from file: " << ConfigFilePath(); google::SetCommandLineOption("flagfile", ConfigFilePath().c_str()); CHECK(apollo::common::util::GetProtoFromFile(FLAGS_control_conf_file, &control_conf_)) << "Unable to load control conf file: " + FLAGS_control_conf_file; AINFO << "Conf file: " << FLAGS_control_conf_file << " is loaded."; AINFO << "Conf file: " << ConfigFilePath() << " is loaded."; // set controller if (!controller_agent_.Init(&control_conf_).ok()) { monitor_logger_buffer_.ERROR("Control init controller failed! Stopping..."); return false; } chassis_reader_ = node_->CreateReader<Chassis>( control_conf_.chassis_channel(), [this](const std::shared_ptr<Chassis> &chassis) { ADEBUG << "Received chassis data: run chassis callback."; std::lock_guard<std::mutex> lock(mutex_); chassis_.CopyFrom(*chassis); }); trajectory_reader_ = node_->CreateReader<ADCTrajectory>( control_conf_.chassis_channel(), [this](const std::shared_ptr<ADCTrajectory> &trajectory) { ADEBUG << "Received chassis data: run trajectory callback."; std::lock_guard<std::mutex> lock(mutex_); trajectory_.CopyFrom(*trajectory); }); localization_reader_ = node_->CreateReader<LocalizationEstimate>( control_conf_.localization_channel(), [this](const std::shared_ptr<LocalizationEstimate> &localization) { ADEBUG << "Received control data: run localization message callback."; std::lock_guard<std::mutex> lock(mutex_); localization_.CopyFrom(*localization); }); pad_msg_reader_ = node_->CreateReader<PadMessage>( control_conf_.pad_msg_channel(), [this](const std::shared_ptr<PadMessage> &pad_msg) { ADEBUG << "Received control data: run pad message callback."; OnPad(*pad_msg); }); control_cmd_writer_ = node_->CreateWriter<ControlCommand>( control_conf_.control_command_channel()); // set initial vehicle state by cmd // need to sleep, because advertised channel is not ready immediately // simple test shows a short delay of 80 ms or so AINFO << "Control resetting vehicle state, sleeping for 1000 ms ..."; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // should init_vehicle first, let car enter work status, then use status msg // trigger control AINFO << "Control default driving action is " << DrivingAction_Name(control_conf_.action()); pad_msg_.set_action(control_conf_.action()); return true; } void ControlComponent::OnPad(const PadMessage &pad) { pad_msg_ = pad; ADEBUG << "Received Pad Msg:" << pad.DebugString(); AERROR_IF(!pad_msg_.has_action()) << "pad message check failed!"; // do something according to pad message if (pad_msg_.action() == DrivingAction::RESET) { AINFO << "Control received RESET action!"; estop_ = false; estop_reason_.clear(); } pad_received_ = true; } void ControlComponent::OnMonitor( const common::monitor::MonitorMessage &monitor_message) { for (const auto &item : monitor_message.item()) { if (item.log_level() == common::monitor::MonitorMessageItem::FATAL) { estop_ = true; return; } } } Status ControlComponent::ProduceControlCommand( ControlCommand *control_command) { Status status = CheckInput(); // check data if (!status.ok()) { AERROR_EVERY(100) << "Control input data failed: " << status.error_message(); control_command->mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::DISALLOW_ENGAGE); control_command->mutable_engage_advice()->set_reason( status.error_message()); estop_ = true; estop_reason_ = status.error_message(); } else { Status status_ts = CheckTimestamp(); if (!status_ts.ok()) { AERROR << "Input messages timeout"; // estop_ = true; status = status_ts; if (chassis_.driving_mode() != apollo::canbus::Chassis::COMPLETE_AUTO_DRIVE) { control_command->mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::DISALLOW_ENGAGE); control_command->mutable_engage_advice()->set_reason( status.error_message()); } } else { control_command->mutable_engage_advice()->set_advice( apollo::common::EngageAdvice::READY_TO_ENGAGE); } } // check estop estop_ = control_conf_.enable_persistent_estop() ? estop_ || trajectory_.estop().is_estop() : trajectory_.estop().is_estop(); if (trajectory_.estop().is_estop()) { estop_reason_ = "estop from planning"; } // if planning set estop, then no control process triggered if (!estop_) { if (chassis_.driving_mode() == Chassis::COMPLETE_MANUAL) { controller_agent_.Reset(); AINFO_EVERY(100) << "Reset Controllers in Manual Mode"; } auto debug = control_command->mutable_debug()->mutable_input_debug(); debug->mutable_localization_header()->CopyFrom(localization_.header()); debug->mutable_canbus_header()->CopyFrom(chassis_.header()); debug->mutable_trajectory_header()->CopyFrom(trajectory_.header()); Status status_compute = controller_agent_.ComputeControlCommand( &localization_, &chassis_, &trajectory_, control_command); if (!status_compute.ok()) { AERROR << "Control main function failed" << " with localization: " << localization_.ShortDebugString() << " with chassis: " << chassis_.ShortDebugString() << " with trajectory: " << trajectory_.ShortDebugString() << " with cmd: " << control_command->ShortDebugString() << " status:" << status_compute.error_message(); estop_ = true; estop_reason_ = status_compute.error_message(); status = status_compute; } } if (estop_) { AWARN_EVERY(100) << "Estop triggered! No control core method executed!"; // set Estop command control_command->set_speed(0); control_command->set_throttle(0); control_command->set_brake(control_conf_.soft_estop_brake()); control_command->set_gear_location(Chassis::GEAR_DRIVE); } // check signal if (trajectory_.decision().has_vehicle_signal()) { control_command->mutable_signal()->CopyFrom( trajectory_.decision().vehicle_signal()); } return status; } bool ControlComponent::Proc() { double start_timestamp = Clock::NowInSeconds(); if (control_conf_.is_control_test_mode() && control_conf_.control_test_duration() > 0 && (start_timestamp - init_time_) > control_conf_.control_test_duration()) { AERROR << "Control finished testing. exit"; return false; } ControlCommand control_command; Status status = ProduceControlCommand(&control_command); AERROR_IF(!status.ok()) << "Failed to produce control command:" << status.error_message(); double end_timestamp = Clock::NowInSeconds(); if (pad_received_) { control_command.mutable_pad_msg()->CopyFrom(pad_msg_); pad_received_ = false; } const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; control_command.mutable_latency_stats()->set_total_time_ms(time_diff_ms); control_command.mutable_latency_stats()->set_total_time_exceeded( time_diff_ms < control_conf_.control_period()); ADEBUG << "control cycle time is: " << time_diff_ms << " ms."; status.Save(control_command.mutable_header()->mutable_status()); // forward estop reason among following control frames. if (estop_) { control_command.mutable_header()->mutable_status()->set_msg(estop_reason_); } // set header control_command.mutable_header()->set_lidar_timestamp( trajectory_.header().lidar_timestamp()); control_command.mutable_header()->set_camera_timestamp( trajectory_.header().camera_timestamp()); control_command.mutable_header()->set_radar_timestamp( trajectory_.header().radar_timestamp()); common::util::FillHeader(node_->Name(), &control_command); ADEBUG << control_command.ShortDebugString(); if (control_conf_.is_control_test_mode()) { ADEBUG << "Skip publish control command in test mode"; return true; } control_cmd_writer_->Write(std::make_shared<ControlCommand>(control_command)); return true; } Status ControlComponent::CheckInput() { if (localization_reader_ == nullptr) { AWARN_EVERY(100) << "No Localization msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No localization msg"); } ADEBUG << "Received localization:" << localization_.ShortDebugString(); if (chassis_reader_ == nullptr) { AWARN_EVERY(100) << "No Chassis msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No chassis msg"); } ADEBUG << "Received chassis:" << chassis_.ShortDebugString(); if (trajectory_reader_ == nullptr) { AWARN_EVERY(100) << "No planning msg yet. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "No planning msg"); } if (!trajectory_.estop().is_estop() && trajectory_.trajectory_point_size() == 0) { AWARN_EVERY(100) << "planning has no trajectory point. "; return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "planning has no trajectory point."); } for (auto &trajectory_point : *trajectory_.mutable_trajectory_point()) { if (trajectory_point.v() < control_conf_.minimum_speed_resolution()) { trajectory_point.set_v(0.0); trajectory_point.set_a(0.0); } } VehicleStateProvider::Instance()->Update(localization_, chassis_); return Status::OK(); } Status ControlComponent::CheckTimestamp() { if (!control_conf_.enable_input_timestamp_check() || control_conf_.is_control_test_mode()) { ADEBUG << "Skip input timestamp check by gflags."; return Status::OK(); } double current_timestamp = Clock::NowInSeconds(); double localization_diff = current_timestamp - localization_.header().timestamp_sec(); if (localization_diff > (control_conf_.max_localization_miss_num() * control_conf_.localization_period())) { AERROR << "Localization msg lost for " << std::setprecision(6) << localization_diff << "s"; monitor_logger_buffer_.ERROR("Localization msg lost"); return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Localization msg timeout"); } double chassis_diff = current_timestamp - chassis_.header().timestamp_sec(); if (chassis_diff > (control_conf_.max_chassis_miss_num() * control_conf_.chassis_period())) { AERROR << "Chassis msg lost for " << std::setprecision(6) << chassis_diff << "s"; monitor_logger_buffer_.ERROR("Chassis msg lost"); return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Chassis msg timeout"); } double trajectory_diff = current_timestamp - trajectory_.header().timestamp_sec(); if (trajectory_diff > (control_conf_.max_planning_miss_num() * control_conf_.trajectory_period())) { AERROR << "Trajectory msg lost for " << std::setprecision(6) << trajectory_diff << "s"; monitor_logger_buffer_.ERROR("Trajectory msg lost"); return Status(ErrorCode::CONTROL_COMPUTE_ERROR, "Trajectory msg timeout"); } return Status::OK(); } } // namespace control } // namespace apollo <|endoftext|>
<commit_before>/** Copyright 2014-2015 Jason R. Wendlandt 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. */ #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Graphics/RenderWindow.h" #include "Toolbox/Logger.h" namespace alpha { /** Initialize global window to nullptr */ GLFWwindow * g_pWindow = nullptr; RenderWindow::RenderWindow() { } RenderWindow::~RenderWindow() { } bool RenderWindow::Initialize() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // opengl 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); g_pWindow = glfwCreateWindow(800, 600, "ALPHA Engine", nullptr, nullptr); glfwMakeContextCurrent(g_pWindow); if (g_pWindow == NULL) { LOG_ERR("Failed to create GLFW window."); glfwTerminate(); return false; } return true; } bool RenderWindow::Update(double /*currentTime*/, double /*elapsedTime*/) { // play nicely with existing window system (X11) if (glfwWindowShouldClose(g_pWindow)) { return false; } else { glfwPollEvents(); } return true; } bool RenderWindow::Shutdown() { return true; } void RenderWindow::Render() { // XXX remove this? probably not needed } GLFWwindow * RenderWindow::GetWindow() const { return g_pWindow; } } <commit_msg>Cleaned up a bit of code<commit_after>/** Copyright 2014-2015 Jason R. Wendlandt 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. */ #define GLEW_STATIC #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Graphics/RenderWindow.h" #include "Toolbox/Logger.h" namespace alpha { /** Initialize global window to nullptr */ GLFWwindow * g_pWindow = nullptr; RenderWindow::RenderWindow() { } RenderWindow::~RenderWindow() { } bool RenderWindow::Initialize() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // opengl 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); g_pWindow = glfwCreateWindow(800, 600, "ALPHA Engine", nullptr, nullptr); glfwMakeContextCurrent(g_pWindow); if (g_pWindow == NULL) { LOG_ERR("Failed to create GLFW window."); glfwTerminate(); return false; } return true; } bool RenderWindow::Update(double /*currentTime*/, double /*elapsedTime*/) { // play nicely with the existing window system (X11) if (glfwWindowShouldClose(g_pWindow)) { return false; } glfwPollEvents(); return true; } bool RenderWindow::Shutdown() { return true; } void RenderWindow::Render() { // XXX remove this? probably not needed } GLFWwindow * RenderWindow::GetWindow() const { return g_pWindow; } } <|endoftext|>
<commit_before>#ifndef K3_VECTOR #define K3_VECTOR #include "boost/serialization/vector.hpp" #include "boost/serialization/base_object.hpp" #include "STLDataspace.hpp" #include "serialization/Json.hpp" #include "serialization/Yaml.hpp" namespace K3 { template <template <class> class Derived, class Elem> using VectorDS = STLDS<Derived, std::vector, Elem>; template <class Elem> class Vector : public VectorDS<K3::Vector, Elem> { using Super = VectorDS<K3::Vector, Elem>; public: Vector() : Super() {} Vector(const Super& c) : Super(c) {} Vector(Super&& c) : Super(std::move(c)) {} Elem at(int i) const { auto& vec = Super::getConstContainer(); return vec[i]; } template<class F, class G> auto safe_at(int i, F f, G g) const { auto& vec = Super::getConstContainer(); if (i < vec.size()) { return g(vec[i]); } else { return f(unit_t {}); } } template<class F> auto unsafe_at(int i, F f) const { auto& vec = Super::getConstContainer(); return f(vec[i]); } template <class Q> unit_t set(int i, Q&& q) { auto& vec = Super::getContainer(); vec[i] = std::forward<Q>(q); return unit_t(); } template <class Q> unit_t insert_at(int i, Q&& q) { auto& vec = Super::getContainer(); if (i >= vec.size()) { vec.resize(i + 1); } vec[i] = std::forward<Q>(q); return unit_t(); } template <class F> unit_t update_at(int i, F f) { auto& vec = Super::getContainer(); vec[i] = f(std::move(vec[i])); return unit_t(); } auto erase_at(int i) { auto& vec = Super::getContainer(); return std::move(vec[i]); } template <class Q> Elem swap(int i, Q&& q) { auto& vec = Super::getContainer(); auto old = std::move(vec[i]); vec[i] = std::forward<Q>(q); return old; } template<class Archive> void serialize(Archive &ar) { ar & yas::base_object<VectorDS<K3::Vector, Elem>>(*this); } template <class Archive> void serialize(Archive& ar, const unsigned int) { ar& boost::serialization::base_object<VectorDS<K3::Vector, Elem>>( *this); } private: friend class boost::serialization::access; }; // Specialization for a vector of bools. template <> class Vector<R_elem<bool>> : public VectorDS<K3::Vector, bool> { using Elem = bool; using RElem = R_elem<bool>; using Super = VectorDS<K3::Vector, bool>; using Container = std::vector<bool>; public: Vector() : Super() {} Vector(const Super& c) : Super(c) {} Vector(Super&& c) : Super(std::move(c)) {} template <class I> class bool_iterator : public std::iterator<std::forward_iterator_tag, RElem> { public: template <class _I> bool_iterator(Container& _c, _I&& _i) : c(_c), i(static_cast<I>(std::forward<_I>(_i))) {} bool_iterator& operator++() { i++; return *this; } bool_iterator operator++(int) { bool_iterator t = *this; *this++; return t; } auto operator -> () const { auto c = const_cast<RElem*>(&current); *c = RElem{ *i }; return &current; } auto& operator*() const { auto c = const_cast<RElem*>(&current); *c = RElem{ *i }; return current; } bool operator==(const bool_iterator& other) const { return i == other.i; } bool operator!=(const bool_iterator& other) const { return i != other.i; } private: Container& c; I i; RElem current; }; using iterator = bool_iterator<std::vector<bool>::iterator>; using const_iterator = bool_iterator<std::vector<bool>::const_iterator>; iterator begin() { auto c = Super::getContainer(); return iterator(c, c.begin()); } iterator end() { auto c = Super::getContainer(); return iterator(c, c.end()); } const_iterator begin() const { auto c = Super::getConstContainer(); return const_iterator(c, c.begin()); } const_iterator end() const { auto c = Super::getConstContainer(); return const_iterator(c, c.end()); } //////////////////////////////////// // Accessors. template <class F, class G> auto peek(F f, G g) const { auto it = container.begin(); if (it == container.end()) { return f(unit_t{}); } else { return g(RElem{ *it }); } } RElem at(int i) const { auto& vec = Super::getConstContainer(); return RElem{ vec[i] }; } template<class F, class G> auto safe_at(int i, F f, G g) const { auto& vec = Super::getConstContainer(); if (i < vec.size()) { return g(RElem{ vec[i] }); } else { return f(unit_t {}); } } template<class F> auto unsafe_at(int i, F f) const { auto& vec = Super::getConstContainer(); return f(RElem{ vec[i] }); } unit_t set(int i, RElem&& v) { auto& vec = Super::getContainer(); vec[i] = v.elem; return unit_t(); } unit_t insert(RElem &&e) { container.insert(container.end(), e.elem); return unit_t(); } unit_t update(const RElem& v, RElem&& v2) { auto it = std::find(container.begin(), container.end(), v.elem); if (it != container.end()) { *it = v2.elem; } return unit_t(); } unit_t erase(const RElem& v) { auto it = std::find(container.begin(), container.end(), v.elem); if (it != container.end()) { container.erase(it); } return unit_t(); } unit_t insert_at(int i, RElem&& v) { auto& vec = Super::getContainer(); if (i >= vec.size()) { vec.resize(i + 1); } vec[i] = v.elem; return unit_t(); } template <class F> unit_t update_at(int i, F f) { auto& vec = Super::getContainer(); vec[i] = f(RElem{ vec[i] }).elem; return unit_t(); } auto erase_at(int i) { auto& vec = Super::getContainer(); return RElem { vec[i] }; } RElem swap(int i, RElem&& q) { auto& vec = Super::getContainer(); auto old = vec[i]; vec[i] = q.elem; return RElem{ old }; } template<typename Fun> unit_t iterate(Fun f) const { for (const Elem& e : container) { f(RElem{ e }); } return unit_t(); } template<typename Fun> auto map(Fun f) const -> Vector<R_elem<RT<Fun, RElem>>> const { Vector<R_elem<RT<Fun, RElem>>> result; for (const Elem &e : container) { result.insert(R_elem<RT<Fun, RElem>> { f(RElem{ e }) }); } return result; } template<typename Fun> Vector<RElem> filter(Fun predicate) const { Vector<RElem> result; for (const Elem &e : container) { if (predicate(RElem{ e })) { result.insert(e); } } return result; } template<typename Fun, typename Acc> Acc fold(Fun f, Acc acc) const { for (const Elem &e : container) { acc = f(std::move(acc), RElem{ e }); } return acc; } // TODO: group by and ext transformers. template<class Archive> void serialize(Archive &ar) { ar & yas::base_object<VectorDS<K3::Vector, Elem>>(*this); } template <class Archive> void serialize(Archive& ar, const unsigned int) { ar& boost::serialization::base_object<VectorDS<K3::Vector, Elem>>(*this); } private: friend class boost::serialization::access; }; } // namespace K3 namespace YAML { template <class E> struct convert<K3::Vector<E>> { static Node encode(const K3::Vector<E>& c) { Node node; auto container = c.getConstContainer(); if (container.size() > 0) { for (auto i : container) { node.push_back(convert<E>::encode(i)); } } else { node = YAML::Load("[]"); } return node; } static bool decode(const Node& node, K3::Vector<E>& c) { for (auto& i : node) { c.insert(i.as<E>()); } return true; } }; // Specialization for a vector of bools. template <> struct convert<K3::Vector<R_elem<bool>>> { static Node encode(const K3::Vector<R_elem<bool>>& c) { Node node; auto container = c.getConstContainer(); if (container.size() > 0) { for (auto i : container) { node.push_back(convert<bool>::encode(i)); } } else { node = YAML::Load("[]"); } return node; } static bool decode(const Node& node, K3::Vector<R_elem<bool>>& c) { for (auto& i : node) { c.insert(i.as<bool>()); } return true; } }; } // namespace YAML namespace JSON { using namespace rapidjson; template <class E> struct convert<K3::Vector<E>> { template <class Allocator> static Value encode(const K3::Vector<E>& c, Allocator& al) { Value v; v.SetObject(); v.AddMember("type", Value("Vector"), al); Value inner; inner.SetArray(); for (const auto& e : c.getConstContainer()) { inner.PushBack(convert<E>::encode(e, al), al); } v.AddMember("value", inner.Move(), al); return v; } }; template <> struct convert<K3::Vector<R_elem<bool>>> { template <class Allocator> static Value encode(const K3::Vector<R_elem<bool>>& c, Allocator& al) { Value v; v.SetObject(); v.AddMember("type", Value("Vector"), al); Value inner; inner.SetArray(); for (const auto& e : c.getConstContainer()) { inner.PushBack(convert<bool>::encode(e, al), al); } v.AddMember("value", inner.Move(), al); return v; } }; } // namespace JSON #endif <commit_msg>vector: some attempted fixes<commit_after>#ifndef K3_VECTOR #define K3_VECTOR #include "boost/serialization/vector.hpp" #include "boost/serialization/base_object.hpp" #include "STLDataspace.hpp" #include "serialization/Json.hpp" #include "serialization/Yaml.hpp" namespace K3 { template <template <class> class Derived, class Elem> using VectorDS = STLDS<Derived, std::vector, Elem>; template <class Elem> class Vector : public VectorDS<K3::Vector, Elem> { using Super = VectorDS<K3::Vector, Elem>; public: Vector() : Super() {} Vector(const Super& c) : Super(c) {} Vector(Super&& c) : Super(std::move(c)) {} Elem at(int i) const { auto& vec = Super::getConstContainer(); return vec[i]; } template<class F, class G> auto safe_at(int i, F f, G g) const { auto& vec = Super::getConstContainer(); if (i < vec.size()) { return g(vec[i]); } else { return f(unit_t {}); } } template<class F> auto unsafe_at(int i, F f) const { auto& vec = Super::getConstContainer(); return f(vec[i]); } template <class Q> unit_t set(int i, Q&& q) { auto& vec = Super::getContainer(); vec[i] = std::forward<Q>(q); return unit_t(); } template <class Q> unit_t insert_at(int i, Q&& q) { auto& vec = Super::getContainer(); if (i >= vec.size()) { vec.resize(i + 1); } vec[i] = std::forward<Q>(q); return unit_t(); } template <class F> unit_t update_at(int i, F f) { auto& vec = Super::getContainer(); vec[i] = f(std::move(vec[i])); return unit_t(); } auto erase_at(int i) { auto& vec = Super::getContainer(); return std::move(vec[i]); } template <class Q> Elem swap(int i, Q&& q) { auto& vec = Super::getContainer(); auto old = std::move(vec[i]); vec[i] = std::forward<Q>(q); return old; } template<class Archive> void serialize(Archive &ar) { ar & yas::base_object<VectorDS<K3::Vector, Elem>>(*this); } template <class Archive> void serialize(Archive& ar, const unsigned int) { ar& boost::serialization::base_object<VectorDS<K3::Vector, Elem>>( *this); } private: friend class boost::serialization::access; }; // Specialization for a vector of bools. template <> class Vector<R_elem<bool>> : public VectorDS<K3::Vector, bool> { using Elem = bool; using RElem = R_elem<bool>; using Super = VectorDS<K3::Vector, bool>; using Container = std::vector<bool>; public: Vector() : Super() {} Vector(const Super& c) : Super(c) {} Vector(Super&& c) : Super(std::move(c)) {} template <class I> class bool_iterator : public std::iterator<std::forward_iterator_tag, RElem> { public: template <class _I> bool_iterator(Container& _c, _I&& _i) : c(_c), i(static_cast<I>(std::forward<_I>(_i))) {} bool_iterator& operator++() { i++; return *this; } bool_iterator operator++(int) { bool_iterator t = *this; i++; return t; } auto operator -> () const { current = RElem(*i); return &current; } auto& operator*() const { current = RElem(*i); return current; } bool operator==(const bool_iterator& other) const { return i == other.i; } bool operator!=(const bool_iterator& other) const { return i != other.i; } private: Container& c; I i; RElem current; }; using iterator = bool_iterator<std::vector<bool>::iterator>; using const_iterator = bool_iterator<std::vector<bool>::const_iterator>; iterator begin() { auto c = Super::getContainer(); return iterator(c, c.begin()); } iterator end() { auto c = Super::getContainer(); return iterator(c, c.end()); } const_iterator begin() const { auto c = Super::getConstContainer(); return const_iterator(c, c.begin()); } const_iterator end() const { auto c = Super::getConstContainer(); return const_iterator(c, c.end()); } //////////////////////////////////// // Accessors. template <class F, class G> auto peek(F f, G g) const { auto it = container.begin(); if (it == container.end()) { return f(unit_t{}); } else { return g(RElem{ *it }); } } RElem at(int i) const { auto& vec = Super::getConstContainer(); return RElem{ vec[i] }; } template<class F, class G> auto safe_at(int i, F f, G g) const { auto& vec = Super::getConstContainer(); if (i < vec.size()) { return g(RElem{ vec[i] }); } else { return f(unit_t {}); } } template<class F> auto unsafe_at(int i, F f) const { auto& vec = Super::getConstContainer(); return f(RElem{ vec[i] }); } unit_t set(int i, RElem&& v) { auto& vec = Super::getContainer(); vec[i] = v.elem; return unit_t(); } unit_t insert(RElem &&e) { container.insert(container.end(), e.elem); return unit_t(); } unit_t update(const RElem& v, RElem&& v2) { auto it = std::find(container.begin(), container.end(), v.elem); if (it != container.end()) { *it = v2.elem; } return unit_t(); } unit_t erase(const RElem& v) { auto it = std::find(container.begin(), container.end(), v.elem); if (it != container.end()) { container.erase(it); } return unit_t(); } unit_t insert_at(int i, RElem&& v) { auto& vec = Super::getContainer(); if (i >= vec.size()) { vec.resize(i + 1); } vec[i] = v.elem; return unit_t(); } template <class F> unit_t update_at(int i, F f) { auto& vec = Super::getContainer(); vec[i] = f(RElem{ vec[i] }).elem; return unit_t(); } auto erase_at(int i) { auto& vec = Super::getContainer(); return RElem { vec[i] }; } RElem swap(int i, RElem&& q) { auto& vec = Super::getContainer(); auto old = vec[i]; vec[i] = q.elem; return RElem{ old }; } template<typename Fun> unit_t iterate(Fun f) const { for (const Elem& e : container) { f(RElem{ e }); } return unit_t(); } template<typename Fun> auto map(Fun f) const -> Vector<R_elem<RT<Fun, RElem>>> const { Vector<R_elem<RT<Fun, RElem>>> result; for (const Elem &e : container) { result.insert(R_elem<RT<Fun, RElem>> { f(RElem{ e }) }); } return result; } template<typename Fun> Vector<RElem> filter(Fun predicate) const { Vector<RElem> result; for (const Elem &e : container) { if (predicate(RElem{ e })) { result.insert(e); } } return result; } template<typename Fun, typename Acc> Acc fold(Fun f, Acc acc) const { for (const Elem &e : container) { acc = f(std::move(acc), RElem{ e }); } return acc; } // TODO: group by and ext transformers. template<class Archive> void serialize(Archive &ar) { ar & yas::base_object<VectorDS<K3::Vector, Elem>>(*this); } template <class Archive> void serialize(Archive& ar, const unsigned int) { ar& boost::serialization::base_object<VectorDS<K3::Vector, Elem>>(*this); } private: friend class boost::serialization::access; }; } // namespace K3 namespace YAML { template <class E> struct convert<K3::Vector<E>> { static Node encode(const K3::Vector<E>& c) { Node node; auto container = c.getConstContainer(); if (container.size() > 0) { for (auto i : container) { node.push_back(convert<E>::encode(i)); } } else { node = YAML::Load("[]"); } return node; } static bool decode(const Node& node, K3::Vector<E>& c) { for (auto& i : node) { c.insert(i.as<E>()); } return true; } }; // Specialization for a vector of bools. template <> struct convert<K3::Vector<R_elem<bool>>> { static Node encode(const K3::Vector<R_elem<bool>>& c) { Node node; auto container = c.getConstContainer(); if (container.size() > 0) { for (auto i : container) { node.push_back(convert<bool>::encode(i)); } } else { node = YAML::Load("[]"); } return node; } static bool decode(const Node& node, K3::Vector<R_elem<bool>>& c) { for (auto& i : node) { c.insert(i.as<bool>()); } return true; } }; } // namespace YAML namespace JSON { using namespace rapidjson; template <class E> struct convert<K3::Vector<E>> { template <class Allocator> static Value encode(const K3::Vector<E>& c, Allocator& al) { Value v; v.SetObject(); v.AddMember("type", Value("Vector"), al); Value inner; inner.SetArray(); for (const auto& e : c.getConstContainer()) { inner.PushBack(convert<E>::encode(e, al), al); } v.AddMember("value", inner.Move(), al); return v; } }; template <> struct convert<K3::Vector<R_elem<bool>>> { template <class Allocator> static Value encode(const K3::Vector<R_elem<bool>>& c, Allocator& al) { Value v; v.SetObject(); v.AddMember("type", Value("Vector"), al); Value inner; inner.SetArray(); for (const auto& e : c.getConstContainer()) { inner.PushBack(convert<bool>::encode(e, al), al); } v.AddMember("value", inner.Move(), al); return v; } }; } // namespace JSON #endif <|endoftext|>
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/globals.h" #if defined(TARGET_OS_MACOS) #include <errno.h> // NOLINT #include <netdb.h> // NOLINT #include <mach/mach.h> // NOLINT #include <mach/clock.h> // NOLINT #include <mach/mach_time.h> // NOLINT #include <sys/time.h> // NOLINT #include <time.h> // NOLINT #include "bin/utils.h" #include "platform/assert.h" #include "platform/utils.h" namespace dart { namespace bin { OSError::OSError() : sub_system_(kSystem), code_(0), message_(NULL) { set_sub_system(kSystem); set_code(errno); const int kBufferSize = 1024; char error_message[kBufferSize]; Utils::StrError(errno, error_message, kBufferSize); SetMessage(error_message); } void OSError::SetCodeAndMessage(SubSystem sub_system, int code) { set_sub_system(sub_system); set_code(code); if (sub_system == kSystem) { const int kBufferSize = 1024; char error_message[kBufferSize]; Utils::StrError(code, error_message, kBufferSize); SetMessage(error_message); } else if (sub_system == kGetAddressInfo) { SetMessage(gai_strerror(code)); } else { UNREACHABLE(); } } const char* StringUtils::ConsoleStringToUtf8( const char* str, intptr_t len, intptr_t* result_len) { UNIMPLEMENTED(); return NULL; } const char* StringUtils::Utf8ToConsoleString( const char* utf8, intptr_t len, intptr_t* result_len) { UNIMPLEMENTED(); return NULL; } char* StringUtils::ConsoleStringToUtf8( char* str, intptr_t len, intptr_t* result_len) { UNIMPLEMENTED(); return NULL; } char* StringUtils::Utf8ToConsoleString( char* utf8, intptr_t len, intptr_t* result_len) { UNIMPLEMENTED(); return NULL; } bool ShellUtils::GetUtf8Argv(int argc, char** argv) { return false; } static mach_timebase_info_data_t timebase_info; void TimerUtils::InitOnce() { kern_return_t kr = mach_timebase_info(&timebase_info); ASSERT(KERN_SUCCESS == kr); } int64_t TimerUtils::GetCurrentMonotonicMillis() { return GetCurrentMonotonicMicros() / 1000; } int64_t TimerUtils::GetCurrentMonotonicMicros() { #if TARGET_OS_IOS // On iOS mach_absolute_time stops while the device is sleeping. Instead use // now - KERN_BOOTTIME to get a time difference that is not impacted by clock // changes. KERN_BOOTTIME will be updated by the system whenever the system // clock change. struct timeval boottime; int mib[2] = {CTL_KERN, KERN_BOOTTIME}; size_t size = sizeof(boottime); int kr = sysctl(mib, sizeof(mib) / sizeof(mib[0]), &boottime, &size, NULL, 0); ASSERT(KERN_SUCCESS == kr); int64_t now = GetCurrentTimeMicros(); int64_t origin = boottime.tv_sec * kMicrosecondsPerSecond; origin += boottime.tv_usec; return now - origin; #else ASSERT(timebase_info.denom != 0); // timebase_info converts absolute time tick units into nanoseconds. Convert // to microseconds. int64_t result = mach_absolute_time() / kNanosecondsPerMicrosecond; result *= timebase_info.numer; result /= timebase_info.denom; return result; #endif // TARGET_OS_IOS } void TimerUtils::Sleep(int64_t millis) { struct timespec req; // requested. struct timespec rem; // remainder. int64_t micros = millis * kMicrosecondsPerMillisecond; int64_t seconds = micros / kMicrosecondsPerSecond; micros = micros - seconds * kMicrosecondsPerSecond; int64_t nanos = micros * kNanosecondsPerMicrosecond; req.tv_sec = seconds; req.tv_nsec = nanos; while (true) { int r = nanosleep(&req, &rem); if (r == 0) { break; } // We should only ever see an interrupt error. ASSERT(errno == EINTR); // Copy remainder into requested and repeat. req = rem; } } } // namespace bin } // namespace dart #endif // defined(TARGET_OS_MACOS) <commit_msg>Fix iOS implementation of |GetCurrentMonotonicMicros|. Fixes regression introduced in dd4ef2909893c055f584e1e8aeecd4c093b077e2<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/globals.h" #if defined(TARGET_OS_MACOS) #include <errno.h> // NOLINT #include <netdb.h> // NOLINT #include <mach/mach.h> // NOLINT #include <mach/clock.h> // NOLINT #include <mach/mach_time.h> // NOLINT #include <sys/time.h> // NOLINT #include <time.h> // NOLINT #if TARGET_OS_IOS #include <sys/sysctl.h> // NOLINT #endif #include "bin/utils.h" #include "platform/assert.h" #include "platform/utils.h" namespace dart { namespace bin { OSError::OSError() : sub_system_(kSystem), code_(0), message_(NULL) { set_sub_system(kSystem); set_code(errno); const int kBufferSize = 1024; char error_message[kBufferSize]; Utils::StrError(errno, error_message, kBufferSize); SetMessage(error_message); } void OSError::SetCodeAndMessage(SubSystem sub_system, int code) { set_sub_system(sub_system); set_code(code); if (sub_system == kSystem) { const int kBufferSize = 1024; char error_message[kBufferSize]; Utils::StrError(code, error_message, kBufferSize); SetMessage(error_message); } else if (sub_system == kGetAddressInfo) { SetMessage(gai_strerror(code)); } else { UNREACHABLE(); } } const char* StringUtils::ConsoleStringToUtf8( const char* str, intptr_t len, intptr_t* result_len) { UNIMPLEMENTED(); return NULL; } const char* StringUtils::Utf8ToConsoleString( const char* utf8, intptr_t len, intptr_t* result_len) { UNIMPLEMENTED(); return NULL; } char* StringUtils::ConsoleStringToUtf8( char* str, intptr_t len, intptr_t* result_len) { UNIMPLEMENTED(); return NULL; } char* StringUtils::Utf8ToConsoleString( char* utf8, intptr_t len, intptr_t* result_len) { UNIMPLEMENTED(); return NULL; } bool ShellUtils::GetUtf8Argv(int argc, char** argv) { return false; } static mach_timebase_info_data_t timebase_info; void TimerUtils::InitOnce() { kern_return_t kr = mach_timebase_info(&timebase_info); ASSERT(KERN_SUCCESS == kr); } int64_t TimerUtils::GetCurrentMonotonicMillis() { return GetCurrentMonotonicMicros() / 1000; } #if TARGET_OS_IOS static int64_t GetCurrentTimeMicros() { // gettimeofday has microsecond resolution. struct timeval tv; if (gettimeofday(&tv, NULL) < 0) { UNREACHABLE(); return 0; } return (static_cast<int64_t>(tv.tv_sec) * 1000000) + tv.tv_usec; } #endif // TARGET_OS_IOS int64_t TimerUtils::GetCurrentMonotonicMicros() { #if TARGET_OS_IOS // On iOS mach_absolute_time stops while the device is sleeping. Instead use // now - KERN_BOOTTIME to get a time difference that is not impacted by clock // changes. KERN_BOOTTIME will be updated by the system whenever the system // clock change. struct timeval boottime; int mib[2] = {CTL_KERN, KERN_BOOTTIME}; size_t size = sizeof(boottime); int kr = sysctl(mib, sizeof(mib) / sizeof(mib[0]), &boottime, &size, NULL, 0); ASSERT(KERN_SUCCESS == kr); int64_t now = GetCurrentTimeMicros(); int64_t origin = boottime.tv_sec * kMicrosecondsPerSecond; origin += boottime.tv_usec; return now - origin; #else ASSERT(timebase_info.denom != 0); // timebase_info converts absolute time tick units into nanoseconds. Convert // to microseconds. int64_t result = mach_absolute_time() / kNanosecondsPerMicrosecond; result *= timebase_info.numer; result /= timebase_info.denom; return result; #endif // TARGET_OS_IOS } void TimerUtils::Sleep(int64_t millis) { struct timespec req; // requested. struct timespec rem; // remainder. int64_t micros = millis * kMicrosecondsPerMillisecond; int64_t seconds = micros / kMicrosecondsPerSecond; micros = micros - seconds * kMicrosecondsPerSecond; int64_t nanos = micros * kNanosecondsPerMicrosecond; req.tv_sec = seconds; req.tv_nsec = nanos; while (true) { int r = nanosleep(&req, &rem); if (r == 0) { break; } // We should only ever see an interrupt error. ASSERT(errno == EINTR); // Copy remainder into requested and repeat. req = rem; } } } // namespace bin } // namespace dart #endif // defined(TARGET_OS_MACOS) <|endoftext|>
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/coding.h" namespace leveldb { void EncodeFixed32(char* buf, uint32_t value) { if (port::kLittleEndian) { memcpy(buf, &value, sizeof(value)); } else { buf[0] = value & 0xff; buf[1] = (value >> 8) & 0xff; buf[2] = (value >> 16) & 0xff; buf[3] = (value >> 24) & 0xff; } } void EncodeFixed64(char* buf, uint64_t value) { if (port::kLittleEndian) { memcpy(buf, &value, sizeof(value)); } else { buf[0] = value & 0xff; buf[1] = (value >> 8) & 0xff; buf[2] = (value >> 16) & 0xff; buf[3] = (value >> 24) & 0xff; buf[4] = (value >> 32) & 0xff; buf[5] = (value >> 40) & 0xff; buf[6] = (value >> 48) & 0xff; buf[7] = (value >> 56) & 0xff; } } void PutFixed32(std::string* dst, uint32_t value) { char buf[sizeof(value)]; EncodeFixed32(buf, value); dst->append(buf, sizeof(buf)); } void PutFixed64(std::string* dst, uint64_t value) { char buf[sizeof(value)]; EncodeFixed64(buf, value); dst->append(buf, sizeof(buf)); } char* EncodeVarint32(char* dst, uint32_t v) { // Operate on characters as unsigneds unsigned char* ptr = reinterpret_cast<unsigned char*>(dst); static const int B = 128; if (v < (1<<7)) { *(ptr++) = v; } else if (v < (1<<14)) { *(ptr++) = v | B; *(ptr++) = v>>7; } else if (v < (1<<21)) { *(ptr++) = v | B; *(ptr++) = (v>>7) | B; *(ptr++) = v>>14; } else if (v < (1<<28)) { *(ptr++) = v | B; *(ptr++) = (v>>7) | B; *(ptr++) = (v>>14) | B; *(ptr++) = v>>21; } else { *(ptr++) = v | B; *(ptr++) = (v>>7) | B; *(ptr++) = (v>>14) | B; *(ptr++) = (v>>21) | B; *(ptr++) = v>>28; } return reinterpret_cast<char*>(ptr); } void PutVarint32(std::string* dst, uint32_t v) { char buf[5]; char* ptr = EncodeVarint32(buf, v); dst->append(buf, ptr - buf); } char* EncodeVarint64(char* dst, uint64_t v) { static const int B = 128; unsigned char* ptr = reinterpret_cast<unsigned char*>(dst); while (v >= B) { *(ptr++) = (v & (B-1)) | B; v >>= 7; } *(ptr++) = static_cast<unsigned char>(v); return reinterpret_cast<char*>(ptr); } void PutVarint64(std::string* dst, uint64_t v) { char buf[10]; char* ptr = EncodeVarint64(buf, v); dst->append(buf, ptr - buf); } void PutLengthPrefixedSlice(std::string* dst, const Slice& value) { PutVarint32(dst, value.size()); dst->append(value.data(), value.size()); } int VarintLength(uint64_t v) { int len = 1; while (v >= 128) { v >>= 7; len++; } return len; } const char* GetVarint32PtrFallback(const char* p, const char* limit, uint32_t* value) { uint32_t result = 0; for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) { uint32_t byte = *(reinterpret_cast<const unsigned char*>(p)); p++; if (byte & 128) { // More bytes are present result |= ((byte & 127) << shift); } else { result |= (byte << shift); *value = result; return reinterpret_cast<const char*>(p); } } return nullptr; } bool GetVarint32(Slice* input, uint32_t* value) { const char* p = input->data(); const char* limit = p + input->size(); const char* q = GetVarint32Ptr(p, limit, value); if (q == nullptr) { return false; } else { *input = Slice(q, limit - q); return true; } } const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* value) { uint64_t result = 0; for (uint32_t shift = 0; shift <= 63 && p < limit; shift += 7) { uint64_t byte = *(reinterpret_cast<const unsigned char*>(p)); p++; if (byte & 128) { // More bytes are present result |= ((byte & 127) << shift); } else { result |= (byte << shift); *value = result; return reinterpret_cast<const char*>(p); } } return nullptr; } bool GetVarint64(Slice* input, uint64_t* value) { const char* p = input->data(); const char* limit = p + input->size(); const char* q = GetVarint64Ptr(p, limit, value); if (q == nullptr) { return false; } else { *input = Slice(q, limit - q); return true; } } const char* GetLengthPrefixedSlice(const char* p, const char* limit, Slice* result) { uint32_t len; p = GetVarint32Ptr(p, limit, &len); if (p == nullptr) return nullptr; if (p + len > limit) return nullptr; *result = Slice(p, len); return p + len; } bool GetLengthPrefixedSlice(Slice* input, Slice* result) { uint32_t len; if (GetVarint32(input, &len) && input->size() >= len) { *result = Slice(input->data(), len); input->remove_prefix(len); return true; } else { return false; } } } // namespace leveldb <commit_msg>Remove unnecessary bit operation.<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/coding.h" namespace leveldb { void EncodeFixed32(char* buf, uint32_t value) { if (port::kLittleEndian) { memcpy(buf, &value, sizeof(value)); } else { buf[0] = value & 0xff; buf[1] = (value >> 8) & 0xff; buf[2] = (value >> 16) & 0xff; buf[3] = (value >> 24) & 0xff; } } void EncodeFixed64(char* buf, uint64_t value) { if (port::kLittleEndian) { memcpy(buf, &value, sizeof(value)); } else { buf[0] = value & 0xff; buf[1] = (value >> 8) & 0xff; buf[2] = (value >> 16) & 0xff; buf[3] = (value >> 24) & 0xff; buf[4] = (value >> 32) & 0xff; buf[5] = (value >> 40) & 0xff; buf[6] = (value >> 48) & 0xff; buf[7] = (value >> 56) & 0xff; } } void PutFixed32(std::string* dst, uint32_t value) { char buf[sizeof(value)]; EncodeFixed32(buf, value); dst->append(buf, sizeof(buf)); } void PutFixed64(std::string* dst, uint64_t value) { char buf[sizeof(value)]; EncodeFixed64(buf, value); dst->append(buf, sizeof(buf)); } char* EncodeVarint32(char* dst, uint32_t v) { // Operate on characters as unsigneds unsigned char* ptr = reinterpret_cast<unsigned char*>(dst); static const int B = 128; if (v < (1<<7)) { *(ptr++) = v; } else if (v < (1<<14)) { *(ptr++) = v | B; *(ptr++) = v>>7; } else if (v < (1<<21)) { *(ptr++) = v | B; *(ptr++) = (v>>7) | B; *(ptr++) = v>>14; } else if (v < (1<<28)) { *(ptr++) = v | B; *(ptr++) = (v>>7) | B; *(ptr++) = (v>>14) | B; *(ptr++) = v>>21; } else { *(ptr++) = v | B; *(ptr++) = (v>>7) | B; *(ptr++) = (v>>14) | B; *(ptr++) = (v>>21) | B; *(ptr++) = v>>28; } return reinterpret_cast<char*>(ptr); } void PutVarint32(std::string* dst, uint32_t v) { char buf[5]; char* ptr = EncodeVarint32(buf, v); dst->append(buf, ptr - buf); } char* EncodeVarint64(char* dst, uint64_t v) { static const int B = 128; unsigned char* ptr = reinterpret_cast<unsigned char*>(dst); while (v >= B) { *(ptr++) = v | B; v >>= 7; } *(ptr++) = static_cast<unsigned char>(v); return reinterpret_cast<char*>(ptr); } void PutVarint64(std::string* dst, uint64_t v) { char buf[10]; char* ptr = EncodeVarint64(buf, v); dst->append(buf, ptr - buf); } void PutLengthPrefixedSlice(std::string* dst, const Slice& value) { PutVarint32(dst, value.size()); dst->append(value.data(), value.size()); } int VarintLength(uint64_t v) { int len = 1; while (v >= 128) { v >>= 7; len++; } return len; } const char* GetVarint32PtrFallback(const char* p, const char* limit, uint32_t* value) { uint32_t result = 0; for (uint32_t shift = 0; shift <= 28 && p < limit; shift += 7) { uint32_t byte = *(reinterpret_cast<const unsigned char*>(p)); p++; if (byte & 128) { // More bytes are present result |= ((byte & 127) << shift); } else { result |= (byte << shift); *value = result; return reinterpret_cast<const char*>(p); } } return nullptr; } bool GetVarint32(Slice* input, uint32_t* value) { const char* p = input->data(); const char* limit = p + input->size(); const char* q = GetVarint32Ptr(p, limit, value); if (q == nullptr) { return false; } else { *input = Slice(q, limit - q); return true; } } const char* GetVarint64Ptr(const char* p, const char* limit, uint64_t* value) { uint64_t result = 0; for (uint32_t shift = 0; shift <= 63 && p < limit; shift += 7) { uint64_t byte = *(reinterpret_cast<const unsigned char*>(p)); p++; if (byte & 128) { // More bytes are present result |= ((byte & 127) << shift); } else { result |= (byte << shift); *value = result; return reinterpret_cast<const char*>(p); } } return nullptr; } bool GetVarint64(Slice* input, uint64_t* value) { const char* p = input->data(); const char* limit = p + input->size(); const char* q = GetVarint64Ptr(p, limit, value); if (q == nullptr) { return false; } else { *input = Slice(q, limit - q); return true; } } const char* GetLengthPrefixedSlice(const char* p, const char* limit, Slice* result) { uint32_t len; p = GetVarint32Ptr(p, limit, &len); if (p == nullptr) return nullptr; if (p + len > limit) return nullptr; *result = Slice(p, len); return p + len; } bool GetLengthPrefixedSlice(Slice* input, Slice* result) { uint32_t len; if (GetVarint32(input, &len) && input->size() >= len) { *result = Slice(input->data(), len); input->remove_prefix(len); return true; } else { return false; } } } // namespace leveldb <|endoftext|>
<commit_before><commit_msg>runtime: update comment to match current code<commit_after><|endoftext|>