text
stringlengths 54
60.6k
|
---|
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGPID.cpp
Author: Jon S. Berndt
Date started: 6/17/2006
------------- Copyright (C) 2006 Jon S. Berndt ([email protected]) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
HISTORY
--------------------------------------------------------------------------------
Initial code 6/17/2006 JSB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGPID.h"
#include "input_output/FGXMLElement.h"
#include <string>
#include <iostream>
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGPID.cpp,v 1.18 2011/04/18 08:51:12 andgi Exp $";
static const char *IdHdr = ID_PID;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGPID::FGPID(FGFCS* fcs, Element* element) : FGFCSComponent(fcs, element)
{
string kp_string, ki_string, kd_string;
Kp = Ki = Kd = 0.0;
KpPropertyNode = 0;
KiPropertyNode = 0;
KdPropertyNode = 0;
KpPropertySign = 1.0;
KiPropertySign = 1.0;
KdPropertySign = 1.0;
I_out_total = 0.0;
Input_prev = Input_prev2 = 0.0;
Trigger = 0;
if ( element->FindElement("kp") ) {
kp_string = element->FindElementValue("kp");
if (!is_number(kp_string)) { // property
if (kp_string[0] == '-') {
KpPropertySign = -1.0;
kp_string.erase(0,1);
}
KpPropertyNode = PropertyManager->GetNode(kp_string);
} else {
Kp = element->FindElementValueAsNumber("kp");
}
}
if ( element->FindElement("ki") ) {
ki_string = element->FindElementValue("ki");
if (!is_number(ki_string)) { // property
if (ki_string[0] == '-') {
KiPropertySign = -1.0;
ki_string.erase(0,1);
}
KiPropertyNode = PropertyManager->GetNode(ki_string);
} else {
Ki = element->FindElementValueAsNumber("ki");
}
}
if ( element->FindElement("kd") ) {
kd_string = element->FindElementValue("kd");
if (!is_number(kd_string)) { // property
if (kd_string[0] == '-') {
KdPropertySign = -1.0;
kd_string.erase(0,1);
}
KdPropertyNode = PropertyManager->GetNode(kd_string);
} else {
Kd = element->FindElementValueAsNumber("kd");
}
}
if (element->FindElement("trigger")) {
Trigger = PropertyManager->GetNode(element->FindElementValue("trigger"));
}
FGFCSComponent::bind();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGPID::~FGPID()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGPID::Run(void )
{
double I_out_delta = 0.0;
double P_out, D_out;
Input = InputNodes[0]->getDoubleValue() * InputSigns[0];
if (KpPropertyNode != 0) Kp = KpPropertyNode->getDoubleValue() * KpPropertySign;
if (KiPropertyNode != 0) Ki = KiPropertyNode->getDoubleValue() * KiPropertySign;
if (KdPropertyNode != 0) Kd = KdPropertyNode->getDoubleValue() * KdPropertySign;
P_out = Kp * Input;
D_out = (Kd / dt) * (Input - Input_prev);
// Do not continue to integrate the input to the integrator if a wind-up
// condition is sensed - that is, if the property pointed to by the trigger
// element is non-zero. Reset the integrator to 0.0 if the Trigger value
// is negative.
if (Trigger != 0) {
double test = Trigger->getDoubleValue();
if (fabs(test) < 0.000001) I_out_delta = Ki * dt * Input; // Normal
if (test < 0.0) I_out_total = 0.0; // Reset integrator to 0.0
} else { // no anti-wind-up trigger defined
I_out_delta = Ki * dt * Input;
}
I_out_total += I_out_delta;
Output = P_out + I_out_total + D_out;
Input_prev = Input;
Input_prev2 = Input_prev;
Clip();
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGPID::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
if (InputSigns[0] < 0)
cout << " INPUT: -" << InputNodes[0]->GetName() << endl;
else
cout << " INPUT: " << InputNodes[0]->GetName() << endl;
if (IsOutput) {
for (unsigned int i=0; i<OutputNodes.size(); i++)
cout << " OUTPUT: " << OutputNodes[i]->getName() << endl;
}
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGPID" << endl;
if (from == 1) cout << "Destroyed: FGPID" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<commit_msg>cvsimport<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGPID.cpp
Author: Jon S. Berndt
Date started: 6/17/2006
------------- Copyright (C) 2006 Jon S. Berndt ([email protected]) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
HISTORY
--------------------------------------------------------------------------------
Initial code 6/17/2006 JSB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGPID.h"
#include "input_output/FGXMLElement.h"
#include <string>
#include <iostream>
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGPID.cpp,v 1.19 2011/05/05 11:44:11 jberndt Exp $";
static const char *IdHdr = ID_PID;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGPID::FGPID(FGFCS* fcs, Element* element) : FGFCSComponent(fcs, element)
{
string kp_string, ki_string, kd_string;
Kp = Ki = Kd = 0.0;
KpPropertyNode = 0;
KiPropertyNode = 0;
KdPropertyNode = 0;
KpPropertySign = 1.0;
KiPropertySign = 1.0;
KdPropertySign = 1.0;
I_out_total = 0.0;
Input_prev = Input_prev2 = 0.0;
Trigger = 0;
if ( element->FindElement("kp") ) {
kp_string = element->FindElementValue("kp");
if (!is_number(kp_string)) { // property
if (kp_string[0] == '-') {
KpPropertySign = -1.0;
kp_string.erase(0,1);
}
KpPropertyNode = PropertyManager->GetNode(kp_string);
} else {
Kp = element->FindElementValueAsNumber("kp");
}
}
if ( element->FindElement("ki") ) {
ki_string = element->FindElementValue("ki");
if (!is_number(ki_string)) { // property
if (ki_string[0] == '-') {
KiPropertySign = -1.0;
ki_string.erase(0,1);
}
KiPropertyNode = PropertyManager->GetNode(ki_string);
} else {
Ki = element->FindElementValueAsNumber("ki");
}
}
if ( element->FindElement("kd") ) {
kd_string = element->FindElementValue("kd");
if (!is_number(kd_string)) { // property
if (kd_string[0] == '-') {
KdPropertySign = -1.0;
kd_string.erase(0,1);
}
KdPropertyNode = PropertyManager->GetNode(kd_string);
} else {
Kd = element->FindElementValueAsNumber("kd");
}
}
if (element->FindElement("trigger")) {
Trigger = PropertyManager->GetNode(element->FindElementValue("trigger"));
}
FGFCSComponent::bind();
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGPID::~FGPID()
{
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGPID::Run(void )
{
double I_out_delta = 0.0;
double P_out, D_out;
Input = InputNodes[0]->getDoubleValue() * InputSigns[0];
if (KpPropertyNode != 0) Kp = KpPropertyNode->getDoubleValue() * KpPropertySign;
if (KiPropertyNode != 0) Ki = KiPropertyNode->getDoubleValue() * KiPropertySign;
if (KdPropertyNode != 0) Kd = KdPropertyNode->getDoubleValue() * KdPropertySign;
P_out = Kp * Input;
D_out = (Kd / dt) * (Input - Input_prev);
// Do not continue to integrate the input to the integrator if a wind-up
// condition is sensed - that is, if the property pointed to by the trigger
// element is non-zero. Reset the integrator to 0.0 if the Trigger value
// is negative.
if (Trigger != 0) {
double test = Trigger->getDoubleValue();
if (fabs(test) < 0.000001) {
// I_out_delta = Ki * dt * Input; // Normal rectangular integrator
I_out_delta = Ki * dt * (1.5*Input - 0.5*Input_prev); // 2nd order Adams Bashforth integrator
}
if (test < 0.0) I_out_total = 0.0; // Reset integrator to 0.0
} else { // no anti-wind-up trigger defined
// I_out_delta = Ki * dt * Input;
I_out_delta = Ki * dt * (1.5*Input - 0.5*Input_prev); // 2nd order Adams Bashforth integrator
}
I_out_total += I_out_delta;
Output = P_out + I_out_total + D_out;
Input_prev = Input;
Input_prev2 = Input_prev;
Clip();
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGPID::Debug(int from)
{
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
if (InputSigns[0] < 0)
cout << " INPUT: -" << InputNodes[0]->GetName() << endl;
else
cout << " INPUT: " << InputNodes[0]->GetName() << endl;
if (IsOutput) {
for (unsigned int i=0; i<OutputNodes.size(); i++)
cout << " OUTPUT: " << OutputNodes[i]->getName() << endl;
}
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGPID" << endl;
if (from == 1) cout << "Destroyed: FGPID" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "qtmaemo6window.h"
#include <QLabel>
#include <QVBoxLayout>
#include <QWidget>
#include <QEvent>
#include <QApplication>
#include <QCloseEvent>
#include <QDialog>
#include <QDebug>
#include <duideviceprofile.h>
#include "qtmaemo6dialogtitle.h"
#include "qtmaemo6style_p.h"
QtMaemo6Window::QtMaemo6Window(QWidget *originalWidget, QWidget *parent /*= NULL*/)
: QWidget(parent)
, m_centralWidget(0)
, m_scrollArea(0)
, m_window(originalWidget)
, m_closeFromChild(false)
{
setWindowFlags(Qt::Window
| Qt::CustomizeWindowHint
| Qt::FramelessWindowHint);
setAttribute(Qt::WA_DeleteOnClose);
//FIXME: this sort of layouting is not nice
// spacers and widgets should be handled within this class
m_windowLayout = new QGridLayout(this);
m_windowLayout->setMargin(0);
m_windowLayout->setSpacing(0);
setCentralWidget(m_window);
}
QtMaemo6Window::~QtMaemo6Window()
{
qCritical() << "QtMaemo6Window deleted";
}
QSize QtMaemo6Window::maxViewportSize() const
{
return m_centralWidget->maximumViewportSize();
}
void QtMaemo6Window::closeEvent(QCloseEvent *event)
{
//prevent deleting the original Widget by Qt
if (m_scrollArea)
m_scrollArea->takeWidget();
//this must be set back to dialog, so that the dialog can be shown again!
m_window->setWindowFlags(m_originalFlags);
m_window->hide();
QWidget::closeEvent(event);
}
bool QtMaemo6Window::eventFilter(QObject *obj, QEvent *event)
{
switch (event->type()) {
case QEvent::Hide: //intended fall trough
case QEvent::Close:
if (!m_closeFromChild) {
m_closeFromChild = true;
// the decoration is closed, even if the widget is only hidden,
// because the decoration is created again, when the widget is
// shown
this->close();
return true;
}
break;
case QEvent::Show: {
if (m_scrollArea && m_scrollArea->widget())
m_scrollArea->widget()->setMinimumWidth(maxViewportSize().width());
}
break;
default:
break;
}
return QWidget::eventFilter(obj, event);
}
void QtMaemo6Window::showFastMaximized()
{
// Size policy instead?
resize(DuiDeviceProfile::instance()->resolution());
show();
}
void QtMaemo6Window::setCentralWidget(QWidget *widget)
{
if (widget) {
m_window = widget;
m_originalFlags = m_window->windowFlags();
m_window->setWindowFlags(Qt::Widget);
m_window->installEventFilter(this);
//remove the current central widget (and scrollArea if set)
// but don't delete the central widget
if (m_scrollArea) {
m_windowLayout->removeWidget(m_scrollArea);
m_scrollArea->takeWidget();
delete m_scrollArea;
m_scrollArea = NULL;
} else {
if (m_centralWidget)
m_windowLayout->removeWidget(m_centralWidget);
}
m_centralWidget = NULL;
if (qobject_cast<QAbstractScrollArea *>(widget))
m_centralWidget = qobject_cast<QAbstractScrollArea *>(widget);
else {
m_centralWidget = m_scrollArea = new QScrollArea();
m_scrollArea->setFrameShape(QFrame::NoFrame);
m_scrollArea->setWidget(widget);
}
//If the widget has size policy expanding, then care for the widget to
//use at least the scroll area viewport's size
if(widget->sizePolicy().horizontalPolicy() == QSizePolicy::Expanding)
widget->setMinimumWidth(maxViewportSize().width());
if(widget->sizePolicy().verticalPolicy() == QSizePolicy::Expanding)
widget->setMinimumHeight(maxViewportSize().height());
m_windowLayout->addWidget(m_centralWidget, 1, 1, 1, 1);
}
}
<commit_msg>Fixes: NB#157925 - QMessageBox has black background<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "qtmaemo6window.h"
#include <QLabel>
#include <QVBoxLayout>
#include <QWidget>
#include <QEvent>
#include <QApplication>
#include <QCloseEvent>
#include <QDialog>
#include <QDebug>
#include <duideviceprofile.h>
#include "qtmaemo6dialogtitle.h"
#include "qtmaemo6style_p.h"
QtMaemo6Window::QtMaemo6Window(QWidget *originalWidget, QWidget *parent /*= NULL*/)
: QWidget(parent)
, m_centralWidget(0)
, m_scrollArea(0)
, m_window(originalWidget)
, m_closeFromChild(false)
{
setWindowFlags(Qt::Window
| Qt::CustomizeWindowHint
| Qt::FramelessWindowHint);
setAttribute(Qt::WA_DeleteOnClose);
//FIXME: this sort of layouting is not nice
// spacers and widgets should be handled within this class
m_windowLayout = new QGridLayout(this);
m_windowLayout->setMargin(0);
m_windowLayout->setSpacing(0);
setCentralWidget(m_window);
}
QtMaemo6Window::~QtMaemo6Window()
{
qCritical() << "QtMaemo6Window deleted";
}
QSize QtMaemo6Window::maxViewportSize() const
{
return m_centralWidget->maximumViewportSize();
}
void QtMaemo6Window::closeEvent(QCloseEvent *event)
{
//prevent deleting the original Widget by Qt
if (m_scrollArea)
m_scrollArea->takeWidget();
//this must be set back to dialog, so that the dialog can be shown again!
m_window->setWindowFlags(m_originalFlags);
m_window->hide();
QWidget::closeEvent(event);
}
bool QtMaemo6Window::eventFilter(QObject *obj, QEvent *event)
{
switch (event->type()) {
case QEvent::Hide: //intended fall trough
case QEvent::Close:
if (!m_closeFromChild) {
m_closeFromChild = true;
// the decoration is closed, even if the widget is only hidden,
// because the decoration is created again, when the widget is
// shown
this->close();
return true;
}
break;
case QEvent::Resize:
if (!qobject_cast<QDialog*>(obj))
break;
// Fall through for all dialog cases.
// Both Resize and Show are needed to cover all cases
case QEvent::Show: {
if (m_scrollArea && m_scrollArea->widget())
m_scrollArea->widget()->setMinimumWidth(maxViewportSize().width());
}
break;
default:
break;
}
return QWidget::eventFilter(obj, event);
}
void QtMaemo6Window::showFastMaximized()
{
// Size policy instead?
resize(DuiDeviceProfile::instance()->resolution());
show();
}
void QtMaemo6Window::setCentralWidget(QWidget *widget)
{
if (widget) {
m_window = widget;
m_originalFlags = m_window->windowFlags();
m_window->setWindowFlags(Qt::Widget);
m_window->installEventFilter(this);
//remove the current central widget (and scrollArea if set)
// but don't delete the central widget
if (m_scrollArea) {
m_windowLayout->removeWidget(m_scrollArea);
m_scrollArea->takeWidget();
delete m_scrollArea;
m_scrollArea = NULL;
} else {
if (m_centralWidget)
m_windowLayout->removeWidget(m_centralWidget);
}
m_centralWidget = NULL;
if (qobject_cast<QAbstractScrollArea *>(widget))
m_centralWidget = qobject_cast<QAbstractScrollArea *>(widget);
else {
m_centralWidget = m_scrollArea = new QScrollArea();
m_scrollArea->setFrameShape(QFrame::NoFrame);
m_scrollArea->setWidget(widget);
}
//If the widget has size policy expanding, then care for the widget to
//use at least the scroll area viewport's size
if(widget->sizePolicy().horizontalPolicy() == QSizePolicy::Expanding)
widget->setMinimumWidth(maxViewportSize().width());
if(widget->sizePolicy().verticalPolicy() == QSizePolicy::Expanding)
widget->setMinimumHeight(maxViewportSize().height());
m_windowLayout->addWidget(m_centralWidget, 1, 1, 1, 1);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 by Tommi Meakitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "cxxtools/xmlrpc/httpclient.h"
#include "cxxtools/net/uri.h"
#include "cxxtools/net/addrinfo.h"
#include "httpclientimpl.h"
#include <stdexcept>
namespace cxxtools
{
namespace xmlrpc
{
HttpClientImpl* HttpClient::getImpl()
{
if (_impl == 0)
{
_impl = new HttpClientImpl();
_impl->addRef();
impl(_impl);
}
return _impl;
}
HttpClient::HttpClient(SelectorBase& selector, const std::string& server,
unsigned short port, const std::string& url)
: _impl(0)
{
prepareConnect(net::AddrInfo(server, port), url);
setSelector(selector);
}
HttpClient::HttpClient(SelectorBase& selector, const net::Uri& uri)
: _impl(0)
{
prepareConnect(net::AddrInfo(uri.host(), uri.port()), uri.path());
setSelector(selector);
auth(uri.user(), uri.password());
}
HttpClient::HttpClient(const std::string& server, unsigned short port, const std::string& url)
: _impl(0)
{
prepareConnect(net::AddrInfo(server, port), url);
}
HttpClient::HttpClient(const net::Uri& uri)
: _impl(0)
{
prepareConnect(net::AddrInfo(uri.host(), uri.port()), uri.path());
auth(uri.user(), uri.password());
}
HttpClient::HttpClient(const HttpClient& other)
: _impl(other._impl)
{
if (_impl)
_impl->addRef();
}
HttpClient& HttpClient::operator= (const HttpClient& other)
{
if (_impl && _impl->release() <= 0)
delete _impl;
_impl = other._impl;
if (_impl)
_impl->addRef();
return *this;
}
HttpClient::~HttpClient()
{
if (_impl && _impl->release() <= 0)
delete _impl;
}
void HttpClient::prepareConnect(const net::AddrInfo& addrinfo, const std::string& url)
{
getImpl()->prepareConnect(addrinfo, url);
}
void HttpClient::prepareConnect(const net::Uri& uri)
{
if (uri.protocol() != "http")
throw std::runtime_error("only http is supported by http client");
prepareConnect(net::AddrInfo(uri.host(), uri.port()), uri.path());
}
void HttpClient::prepareConnect(const std::string& host, unsigned short port,
const std::string& url)
{
prepareConnect(net::AddrInfo(host, port), url);
}
void HttpClient::connect()
{
getImpl()->connect();
}
void HttpClient::url(const std::string& url)
{
getImpl()->url(url);
}
void HttpClient::auth(const std::string& username, const std::string& password)
{
getImpl()->auth(username, password);
}
void HttpClient::clearAuth()
{
getImpl()->clearAuth();
}
void HttpClient::setSelector(SelectorBase& selector)
{
getImpl()->setSelector(selector);
}
void HttpClient::wait(std::size_t msecs)
{
getImpl()->wait(msecs);
}
}
}
<commit_msg>fix copy and assignment of xmlrpc client<commit_after>/*
* Copyright (C) 2009 by Tommi Meakitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "cxxtools/xmlrpc/httpclient.h"
#include "cxxtools/net/uri.h"
#include "cxxtools/net/addrinfo.h"
#include "httpclientimpl.h"
#include <stdexcept>
namespace cxxtools
{
namespace xmlrpc
{
HttpClientImpl* HttpClient::getImpl()
{
if (_impl == 0)
{
_impl = new HttpClientImpl();
_impl->addRef();
impl(_impl);
}
return _impl;
}
HttpClient::HttpClient(SelectorBase& selector, const std::string& server,
unsigned short port, const std::string& url)
: _impl(0)
{
prepareConnect(net::AddrInfo(server, port), url);
setSelector(selector);
}
HttpClient::HttpClient(SelectorBase& selector, const net::Uri& uri)
: _impl(0)
{
prepareConnect(net::AddrInfo(uri.host(), uri.port()), uri.path());
setSelector(selector);
auth(uri.user(), uri.password());
}
HttpClient::HttpClient(const std::string& server, unsigned short port, const std::string& url)
: _impl(0)
{
prepareConnect(net::AddrInfo(server, port), url);
}
HttpClient::HttpClient(const net::Uri& uri)
: _impl(0)
{
prepareConnect(net::AddrInfo(uri.host(), uri.port()), uri.path());
auth(uri.user(), uri.password());
}
HttpClient::HttpClient(const HttpClient& other)
: _impl(other._impl)
{
if (_impl)
{
_impl->addRef();
impl(_impl);
}
}
HttpClient& HttpClient::operator= (const HttpClient& other)
{
if (_impl && _impl->release() <= 0)
delete _impl;
_impl = other._impl;
if (_impl)
_impl->addRef();
impl(_impl);
return *this;
}
HttpClient::~HttpClient()
{
if (_impl && _impl->release() <= 0)
delete _impl;
}
void HttpClient::prepareConnect(const net::AddrInfo& addrinfo, const std::string& url)
{
getImpl()->prepareConnect(addrinfo, url);
}
void HttpClient::prepareConnect(const net::Uri& uri)
{
if (uri.protocol() != "http")
throw std::runtime_error("only http is supported by http client");
prepareConnect(net::AddrInfo(uri.host(), uri.port()), uri.path());
}
void HttpClient::prepareConnect(const std::string& host, unsigned short port,
const std::string& url)
{
prepareConnect(net::AddrInfo(host, port), url);
}
void HttpClient::connect()
{
getImpl()->connect();
}
void HttpClient::url(const std::string& url)
{
getImpl()->url(url);
}
void HttpClient::auth(const std::string& username, const std::string& password)
{
getImpl()->auth(username, password);
}
void HttpClient::clearAuth()
{
getImpl()->clearAuth();
}
void HttpClient::setSelector(SelectorBase& selector)
{
getImpl()->setSelector(selector);
}
void HttpClient::wait(std::size_t msecs)
{
getImpl()->wait(msecs);
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <memory>
#include <utility>
#include "pugixml.hpp"
#include "core/core_mesh.hpp"
#include "correction_data.hpp"
#include "sn_sweeper_cdd.hpp"
namespace mocc { namespace cmdo {
typedef std::pair<std::unique_ptr<SnSweeper>,
std::shared_ptr<CorrectionData>> CDDPair_t;
/**
* Generate an \ref SnSweeper_CDD and associated correction data based on
* the input provided.
*
* This factory is responsible for interpreting the provided input to
* determine and create the appropriate \ref SnSweeper and return it. This
* factory is distinct from the vanilla \ref SnSweeperFactory in that it
* also creates \ref CorrectionData for the sweeper and returns it as well.
* This is important, because the sweeper that is ultimately returned from
* this function is of the base type \ref SnSweeper, which doesn't actually
* know anything about the existence of correction factors.
*
* \note While it would be possible to maintain type information about the
* CDD nature for the returned sweeper, it would be necessary to propagate
* the template parameter as well, which becomes unwieldy when a sweeper
* ends up owning an \ref SnSweeper_CDD as a member. In this case it becomes
* necessary to template that sweeper class as well.
*
* \note This method has one big potential gotcha; the \c std::pair that is
* returned from the factory, and \ref CorrectionData that it contains is
* the \a only reference to the \ref CorrectionData that survives the to
* the end of this function. It is also impossible to get a new one, since
* sufficient type information to do so is discarded when an \ref SnSweeper
* is returned. Moral of the story is to be careful with what you do with
* the return value of this function. Here is a simple example of how to
* screw up:
* \code
* std::unique_ptr<SnSweeper> sweeper = SnSweeperFactory_CDD( input, mesh).first;
* std::shared_ptr<CorrectionData> corrections = SnSweeperFactory_CDD( input, mesh ).second;
* \endcode
*
*/
CDDPair_t SnSweeperFactory_CDD( const pugi::xml_node &input,
const CoreMesh &mesh);
} }
<commit_msg>Fix some documentation issues`<commit_after>#pragma once
#include <memory>
#include <utility>
#include "pugixml.hpp"
#include "core/core_mesh.hpp"
#include "correction_data.hpp"
#include "sn_sweeper_cdd.hpp"
namespace mocc { namespace cmdo {
typedef std::pair<std::unique_ptr<SnSweeper>,
std::shared_ptr<CorrectionData>> CDDPair_t;
/**
* Generate an \ref SnSweeper_CDD and associated correction data based on
* the input provided.
*
* This factory is responsible for interpreting the provided input to
* determine and create the appropriate \ref sn::SnSweeper and return it.
* This factory is distinct from the vanilla \ref SnSweeperFactory in that
* it also creates \ref CorrectionData for the sweeper and returns it as
* well. This is important, because the sweeper that is ultimately returned
* from this function is of the base type \ref sn::SnSweeper, which doesn't
* actually know anything about the existence of correction factors.
*
* \note While it would be possible to maintain type information about the
* CDD nature for the returned sweeper, it would be necessary to propagate
* the template parameter as well, which becomes unwieldy when a sweeper
* ends up owning an \ref SnSweeper_CDD as a member. In this case it becomes
* necessary to template that sweeper class as well.
*
* \note This method has one big potential gotcha; the \c std::pair that is
* returned from the factory, and \ref CorrectionData that it contains is
* the \a only reference to the \ref CorrectionData that survives the to
* the end of this function. It is also impossible to get a new one, since
* sufficient type information to do so is discarded when an \ref
* sn::SnSweeper is returned. Moral of the story is to be careful with what
* you do with the return value of this function. Here is a simple example
* of how to screw up:
* \code
* std::unique_ptr<SnSweeper> sweeper = SnSweeperFactory_CDD( input, mesh).first;
* std::shared_ptr<CorrectionData> corrections = SnSweeperFactory_CDD( input, mesh ).second;
* \endcode
*
*/
CDDPair_t SnSweeperFactory_CDD( const pugi::xml_node &input,
const CoreMesh &mesh);
} }
<|endoftext|> |
<commit_before>#ifndef MOTOR_SPWM
#define MOTOR_SPWM
//motor_softpwm.hpp
//motor softpwm class header file
#include<cstdio>
#include<wiringPi.h>
#include<softPwm.h>
const int RIGHTMOTOR1 17 //GPIO17
const int RIGHTMOTOR2 27 //GPIO27
const int LEFTMOTOR1 23 //GPIO23
const int LEFTMOTOR2 24 //GPIO24
const int RANGE 100
const int STOP 0
const int FWRD 1
const int BACK 2
const int RIGHT 3
const int LEFT 4
class MotorSoftPwm {
int mode, pwmvalue_r, pwmvalue_l, pwmsecond;
public:
MotorSoftPwm(int m,int pr,int pl,int ps); //constructor function
int motorMove();
int setpwm(int m,int pr,int pl,int ps);motor
};
#endif
<commit_msg>add new file<commit_after>#ifndef MOTOR_SPWM
#define MOTOR_SPWM
//motor_softpwm.hpp
//motor softpwm class header file
#include<cstdio>
#include<wiringPi.h>
#include<softPwm.h>
class MotorSoftPwm {
int mode, pwmvalue_r, pwmvalue_l, pwmsecond;
public:
MotorSoftPwm(int m,int pr,int pl,int ps); //constructor function
int motorMove();
int setpwm(int m,int pr,int pl,int ps);motor
};
#endif
<|endoftext|> |
<commit_before>/*
* connection_observer.hpp
*
* Created on: Jun 3, 2016
* Author: zmij
*/
#ifndef TIP_DB_PG_DETAIL_CONNECTION_OBSERVER_HPP_
#define TIP_DB_PG_DETAIL_CONNECTION_OBSERVER_HPP_
#include <afsm/fsm.hpp>
#include <tip/db/pg/log.hpp>
namespace tip {
namespace db {
namespace pg {
namespace detail {
struct connection_observer {
template < typename FSM, typename Event >
void
start_process_event(FSM const& fsm, Event const&) const noexcept
{
using decayed_event = typename ::std::decay<Event>::type;
using tip::util::ANSI_COLOR;
fsm.log() << typeid(Event).name() << ": Start processing";
}
template < typename FSM >
void
start_process_event(FSM const& fsm, ::afsm::none const&) const noexcept
{
fsm.log() << "[default]: Start processing";
}
template < typename FSM >
void
state_changed(FSM const& fsm) const noexcept
{
fsm.log(log::logger::DEBUG) << "State changed to " << fsm.state_name();
}
template < typename FSM, typename Event >
void
processed_in_state(FSM const& fsm, Event const&) const noexcept
{
fsm.log(log::logger::DEBUG) << typeid(Event).name() << ": processed in state "
<< fsm.state_name();
}
template < typename FSM, typename Event >
void
enqueue_event(FSM const& fsm, Event const&) const noexcept
{
fsm.log() << util::ANSI_COLOR::MAGENTA
<< typeid(Event).name() << ": Enqueue";
}
template < typename FSM >
void
start_process_events_queue(FSM const& fsm) const noexcept
{
fsm.log() << util::ANSI_COLOR::MAGENTA
<< "Start processing event queue";
}
template < typename FSM >
void
end_process_events_queue(FSM const& fsm) const noexcept
{
fsm.log() << util::ANSI_COLOR::MAGENTA
<< "End processing event queue";
}
template < typename FSM, typename Event >
void
defer_event(FSM const& fsm, Event const&) const noexcept
{
fsm.log() << (util::ANSI_COLOR::CYAN | util::ANSI_COLOR::BRIGHT)
<< fsm.state_name() << " "
<< typeid(Event).name() << ": Defer";
}
template < typename FSM >
void
start_process_deferred_queue(FSM const& fsm) const noexcept
{
fsm.log() << util::ANSI_COLOR::CYAN
<< "Start processing deferred queue";
}
template < typename FSM >
void
end_process_deferred_queue(FSM const& fsm) const noexcept
{
fsm.log() << util::ANSI_COLOR::CYAN
<< "End processing deferred queue";
}
template < typename FSM, typename Event >
void
reject_event(FSM const& fsm, Event const&) const noexcept
{
fsm.log(log::logger::ERROR) << (util::ANSI_COLOR::RED | util::ANSI_COLOR::BRIGHT)
<< fsm.state_name() << " "
<< typeid(Event).name() << ": Reject.";
}
};
} /* namespace detail */
} /* namespace pg */
} /* namespace db */
} /* namespace tip */
#endif /* TIP_DB_PG_DETAIL_CONNECTION_OBSERVER_HPP_ */
<commit_msg>Less log in pg_async<commit_after>/*
* connection_observer.hpp
*
* Created on: Jun 3, 2016
* Author: zmij
*/
#ifndef TIP_DB_PG_DETAIL_CONNECTION_OBSERVER_HPP_
#define TIP_DB_PG_DETAIL_CONNECTION_OBSERVER_HPP_
#include <afsm/fsm.hpp>
#include <tip/db/pg/log.hpp>
namespace tip {
namespace db {
namespace pg {
namespace detail {
struct connection_observer {
template < typename FSM, typename Event >
void
start_process_event(FSM const& fsm, Event const&) const noexcept
{
using decayed_event = typename ::std::decay<Event>::type;
using tip::util::ANSI_COLOR;
fsm.log() << typeid(Event).name() << ": Start processing";
}
template < typename FSM >
void
start_process_event(FSM const& fsm, ::afsm::none const&) const noexcept
{
fsm.log() << "[default]: Start processing";
}
template < typename FSM >
void
state_changed(FSM const& fsm) const noexcept
{
fsm.log() << "State changed to " << fsm.state_name();
}
template < typename FSM, typename Event >
void
processed_in_state(FSM const& fsm, Event const&) const noexcept
{
fsm.log() << typeid(Event).name() << ": processed in state "
<< fsm.state_name();
}
template < typename FSM, typename Event >
void
enqueue_event(FSM const& fsm, Event const&) const noexcept
{
fsm.log() << util::ANSI_COLOR::MAGENTA
<< typeid(Event).name() << ": Enqueue";
}
template < typename FSM >
void
start_process_events_queue(FSM const& fsm) const noexcept
{
fsm.log() << util::ANSI_COLOR::MAGENTA
<< "Start processing event queue";
}
template < typename FSM >
void
end_process_events_queue(FSM const& fsm) const noexcept
{
fsm.log() << util::ANSI_COLOR::MAGENTA
<< "End processing event queue";
}
template < typename FSM, typename Event >
void
defer_event(FSM const& fsm, Event const&) const noexcept
{
fsm.log() << (util::ANSI_COLOR::CYAN | util::ANSI_COLOR::BRIGHT)
<< fsm.state_name() << " "
<< typeid(Event).name() << ": Defer";
}
template < typename FSM >
void
start_process_deferred_queue(FSM const& fsm) const noexcept
{
fsm.log() << util::ANSI_COLOR::CYAN
<< "Start processing deferred queue";
}
template < typename FSM >
void
end_process_deferred_queue(FSM const& fsm) const noexcept
{
fsm.log() << util::ANSI_COLOR::CYAN
<< "End processing deferred queue";
}
template < typename FSM, typename Event >
void
reject_event(FSM const& fsm, Event const&) const noexcept
{
fsm.log(log::logger::ERROR) << (util::ANSI_COLOR::RED | util::ANSI_COLOR::BRIGHT)
<< fsm.state_name() << " "
<< typeid(Event).name() << ": Reject.";
}
};
} /* namespace detail */
} /* namespace pg */
} /* namespace db */
} /* namespace tip */
#endif /* TIP_DB_PG_DETAIL_CONNECTION_OBSERVER_HPP_ */
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XercesDefs.hpp>
#include <util/PlatformUtils.hpp>
#include <util/XMLMsgLoader.hpp>
#include <util/XMLString.hpp>
#include <util/XMLUni.hpp>
#include <windows.h>
#include "Win32MsgLoader.hpp"
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
Win32MsgLoader::Win32MsgLoader(const XMLCh* const msgDomain) :
fDomainOfs(0)
, fModHandle(0)
, fMsgDomain(0)
{
// Try to get the module handle
fModHandle = ::GetModuleHandleA(Xerces_DLLName);
if (!fModHandle)
{
//
// If we didn't find it, its probably because its a development
// build which is built as separate DLLs, so lets look for the DLL
// that we are part of.
//
static const char* const privDLLName = "IXUTIL";
fModHandle = ::GetModuleHandleA(privDLLName);
// If neither exists, then we give up
if (!fModHandle)
{
// Probably have to call panic here
}
}
// Store the domain name
fMsgDomain = XMLString::replicate(msgDomain);
// And precalc the id offset we use for this domain
if (!XMLString::compareString(fMsgDomain, XMLUni::fgXMLErrDomain))
fDomainOfs = 0;
else if (!XMLString::compareString(fMsgDomain, XMLUni::fgExceptDomain))
fDomainOfs = 0x2000;
else if (!XMLString::compareString(fMsgDomain, XMLUni::fgValidityDomain))
fDomainOfs = 0x4000;
else
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
}
Win32MsgLoader::~Win32MsgLoader()
{
delete [] fMsgDomain;
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
//
// This is the method that actually does the work of loading a message from
// the attached resources. Note that we don't use LoadStringW here, since it
// won't work on Win98. So we go the next level down and do what LoadStringW
// would have done, since this will work on either platform.
//
bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
// In case we error return, and they don't check it...
toFill[0] = 0;
// Adjust the message id by the domain offset
const unsigned int theMsgId = msgToLoad + fDomainOfs;
//
// Figure out the actual id the id, adjusting it by the domain offset.
// Then first we calculate the particular 16 string block that this id
// is in, and the offset within that block of the string in question.
//
const unsigned int theBlock = (theMsgId >> 4) + 1;
const unsigned int theOfs = theMsgId & 0x000F;
// Try to find this resource. If we fail to find it, return false
HRSRC hMsgRsc = ::FindResourceExA
(
fModHandle
, RT_STRING
, MAKEINTRESOURCE(theBlock)
, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)
);
if (!hMsgRsc)
return false;
// We found it, so load the block. If this fails, also return a false
HGLOBAL hGbl = ::LoadResource(fModHandle, hMsgRsc);
if (!hGbl)
return false;
// Lock this resource into memory. Again, if it fails, just return false
const XMLCh* pBlock = (const XMLCh*)::LockResource(hGbl);
if (!pBlock)
return false;
//
// Look through the block for our desired message. Its stored such that
// the zeroth entry has the length minus the separator null.
//
for (unsigned int index = 0; index < theOfs; index++)
pBlock += *pBlock + 1;
// Calculate how many actual chars we will end up with
const unsigned int actualChars = ((maxChars < *pBlock) ? maxChars : *pBlock);
// Ok, finally now copy as much as we can into the caller's buffer
wcsncpy(toFill, pBlock + 1, actualChars);
toFill[actualChars] = 0;
return true;
}
bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1);
if (repText2)
tmp2 = XMLString::transcode(repText2);
if (repText3)
tmp3 = XMLString::transcode(repText3);
if (repText4)
tmp4 = XMLString::transcode(repText4);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
delete [] tmp1;
if (tmp2)
delete [] tmp2;
if (tmp3)
delete [] tmp3;
if (tmp4)
delete [] tmp4;
return bRet;
}
<commit_msg>[Bug 3666] Win32MsgLoader unable to retrieve error text if DLL is renamed. Patch from Jerry Carter.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/XercesDefs.hpp>
#include <util/PlatformUtils.hpp>
#include <util/XMLMsgLoader.hpp>
#include <util/XMLString.hpp>
#include <util/XMLUni.hpp>
#include <windows.h>
#include "Win32MsgLoader.hpp"
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
HINSTANCE globalModuleHandle;
BOOL APIENTRY DllMain(HINSTANCE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved)
{
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
globalModuleHandle = hModule;
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// ---------------------------------------------------------------------------
// Global module handle
// ---------------------------------------------------------------------------
Win32MsgLoader::Win32MsgLoader(const XMLCh* const msgDomain) :
fDomainOfs(0)
, fModHandle(0)
, fMsgDomain(0)
{
// Try to get the module handle
fModHandle = globalModuleHandle;
if (!fModHandle)
{
//
// If we didn't find it, its probably because its a development
// build which is built as separate DLLs, so lets look for the DLL
// that we are part of.
//
static const char* const privDLLName = "IXUTIL";
fModHandle = ::GetModuleHandleA(privDLLName);
// If neither exists, then we give up
if (!fModHandle)
{
// Probably have to call panic here
}
}
// Store the domain name
fMsgDomain = XMLString::replicate(msgDomain);
// And precalc the id offset we use for this domain
if (!XMLString::compareString(fMsgDomain, XMLUni::fgXMLErrDomain))
fDomainOfs = 0;
else if (!XMLString::compareString(fMsgDomain, XMLUni::fgExceptDomain))
fDomainOfs = 0x2000;
else if (!XMLString::compareString(fMsgDomain, XMLUni::fgValidityDomain))
fDomainOfs = 0x4000;
else
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
}
Win32MsgLoader::~Win32MsgLoader()
{
delete [] fMsgDomain;
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
//
// This is the method that actually does the work of loading a message from
// the attached resources. Note that we don't use LoadStringW here, since it
// won't work on Win98. So we go the next level down and do what LoadStringW
// would have done, since this will work on either platform.
//
bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
// In case we error return, and they don't check it...
toFill[0] = 0;
// Adjust the message id by the domain offset
const unsigned int theMsgId = msgToLoad + fDomainOfs;
//
// Figure out the actual id the id, adjusting it by the domain offset.
// Then first we calculate the particular 16 string block that this id
// is in, and the offset within that block of the string in question.
//
const unsigned int theBlock = (theMsgId >> 4) + 1;
const unsigned int theOfs = theMsgId & 0x000F;
// Try to find this resource. If we fail to find it, return false
HRSRC hMsgRsc = ::FindResourceExA
(
fModHandle
, RT_STRING
, MAKEINTRESOURCE(theBlock)
, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)
);
if (!hMsgRsc)
return false;
// We found it, so load the block. If this fails, also return a false
HGLOBAL hGbl = ::LoadResource(fModHandle, hMsgRsc);
if (!hGbl)
return false;
// Lock this resource into memory. Again, if it fails, just return false
const XMLCh* pBlock = (const XMLCh*)::LockResource(hGbl);
if (!pBlock)
return false;
//
// Look through the block for our desired message. Its stored such that
// the zeroth entry has the length minus the separator null.
//
for (unsigned int index = 0; index < theOfs; index++)
pBlock += *pBlock + 1;
// Calculate how many actual chars we will end up with
const unsigned int actualChars = ((maxChars < *pBlock) ? maxChars : *pBlock);
// Ok, finally now copy as much as we can into the caller's buffer
wcsncpy(toFill, pBlock + 1, actualChars);
toFill[actualChars] = 0;
return true;
}
bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool Win32MsgLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1);
if (repText2)
tmp2 = XMLString::transcode(repText2);
if (repText3)
tmp3 = XMLString::transcode(repText3);
if (repText4)
tmp4 = XMLString::transcode(repText4);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
delete [] tmp1;
if (tmp2)
delete [] tmp2;
if (tmp3)
delete [] tmp3;
if (tmp4)
delete [] tmp4;
return bRet;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "context_mips.h"
#include "mirror/abstract_method.h"
#include "mirror/object.h"
#include "stack.h"
namespace art {
namespace mips {
static const uint32_t gZero = 0;
void MipsContext::Reset() {
for (size_t i = 0; i < kNumberOfCoreRegisters; i++) {
gprs_[i] = NULL;
}
for (size_t i = 0; i < kNumberOfFRegisters; i++) {
fprs_[i] = NULL;
}
gprs_[SP] = &sp_;
gprs_[RA] = &ra_;
// Initialize registers with easy to spot debug values.
sp_ = MipsContext::kBadGprBase + SP;
ra_ = MipsContext::kBadGprBase + RA;
}
void MipsContext::FillCalleeSaves(const StackVisitor& fr) {
mirror::AbstractMethod* method = fr.GetMethod();
uint32_t core_spills = method->GetCoreSpillMask();
uint32_t fp_core_spills = method->GetFpSpillMask();
size_t spill_count = __builtin_popcount(core_spills);
size_t fp_spill_count = __builtin_popcount(fp_core_spills);
size_t frame_size = method->GetFrameSizeInBytes();
if (spill_count > 0) {
// Lowest number spill is farthest away, walk registers and fill into context.
int j = 1;
for (size_t i = 0; i < kNumberOfCoreRegisters; i++) {
if (((core_spills >> i) & 1) != 0) {
gprs_[i] = fr.CalleeSaveAddress(spill_count - j, frame_size);
j++;
}
}
}
if (fp_spill_count > 0) {
// Lowest number spill is farthest away, walk registers and fill into context.
int j = 1;
for (size_t i = 0; i < kNumberOfFRegisters; i++) {
if (((fp_core_spills >> i) & 1) != 0) {
fprs_[i] = fr.CalleeSaveAddress(spill_count + fp_spill_count - j, frame_size);
j++;
}
}
}
}
void MipsContext::SetGPR(uint32_t reg, uintptr_t value) {
CHECK_LT(reg, kNumberOfCoreRegisters);
CHECK_NE(gprs_[reg], &gZero); // Can't overwrite this static value since they are never reset.
CHECK(gprs_[reg] != NULL);
*gprs_[reg] = value;
}
void MipsContext::SmashCallerSaves() {
// This needs to be 0 because we want a null/zero return value.
gprs_[V0] = const_cast<uint32_t*>(&gZero);
gprs_[V1] = const_cast<uint32_t*>(&gZero);
gprs_[A1] = NULL;
gprs_[A2] = NULL;
gprs_[A3] = NULL;
}
extern "C" void art_quick_do_long_jump(uint32_t*, uint32_t*);
void MipsContext::DoLongJump() {
uintptr_t gprs[kNumberOfCoreRegisters];
uint32_t fprs[kNumberOfFRegisters];
for (size_t i = 0; i < kNumberOfCoreRegisters; ++i) {
gprs[i] = gprs_[i] != NULL ? *gprs_[i] : MipsContext::kBadGprBase + i;
}
for (size_t i = 0; i < kNumberOfFRegisters; ++i) {
fprs[i] = fprs_[i] != NULL ? *fprs_[i] : MipsContext::kBadGprBase + i;
}
art_quick_do_long_jump(gprs, fprs);
}
} // namespace mips
} // namespace art
<commit_msg>MIPS build fix.<commit_after>/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "context_mips.h"
#include "mirror/abstract_method.h"
#include "mirror/object-inl.h"
#include "stack.h"
namespace art {
namespace mips {
static const uint32_t gZero = 0;
void MipsContext::Reset() {
for (size_t i = 0; i < kNumberOfCoreRegisters; i++) {
gprs_[i] = NULL;
}
for (size_t i = 0; i < kNumberOfFRegisters; i++) {
fprs_[i] = NULL;
}
gprs_[SP] = &sp_;
gprs_[RA] = &ra_;
// Initialize registers with easy to spot debug values.
sp_ = MipsContext::kBadGprBase + SP;
ra_ = MipsContext::kBadGprBase + RA;
}
void MipsContext::FillCalleeSaves(const StackVisitor& fr) {
mirror::AbstractMethod* method = fr.GetMethod();
uint32_t core_spills = method->GetCoreSpillMask();
uint32_t fp_core_spills = method->GetFpSpillMask();
size_t spill_count = __builtin_popcount(core_spills);
size_t fp_spill_count = __builtin_popcount(fp_core_spills);
size_t frame_size = method->GetFrameSizeInBytes();
if (spill_count > 0) {
// Lowest number spill is farthest away, walk registers and fill into context.
int j = 1;
for (size_t i = 0; i < kNumberOfCoreRegisters; i++) {
if (((core_spills >> i) & 1) != 0) {
gprs_[i] = fr.CalleeSaveAddress(spill_count - j, frame_size);
j++;
}
}
}
if (fp_spill_count > 0) {
// Lowest number spill is farthest away, walk registers and fill into context.
int j = 1;
for (size_t i = 0; i < kNumberOfFRegisters; i++) {
if (((fp_core_spills >> i) & 1) != 0) {
fprs_[i] = fr.CalleeSaveAddress(spill_count + fp_spill_count - j, frame_size);
j++;
}
}
}
}
void MipsContext::SetGPR(uint32_t reg, uintptr_t value) {
CHECK_LT(reg, kNumberOfCoreRegisters);
CHECK_NE(gprs_[reg], &gZero); // Can't overwrite this static value since they are never reset.
CHECK(gprs_[reg] != NULL);
*gprs_[reg] = value;
}
void MipsContext::SmashCallerSaves() {
// This needs to be 0 because we want a null/zero return value.
gprs_[V0] = const_cast<uint32_t*>(&gZero);
gprs_[V1] = const_cast<uint32_t*>(&gZero);
gprs_[A1] = NULL;
gprs_[A2] = NULL;
gprs_[A3] = NULL;
}
extern "C" void art_quick_do_long_jump(uint32_t*, uint32_t*);
void MipsContext::DoLongJump() {
uintptr_t gprs[kNumberOfCoreRegisters];
uint32_t fprs[kNumberOfFRegisters];
for (size_t i = 0; i < kNumberOfCoreRegisters; ++i) {
gprs[i] = gprs_[i] != NULL ? *gprs_[i] : MipsContext::kBadGprBase + i;
}
for (size_t i = 0; i < kNumberOfFRegisters; ++i) {
fprs[i] = fprs_[i] != NULL ? *fprs_[i] : MipsContext::kBadGprBase + i;
}
art_quick_do_long_jump(gprs, fprs);
}
} // namespace mips
} // namespace art
<|endoftext|> |
<commit_before>/* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/types.h>
#include <cassert>
#include <android/log.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <oboe/AudioStream.h>
#include <common/AudioClock.h>
#include "common/OboeDebug.h"
#include "oboe/AudioStreamBuilder.h"
#include "AudioStreamOpenSLES.h"
#include "OpenSLESUtilities.h"
using namespace oboe;
AudioStreamOpenSLES::AudioStreamOpenSLES(const AudioStreamBuilder &builder)
: AudioStreamBuffered(builder) {
// OpenSL ES does not support device IDs. So overwrite value from builder.
mDeviceId = kUnspecified;
// OpenSL ES does not support session IDs. So overwrite value from builder.
mSessionId = SessionId::None;
}
static constexpr int32_t kHighLatencyBufferSizeMillis = 20; // typical Android period
static constexpr SLuint32 kAudioChannelCountMax = 30; // TODO Why 30?
static constexpr SLuint32 SL_ANDROID_UNKNOWN_CHANNELMASK = 0; // Matches name used internally.
SLuint32 AudioStreamOpenSLES::channelCountToChannelMaskDefault(int channelCount) const {
if (channelCount > kAudioChannelCountMax) {
return SL_ANDROID_UNKNOWN_CHANNELMASK;
}
SLuint32 bitfield = (1 << channelCount) - 1;
// Check for OS at run-time.
if(getSdkVersion() >= __ANDROID_API_N__) {
return SL_ANDROID_MAKE_INDEXED_CHANNEL_MASK(bitfield);
}
// Indexed channels masks were added in N.
// For before N, the best we can do is use a positional channel mask.
return bitfield;
}
static bool s_isLittleEndian() {
static uint32_t value = 1;
return (*reinterpret_cast<uint8_t *>(&value) == 1); // Does address point to LSB?
}
SLuint32 AudioStreamOpenSLES::getDefaultByteOrder() {
return s_isLittleEndian() ? SL_BYTEORDER_LITTLEENDIAN : SL_BYTEORDER_BIGENDIAN;
}
Result AudioStreamOpenSLES::open() {
LOGI("AudioStreamOpenSLES::open(chans:%d, rate:%d)",
mChannelCount, mSampleRate);
SLresult result = EngineOpenSLES::getInstance().open();
if (SL_RESULT_SUCCESS != result) {
return Result::ErrorInternal;
}
Result oboeResult = AudioStreamBuffered::open();
if (oboeResult != Result::OK) {
return oboeResult;
}
// Convert to defaults if UNSPECIFIED
if (mSampleRate == kUnspecified) {
mSampleRate = DefaultStreamValues::SampleRate;
}
if (mChannelCount == kUnspecified) {
mChannelCount = DefaultStreamValues::ChannelCount;
}
mSharingMode = SharingMode::Shared;
return Result::OK;
}
Result AudioStreamOpenSLES::configureBufferSizes(int32_t sampleRate) {
// Decide frames per burst based on hints from caller.
mFramesPerBurst = mFramesPerCallback;
if (mFramesPerBurst == kUnspecified) {
mFramesPerBurst = DefaultStreamValues::FramesPerBurst;
}
// Calculate the size of a fixed duration buffer based on sample rate.
int32_t framesPerHighLatencyBuffer =
(kHighLatencyBufferSizeMillis * sampleRate) / kMillisPerSecond;
// For high latency streams, use a larger buffer size.
// Performance Mode support was added in N_MR1 (7.1)
if (getSdkVersion() >= __ANDROID_API_N_MR1__
&& mPerformanceMode != PerformanceMode::LowLatency
&& mFramesPerBurst < framesPerHighLatencyBuffer) {
// Find a multiple of framesPerBurst >= kFramesPerHighLatencyBurst.
int32_t numBursts = (framesPerHighLatencyBuffer + mFramesPerBurst - 1) / mFramesPerBurst;
mFramesPerBurst *= numBursts;
LOGD("AudioStreamOpenSLES:%s() NOT low latency, set mFramesPerBurst = %d",
__func__, mFramesPerBurst);
}
mFramesPerCallback = mFramesPerBurst;
mBytesPerCallback = mFramesPerCallback * getBytesPerFrame();
if (mBytesPerCallback <= 0) {
LOGE("AudioStreamOpenSLES::open() bytesPerCallback < 0 = %d, bad format?",
mBytesPerCallback);
return Result::ErrorInvalidFormat; // causing bytesPerFrame == 0
}
mCallbackBuffer = std::make_unique<uint8_t[]>(mBytesPerCallback);
if (!usingFIFO()) {
mBufferCapacityInFrames = mFramesPerBurst * kBufferQueueLength;
mBufferSizeInFrames = mBufferCapacityInFrames;
}
return Result::OK;
}
SLuint32 AudioStreamOpenSLES::convertPerformanceMode(PerformanceMode oboeMode) const {
SLuint32 openslMode = SL_ANDROID_PERFORMANCE_NONE;
switch(oboeMode) {
case PerformanceMode::None:
openslMode = SL_ANDROID_PERFORMANCE_NONE;
break;
case PerformanceMode::LowLatency:
openslMode = (getSessionId() == SessionId::None) ? SL_ANDROID_PERFORMANCE_LATENCY : SL_ANDROID_PERFORMANCE_LATENCY_EFFECTS;
break;
case PerformanceMode::PowerSaving:
openslMode = SL_ANDROID_PERFORMANCE_POWER_SAVING;
break;
default:
break;
}
return openslMode;
}
PerformanceMode AudioStreamOpenSLES::convertPerformanceMode(SLuint32 openslMode) const {
PerformanceMode oboeMode = PerformanceMode::None;
switch(openslMode) {
case SL_ANDROID_PERFORMANCE_NONE:
oboeMode = PerformanceMode::None;
break;
case SL_ANDROID_PERFORMANCE_LATENCY:
case SL_ANDROID_PERFORMANCE_LATENCY_EFFECTS:
oboeMode = PerformanceMode::LowLatency;
break;
case SL_ANDROID_PERFORMANCE_POWER_SAVING:
oboeMode = PerformanceMode::PowerSaving;
break;
default:
break;
}
return oboeMode;
}
void AudioStreamOpenSLES::logUnsupportedAttributes() {
// Log unsupported attributes
// only report if changed from the default
// Device ID
if (mDeviceId != kUnspecified) {
LOGW("Device ID [AudioStreamBuilder::setDeviceId()] "
"is not supported on OpenSLES streams.");
}
// Sharing Mode
if (mSharingMode != SharingMode::Shared) {
LOGW("SharingMode [AudioStreamBuilder::setSharingMode()] "
"is not supported on OpenSLES streams.");
}
// Performance Mode
int sdkVersion = getSdkVersion();
if (mPerformanceMode != PerformanceMode::None && sdkVersion < __ANDROID_API_N_MR1__) {
LOGW("PerformanceMode [AudioStreamBuilder::setPerformanceMode()] "
"is not supported on OpenSLES streams running on pre-Android N-MR1 versions.");
}
// Content Type
if (mContentType != ContentType::Music) {
LOGW("ContentType [AudioStreamBuilder::setContentType()] "
"is not supported on OpenSLES streams.");
}
// Session Id
if (mSessionId != SessionId::None) {
LOGW("SessionId [AudioStreamBuilder::setSessionId()] "
"is not supported on OpenSLES streams.");
}
// Input Preset
if (mInputPreset != InputPreset::VoiceRecognition) {
LOGW("InputPreset [AudioStreamBuilder::setInputPreset()] "
"is not supported on OpenSLES streams.");
}
}
SLresult AudioStreamOpenSLES::configurePerformanceMode(SLAndroidConfigurationItf configItf) {
if (configItf == nullptr) {
LOGW("%s() called with NULL configuration", __func__);
mPerformanceMode = PerformanceMode::None;
return SL_RESULT_INTERNAL_ERROR;
}
if (getSdkVersion() < __ANDROID_API_N_MR1__) {
LOGW("%s() not supported until N_MR1", __func__);
mPerformanceMode = PerformanceMode::None;
return SL_RESULT_SUCCESS;
}
SLresult result = SL_RESULT_SUCCESS;
SLuint32 performanceMode = convertPerformanceMode(getPerformanceMode());
result = (*configItf)->SetConfiguration(configItf, SL_ANDROID_KEY_PERFORMANCE_MODE,
&performanceMode, sizeof(performanceMode));
if (SL_RESULT_SUCCESS != result) {
LOGW("SetConfiguration(PERFORMANCE_MODE, SL %u) returned %s",
performanceMode, getSLErrStr(result));
mPerformanceMode = PerformanceMode::None;
}
return result;
}
SLresult AudioStreamOpenSLES::updateStreamParameters(SLAndroidConfigurationItf configItf) {
SLresult result = SL_RESULT_SUCCESS;
if(getSdkVersion() >= __ANDROID_API_N_MR1__ && configItf != nullptr) {
SLuint32 performanceMode = 0;
SLuint32 performanceModeSize = sizeof(performanceMode);
result = (*configItf)->GetConfiguration(configItf, SL_ANDROID_KEY_PERFORMANCE_MODE,
&performanceModeSize, &performanceMode);
// A bug in GetConfiguration() before P caused a wrong result code to be returned.
if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
result = SL_RESULT_SUCCESS; // Ignore actual result before P.
}
if (SL_RESULT_SUCCESS != result) {
LOGW("GetConfiguration(SL_ANDROID_KEY_PERFORMANCE_MODE) returned %d", result);
mPerformanceMode = PerformanceMode::None; // If we can't query it then assume None.
} else {
mPerformanceMode = convertPerformanceMode(performanceMode); // convert SL to Oboe mode
}
} else {
mPerformanceMode = PerformanceMode::None; // If we can't query it then assume None.
}
return result;
}
Result AudioStreamOpenSLES::close() {
if (mState == StreamState::Closed) {
return Result::ErrorClosed;
}
AudioStreamBuffered::close();
onBeforeDestroy();
if (mObjectInterface != nullptr) {
(*mObjectInterface)->Destroy(mObjectInterface);
mObjectInterface = nullptr;
}
onAfterDestroy();
mSimpleBufferQueueInterface = nullptr;
EngineOpenSLES::getInstance().close();
setState(StreamState::Closed);
return Result::OK;
}
SLresult AudioStreamOpenSLES::enqueueCallbackBuffer(SLAndroidSimpleBufferQueueItf bq) {
return (*bq)->Enqueue(bq, mCallbackBuffer.get(), mBytesPerCallback);
}
int32_t AudioStreamOpenSLES::getBufferDepth(SLAndroidSimpleBufferQueueItf bq) {
SLAndroidSimpleBufferQueueState queueState;
SLresult result = (*bq)->GetState(bq, &queueState);
return (result == SL_RESULT_SUCCESS) ? queueState.count : -1;
}
void AudioStreamOpenSLES::processBufferCallback(SLAndroidSimpleBufferQueueItf bq) {
bool stopStream = false;
// Ask the callback to fill the output buffer with data.
DataCallbackResult result = fireDataCallback(mCallbackBuffer.get(), mFramesPerCallback);
if (result == DataCallbackResult::Continue) {
// Update Oboe service position based on OpenSL ES position.
updateServiceFrameCounter();
// Update Oboe client position with frames handled by the callback.
if (getDirection() == Direction::Input) {
mFramesRead += mFramesPerCallback;
} else {
mFramesWritten += mFramesPerCallback;
}
// Pass the data to OpenSLES.
SLresult enqueueResult = enqueueCallbackBuffer(bq);
if (enqueueResult != SL_RESULT_SUCCESS) {
LOGE("%s() returned %d", __func__, enqueueResult);
stopStream = true;
}
} else if (result == DataCallbackResult::Stop) {
LOGD("Oboe callback returned Stop");
stopStream = true;
} else {
LOGW("Oboe callback returned unexpected value = %d", result);
stopStream = true;
}
if (stopStream) {
requestStop();
}
}
// this callback handler is called every time a buffer needs processing
static void bqCallbackGlue(SLAndroidSimpleBufferQueueItf bq, void *context) {
(reinterpret_cast<AudioStreamOpenSLES *>(context))->processBufferCallback(bq);
}
SLresult AudioStreamOpenSLES::registerBufferQueueCallback() {
// The BufferQueue
SLresult result = (*mObjectInterface)->GetInterface(mObjectInterface, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
&mSimpleBufferQueueInterface);
if (SL_RESULT_SUCCESS != result) {
LOGE("get buffer queue interface:%p result:%s",
mSimpleBufferQueueInterface,
getSLErrStr(result));
} else {
// Register the BufferQueue callback
result = (*mSimpleBufferQueueInterface)->RegisterCallback(mSimpleBufferQueueInterface,
bqCallbackGlue, this);
if (SL_RESULT_SUCCESS != result) {
LOGE("RegisterCallback result:%s", getSLErrStr(result));
}
}
return result;
}
int32_t AudioStreamOpenSLES::getFramesPerBurst() {
return mFramesPerBurst;
}
int64_t AudioStreamOpenSLES::getFramesProcessedByServer() const {
int64_t millis64 = mPositionMillis.get();
int64_t framesProcessed = millis64 * getSampleRate() / kMillisPerSecond;
return framesProcessed;
}
Result AudioStreamOpenSLES::waitForStateChange(StreamState currentState,
StreamState *nextState,
int64_t timeoutNanoseconds) {
Result oboeResult = Result::ErrorTimeout;
int64_t sleepTimeNanos = 20 * kNanosPerMillisecond; // arbitrary
int64_t timeLeftNanos = timeoutNanoseconds;
while (true) {
const StreamState state = getState(); // this does not require a lock
if (nextState != nullptr) {
*nextState = state;
}
if (currentState != state) { // state changed?
oboeResult = Result::OK;
break;
}
// Did we timeout or did user ask for non-blocking?
if (timeoutNanoseconds <= 0) {
break;
}
if (sleepTimeNanos > timeLeftNanos){
sleepTimeNanos = timeLeftNanos;
}
AudioClock::sleepForNanos(sleepTimeNanos);
timeLeftNanos -= sleepTimeNanos;
}
return oboeResult;
}
<commit_msg>opensles: honor setFramesPerCallback()<commit_after>/* Copyright 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/types.h>
#include <cassert>
#include <android/log.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <oboe/AudioStream.h>
#include <common/AudioClock.h>
#include "common/OboeDebug.h"
#include "oboe/AudioStreamBuilder.h"
#include "AudioStreamOpenSLES.h"
#include "OpenSLESUtilities.h"
using namespace oboe;
AudioStreamOpenSLES::AudioStreamOpenSLES(const AudioStreamBuilder &builder)
: AudioStreamBuffered(builder) {
// OpenSL ES does not support device IDs. So overwrite value from builder.
mDeviceId = kUnspecified;
// OpenSL ES does not support session IDs. So overwrite value from builder.
mSessionId = SessionId::None;
}
static constexpr int32_t kHighLatencyBufferSizeMillis = 20; // typical Android period
static constexpr SLuint32 kAudioChannelCountMax = 30; // TODO Why 30?
static constexpr SLuint32 SL_ANDROID_UNKNOWN_CHANNELMASK = 0; // Matches name used internally.
SLuint32 AudioStreamOpenSLES::channelCountToChannelMaskDefault(int channelCount) const {
if (channelCount > kAudioChannelCountMax) {
return SL_ANDROID_UNKNOWN_CHANNELMASK;
}
SLuint32 bitfield = (1 << channelCount) - 1;
// Check for OS at run-time.
if(getSdkVersion() >= __ANDROID_API_N__) {
return SL_ANDROID_MAKE_INDEXED_CHANNEL_MASK(bitfield);
}
// Indexed channels masks were added in N.
// For before N, the best we can do is use a positional channel mask.
return bitfield;
}
static bool s_isLittleEndian() {
static uint32_t value = 1;
return (*reinterpret_cast<uint8_t *>(&value) == 1); // Does address point to LSB?
}
SLuint32 AudioStreamOpenSLES::getDefaultByteOrder() {
return s_isLittleEndian() ? SL_BYTEORDER_LITTLEENDIAN : SL_BYTEORDER_BIGENDIAN;
}
Result AudioStreamOpenSLES::open() {
LOGI("AudioStreamOpenSLES::open(chans:%d, rate:%d)",
mChannelCount, mSampleRate);
SLresult result = EngineOpenSLES::getInstance().open();
if (SL_RESULT_SUCCESS != result) {
return Result::ErrorInternal;
}
Result oboeResult = AudioStreamBuffered::open();
if (oboeResult != Result::OK) {
return oboeResult;
}
// Convert to defaults if UNSPECIFIED
if (mSampleRate == kUnspecified) {
mSampleRate = DefaultStreamValues::SampleRate;
}
if (mChannelCount == kUnspecified) {
mChannelCount = DefaultStreamValues::ChannelCount;
}
mSharingMode = SharingMode::Shared;
return Result::OK;
}
Result AudioStreamOpenSLES::configureBufferSizes(int32_t sampleRate) {
LOGD("AudioStreamOpenSLES:%s(%d) initial mFramesPerBurst = %d, mFramesPerCallback = %d",
__func__, sampleRate, mFramesPerBurst, mFramesPerCallback);
// Decide frames per burst based on hints from caller.
if (mFramesPerCallback != kUnspecified) {
// Requested framesPerCallback must be honored.
mFramesPerBurst = mFramesPerCallback;
} else {
mFramesPerBurst = DefaultStreamValues::FramesPerBurst;
// Calculate the size of a fixed duration high latency buffer based on sample rate.
int32_t framesPerHighLatencyBuffer =
(kHighLatencyBufferSizeMillis * sampleRate) / kMillisPerSecond;
// For high latency streams, use a larger buffer size.
// Performance Mode support was added in N_MR1 (7.1)
if (getSdkVersion() >= __ANDROID_API_N_MR1__
&& mPerformanceMode != PerformanceMode::LowLatency
&& mFramesPerBurst < framesPerHighLatencyBuffer) {
// Find a multiple of framesPerBurst >= framesPerHighLatencyBuffer.
int32_t numBursts = (framesPerHighLatencyBuffer + mFramesPerBurst - 1) / mFramesPerBurst;
mFramesPerBurst *= numBursts;
LOGD("AudioStreamOpenSLES:%s() NOT low latency, set mFramesPerBurst = %d",
__func__, mFramesPerBurst);
}
mFramesPerCallback = mFramesPerBurst;
}
mBytesPerCallback = mFramesPerCallback * getBytesPerFrame();
if (mBytesPerCallback <= 0) {
LOGE("AudioStreamOpenSLES::open() bytesPerCallback < 0 = %d, bad format?",
mBytesPerCallback);
return Result::ErrorInvalidFormat; // causing bytesPerFrame == 0
}
mCallbackBuffer = std::make_unique<uint8_t[]>(mBytesPerCallback);
if (!usingFIFO()) {
mBufferCapacityInFrames = mFramesPerBurst * kBufferQueueLength;
mBufferSizeInFrames = mBufferCapacityInFrames;
}
return Result::OK;
}
SLuint32 AudioStreamOpenSLES::convertPerformanceMode(PerformanceMode oboeMode) const {
SLuint32 openslMode = SL_ANDROID_PERFORMANCE_NONE;
switch(oboeMode) {
case PerformanceMode::None:
openslMode = SL_ANDROID_PERFORMANCE_NONE;
break;
case PerformanceMode::LowLatency:
openslMode = (getSessionId() == SessionId::None) ? SL_ANDROID_PERFORMANCE_LATENCY : SL_ANDROID_PERFORMANCE_LATENCY_EFFECTS;
break;
case PerformanceMode::PowerSaving:
openslMode = SL_ANDROID_PERFORMANCE_POWER_SAVING;
break;
default:
break;
}
return openslMode;
}
PerformanceMode AudioStreamOpenSLES::convertPerformanceMode(SLuint32 openslMode) const {
PerformanceMode oboeMode = PerformanceMode::None;
switch(openslMode) {
case SL_ANDROID_PERFORMANCE_NONE:
oboeMode = PerformanceMode::None;
break;
case SL_ANDROID_PERFORMANCE_LATENCY:
case SL_ANDROID_PERFORMANCE_LATENCY_EFFECTS:
oboeMode = PerformanceMode::LowLatency;
break;
case SL_ANDROID_PERFORMANCE_POWER_SAVING:
oboeMode = PerformanceMode::PowerSaving;
break;
default:
break;
}
return oboeMode;
}
void AudioStreamOpenSLES::logUnsupportedAttributes() {
// Log unsupported attributes
// only report if changed from the default
// Device ID
if (mDeviceId != kUnspecified) {
LOGW("Device ID [AudioStreamBuilder::setDeviceId()] "
"is not supported on OpenSLES streams.");
}
// Sharing Mode
if (mSharingMode != SharingMode::Shared) {
LOGW("SharingMode [AudioStreamBuilder::setSharingMode()] "
"is not supported on OpenSLES streams.");
}
// Performance Mode
int sdkVersion = getSdkVersion();
if (mPerformanceMode != PerformanceMode::None && sdkVersion < __ANDROID_API_N_MR1__) {
LOGW("PerformanceMode [AudioStreamBuilder::setPerformanceMode()] "
"is not supported on OpenSLES streams running on pre-Android N-MR1 versions.");
}
// Content Type
if (mContentType != ContentType::Music) {
LOGW("ContentType [AudioStreamBuilder::setContentType()] "
"is not supported on OpenSLES streams.");
}
// Session Id
if (mSessionId != SessionId::None) {
LOGW("SessionId [AudioStreamBuilder::setSessionId()] "
"is not supported on OpenSLES streams.");
}
// Input Preset
if (mInputPreset != InputPreset::VoiceRecognition) {
LOGW("InputPreset [AudioStreamBuilder::setInputPreset()] "
"is not supported on OpenSLES streams.");
}
}
SLresult AudioStreamOpenSLES::configurePerformanceMode(SLAndroidConfigurationItf configItf) {
if (configItf == nullptr) {
LOGW("%s() called with NULL configuration", __func__);
mPerformanceMode = PerformanceMode::None;
return SL_RESULT_INTERNAL_ERROR;
}
if (getSdkVersion() < __ANDROID_API_N_MR1__) {
LOGW("%s() not supported until N_MR1", __func__);
mPerformanceMode = PerformanceMode::None;
return SL_RESULT_SUCCESS;
}
SLresult result = SL_RESULT_SUCCESS;
SLuint32 performanceMode = convertPerformanceMode(getPerformanceMode());
result = (*configItf)->SetConfiguration(configItf, SL_ANDROID_KEY_PERFORMANCE_MODE,
&performanceMode, sizeof(performanceMode));
if (SL_RESULT_SUCCESS != result) {
LOGW("SetConfiguration(PERFORMANCE_MODE, SL %u) returned %s",
performanceMode, getSLErrStr(result));
mPerformanceMode = PerformanceMode::None;
}
return result;
}
SLresult AudioStreamOpenSLES::updateStreamParameters(SLAndroidConfigurationItf configItf) {
SLresult result = SL_RESULT_SUCCESS;
if(getSdkVersion() >= __ANDROID_API_N_MR1__ && configItf != nullptr) {
SLuint32 performanceMode = 0;
SLuint32 performanceModeSize = sizeof(performanceMode);
result = (*configItf)->GetConfiguration(configItf, SL_ANDROID_KEY_PERFORMANCE_MODE,
&performanceModeSize, &performanceMode);
// A bug in GetConfiguration() before P caused a wrong result code to be returned.
if (getSdkVersion() <= __ANDROID_API_O_MR1__) {
result = SL_RESULT_SUCCESS; // Ignore actual result before P.
}
if (SL_RESULT_SUCCESS != result) {
LOGW("GetConfiguration(SL_ANDROID_KEY_PERFORMANCE_MODE) returned %d", result);
mPerformanceMode = PerformanceMode::None; // If we can't query it then assume None.
} else {
mPerformanceMode = convertPerformanceMode(performanceMode); // convert SL to Oboe mode
}
} else {
mPerformanceMode = PerformanceMode::None; // If we can't query it then assume None.
}
return result;
}
Result AudioStreamOpenSLES::close() {
if (mState == StreamState::Closed) {
return Result::ErrorClosed;
}
AudioStreamBuffered::close();
onBeforeDestroy();
if (mObjectInterface != nullptr) {
(*mObjectInterface)->Destroy(mObjectInterface);
mObjectInterface = nullptr;
}
onAfterDestroy();
mSimpleBufferQueueInterface = nullptr;
EngineOpenSLES::getInstance().close();
setState(StreamState::Closed);
return Result::OK;
}
SLresult AudioStreamOpenSLES::enqueueCallbackBuffer(SLAndroidSimpleBufferQueueItf bq) {
return (*bq)->Enqueue(bq, mCallbackBuffer.get(), mBytesPerCallback);
}
int32_t AudioStreamOpenSLES::getBufferDepth(SLAndroidSimpleBufferQueueItf bq) {
SLAndroidSimpleBufferQueueState queueState;
SLresult result = (*bq)->GetState(bq, &queueState);
return (result == SL_RESULT_SUCCESS) ? queueState.count : -1;
}
void AudioStreamOpenSLES::processBufferCallback(SLAndroidSimpleBufferQueueItf bq) {
bool stopStream = false;
// Ask the callback to fill the output buffer with data.
DataCallbackResult result = fireDataCallback(mCallbackBuffer.get(), mFramesPerCallback);
if (result == DataCallbackResult::Continue) {
// Update Oboe service position based on OpenSL ES position.
updateServiceFrameCounter();
// Update Oboe client position with frames handled by the callback.
if (getDirection() == Direction::Input) {
mFramesRead += mFramesPerCallback;
} else {
mFramesWritten += mFramesPerCallback;
}
// Pass the data to OpenSLES.
SLresult enqueueResult = enqueueCallbackBuffer(bq);
if (enqueueResult != SL_RESULT_SUCCESS) {
LOGE("%s() returned %d", __func__, enqueueResult);
stopStream = true;
}
} else if (result == DataCallbackResult::Stop) {
LOGD("Oboe callback returned Stop");
stopStream = true;
} else {
LOGW("Oboe callback returned unexpected value = %d", result);
stopStream = true;
}
if (stopStream) {
requestStop();
}
}
// this callback handler is called every time a buffer needs processing
static void bqCallbackGlue(SLAndroidSimpleBufferQueueItf bq, void *context) {
(reinterpret_cast<AudioStreamOpenSLES *>(context))->processBufferCallback(bq);
}
SLresult AudioStreamOpenSLES::registerBufferQueueCallback() {
// The BufferQueue
SLresult result = (*mObjectInterface)->GetInterface(mObjectInterface, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
&mSimpleBufferQueueInterface);
if (SL_RESULT_SUCCESS != result) {
LOGE("get buffer queue interface:%p result:%s",
mSimpleBufferQueueInterface,
getSLErrStr(result));
} else {
// Register the BufferQueue callback
result = (*mSimpleBufferQueueInterface)->RegisterCallback(mSimpleBufferQueueInterface,
bqCallbackGlue, this);
if (SL_RESULT_SUCCESS != result) {
LOGE("RegisterCallback result:%s", getSLErrStr(result));
}
}
return result;
}
int32_t AudioStreamOpenSLES::getFramesPerBurst() {
return mFramesPerBurst;
}
int64_t AudioStreamOpenSLES::getFramesProcessedByServer() const {
int64_t millis64 = mPositionMillis.get();
int64_t framesProcessed = millis64 * getSampleRate() / kMillisPerSecond;
return framesProcessed;
}
Result AudioStreamOpenSLES::waitForStateChange(StreamState currentState,
StreamState *nextState,
int64_t timeoutNanoseconds) {
Result oboeResult = Result::ErrorTimeout;
int64_t sleepTimeNanos = 20 * kNanosPerMillisecond; // arbitrary
int64_t timeLeftNanos = timeoutNanoseconds;
while (true) {
const StreamState state = getState(); // this does not require a lock
if (nextState != nullptr) {
*nextState = state;
}
if (currentState != state) { // state changed?
oboeResult = Result::OK;
break;
}
// Did we timeout or did user ask for non-blocking?
if (timeoutNanoseconds <= 0) {
break;
}
if (sleepTimeNanos > timeLeftNanos){
sleepTimeNanos = timeLeftNanos;
}
AudioClock::sleepForNanos(sleepTimeNanos);
timeLeftNanos -= sleepTimeNanos;
}
return oboeResult;
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.4 2003/11/28 20:20:54 neilg
* make use of canonical representation in PSVIAttribute implementation
*
* Revision 1.3 2003/11/27 06:10:32 neilg
* PSVIAttribute implementation
*
* Revision 1.2 2003/11/06 21:50:33 neilg
* fix compilation errors under gcc 3.3.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/PSVIAttribute.hpp>
XERCES_CPP_NAMESPACE_BEGIN
PSVIAttribute::PSVIAttribute( MemoryManager* const manager ):
PSVIItem(manager),
fAttributeDecl(0)
{
}
void PSVIAttribute::reset(
const XMLCh * const valContext
, PSVIItem::VALIDITY_STATE state
, PSVIItem::ASSESSMENT_TYPE assessmentType
, const XMLCh * const normalizedValue
, XSSimpleTypeDefinition * validatingType
, XSSimpleTypeDefinition * memberType
, const XMLCh * const defaultValue
, const bool isSpecified
, XSAttributeDeclaration * attrDecl
, DatatypeValidator *dv
)
{
fValidationContext = valContext;
fValidityState = state;
fAssessmentType = assessmentType;
fNormalizedValue = normalizedValue;
fType = validatingType;
fMemberType = memberType;
fDefaultValue = defaultValue;
fIsSpecified = isSpecified;
fMemoryManager->deallocate((void *)fCanonicalValue);
if(normalizedValue && dv)
fCanonicalValue = dv->getCanonicalRepresentation(normalizedValue, fMemoryManager);
else
fCanonicalValue = 0;
fAttributeDecl = attrDecl;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>fix compilation error<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.5 2003/11/28 22:41:04 neilg
* fix compilation error
*
* Revision 1.4 2003/11/28 20:20:54 neilg
* make use of canonical representation in PSVIAttribute implementation
*
* Revision 1.3 2003/11/27 06:10:32 neilg
* PSVIAttribute implementation
*
* Revision 1.2 2003/11/06 21:50:33 neilg
* fix compilation errors under gcc 3.3.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#include <xercesc/framework/psvi/PSVIAttribute.hpp>
XERCES_CPP_NAMESPACE_BEGIN
PSVIAttribute::PSVIAttribute( MemoryManager* const manager ):
PSVIItem(manager),
fAttributeDecl(0)
{
}
void PSVIAttribute::reset(
const XMLCh * const valContext
, PSVIItem::VALIDITY_STATE state
, PSVIItem::ASSESSMENT_TYPE assessmentType
, const XMLCh * const normalizedValue
, XSSimpleTypeDefinition * validatingType
, XSSimpleTypeDefinition * memberType
, const XMLCh * const defaultValue
, const bool isSpecified
, XSAttributeDeclaration * attrDecl
, DatatypeValidator *dv
)
{
fValidationContext = valContext;
fValidityState = state;
fAssessmentType = assessmentType;
fNormalizedValue = normalizedValue;
fType = validatingType;
fMemberType = memberType;
fDefaultValue = defaultValue;
fIsSpecified = isSpecified;
fMemoryManager->deallocate((void *)fCanonicalValue);
if(normalizedValue && dv)
fCanonicalValue = (XMLCh *)dv->getCanonicalRepresentation(normalizedValue, fMemoryManager);
else
fCanonicalValue = 0;
fAttributeDecl = attrDecl;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>/**
* @file
*
* @brief Tests for leaf plugin
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#include "leaf.hpp"
#include <kdbmodule.h>
#include <kdbprivate.h>
#include <tests.hpp>
using CppKeySet = kdb::KeySet;
using CppKey = kdb::Key;
// -- Macros -------------------------------------------------------------------------------------------------------------------------------
#define OPEN_PLUGIN(parentName, filepath) \
CppKeySet modules{ 0, KS_END }; \
CppKeySet config{ 0, KS_END }; \
elektraModulesInit (modules.getKeySet (), 0); \
CppKey parent{ parentName, KEY_VALUE, filepath, KEY_END }; \
Plugin * plugin = elektraPluginOpen ("leaf", modules.getKeySet (), config.getKeySet (), *parent); \
exit_if_fail (plugin != NULL, "Could not open leaf plugin");
#define CLOSE_PLUGIN() \
ksDel (modules.release ()); \
config.release (); \
elektraPluginClose (plugin, 0); \
elektraModulesClose (modules.getKeySet (), 0)
// -- Tests --------------------------------------------------------------------------------------------------------------------------------
TEST (leaf, basics)
{
OPEN_PLUGIN ("system/elektra/modules/leaf", "")
CppKeySet keys{ 0, KS_END };
succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
"Unable to retrieve plugin contract");
succeed_if_same (plugin->kdbSet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_NO_UPDATE, "Call of `kdbSet` failed");
CLOSE_PLUGIN ();
}
<commit_msg>Leaf: Do not test `set` function in basic test<commit_after>/**
* @file
*
* @brief Tests for leaf plugin
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#include "leaf.hpp"
#include <kdbmodule.h>
#include <kdbprivate.h>
#include <tests.hpp>
using CppKeySet = kdb::KeySet;
using CppKey = kdb::Key;
// -- Macros -------------------------------------------------------------------------------------------------------------------------------
#define OPEN_PLUGIN(parentName, filepath) \
CppKeySet modules{ 0, KS_END }; \
CppKeySet config{ 0, KS_END }; \
elektraModulesInit (modules.getKeySet (), 0); \
CppKey parent{ parentName, KEY_VALUE, filepath, KEY_END }; \
Plugin * plugin = elektraPluginOpen ("leaf", modules.getKeySet (), config.getKeySet (), *parent); \
exit_if_fail (plugin != NULL, "Could not open leaf plugin");
#define CLOSE_PLUGIN() \
ksDel (modules.release ()); \
config.release (); \
elektraPluginClose (plugin, 0); \
elektraModulesClose (modules.getKeySet (), 0)
// -- Tests --------------------------------------------------------------------------------------------------------------------------------
TEST (leaf, basics)
{
OPEN_PLUGIN ("system/elektra/modules/leaf", "")
CppKeySet keys{ 0, KS_END };
succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
"Unable to retrieve plugin contract");
CLOSE_PLUGIN ();
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlocalsocket.h"
#include "qlocalsocket_p.h"
#ifndef QT_NO_LOCALSOCKET
QT_BEGIN_NAMESPACE
/*!
\class QLocalSocket
\since 4.4
\brief The QLocalSocket class provides a local socket.
On Windows this is a named pipe and on Unix this is a local domain socket.
If an error occurs, socketError() returns the type of error, and
errorString() can be called to get a human readable description
of what happened.
Although QLocalSocket is designed for use with an event loop, it's possible
to use it without one. In that case, you must use waitForConnected(),
waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected()
which blocks until the operation is complete or the timeout expires.
Note that this feature is not supported on Window 9x.
\sa QLocalServer
*/
/*!
\fn void QLocalSocket::connectToServer(const QString &name, OpenMode openMode)
Attempts to make a connection to \a name.
The socket is opened in the given \a openMode and first enters ConnectingState.
It then attempts to connect to the address or addresses returned by the lookup.
Finally, if a connection is established, QLocalSocket enters ConnectedState
and emits connected().
At any point, the socket can emit error() to signal that an error occurred.
See also state(), serverName(), and waitForConnected().
*/
/*!
\fn void QLocalSocket::connected()
This signal is emitted after connectToServer() has been called and
a connection has been successfully established.
\sa connectToServer(), disconnected()
*/
/*!
\fn bool QLocalSocket::setSocketDescriptor(quintptr socketDescriptor,
LocalSocketState socketState, OpenMode openMode)
Initializes QLocalSocket with the native socket descriptor
\a socketDescriptor. Returns true if socketDescriptor is accepted
as a valid socket descriptor; otherwise returns false. The socket is
opened in the mode specified by \a openMode, and enters the socket state
specified by \a socketState.
Note: It is not possible to initialize two local sockets with the same
native socket descriptor.
\sa socketDescriptor(), state(), openMode()
*/
/*!
\fn quintptr QLocalSocket::socketDescriptor() const
Returns the native socket descriptor of the QLocalSocket object if
this is available; otherwise returns -1.
The socket descriptor is not available when QLocalSocket
is in UnconnectedState.
\sa setSocketDescriptor()
*/
/*!
\fn qint64 QLocalSocket::readData(char *data, qint64 c)
\reimp
*/
/*!
\fn qint64 QLocalSocket::writeData(const char *data, qint64 c)
\reimp
*/
/*!
\fn void QLocalSocket::abort()
Aborts the current connection and resets the socket.
Unlike disconnectFromServer(), this function immediately closes the socket,
clearing any pending data in the write buffer.
\sa disconnectFromServer(), close()
*/
/*!
\fn qint64 QLocalSocket::bytesAvailable() const
\reimp
*/
/*!
\fn qint64 QLocalSocket::bytesToWrite() const
\reimp
*/
/*!
\fn bool QLocalSocket::canReadLine() const
\reimp
*/
/*!
\fn void QLocalSocket::close()
\reimp
*/
/*!
\fn bool QLocalSocket::waitForBytesWritten(int msecs)
\reimp
*/
/*!
\fn bool QLocalSocket::flush()
This function writes as much as possible from the internal write buffer
to the socket, without blocking. If any data was written, this function
returns true; otherwise false is returned.
Call this function if you need QLocalSocket to start sending buffered data
immediately. The number of bytes successfully written depends on the
operating system. In most cases, you do not need to call this function,
because QLocalSocket will start sending data automatically once control
goes back to the event loop. In the absence of an event loop, call
waitForBytesWritten() instead.
\sa write(), waitForBytesWritten()
*/
/*!
\fn void QLocalSocket::disconnectFromServer()
Attempts to close the socket. If there is pending data waiting to be
written, QLocalSocket will enter ClosingState and wait until all data
has been written. Eventually, it will enter UnconnectedState and emit
the disconnectedFromServer() signal.
\sa connectToServer()
*/
/*!
\fn QLocalSocket::LocalSocketError QLocalSocket::error() const
Returns the type of error that last occurred.
\sa state(), errorString()
*/
/*!
\fn bool QLocalSocket::isValid() const
Returns true if the socket is valid and ready for use; otherwise
returns false.
Note: The socket's state must be ConnectedState before reading
and writing can occur.
\sa state()
*/
/*!
\fn qint64 QLocalSocket::readBufferSize() const
Returns the size of the internal read buffer. This limits the amount of
data that the client can receive before you call read() or readAll().
A read buffer size of 0 (the default) means that the buffer has no size
limit, ensuring that no data is lost.
\sa setReadBufferSize(), read()
*/
/*!
\fn void QLocalSocket::setReadBufferSize(qint64 size)
Sets the size of QLocalSocket's internal read buffer to be \a size bytes.
If the buffer size is limited to a certain size, QLocalSocket won't
buffer more than this size of data. Exceptionally, a buffer size of 0
means that the read buffer is unlimited and all incoming data is buffered.
This is the default.
This option is useful if you only read the data at certain points in
time (e.g., in a real-time streaming application) or if you want to
protect your socket against receiving too much data, which may eventually
cause your application to run out of memory.
\sa readBufferSize(), read()
*/
/*!
\fn bool QLocalSocket::waitForConnected(int msec)
Waits until the socket is connected, up to \a msec milliseconds. If the
connection has been established, this function returns true; otherwise
it returns false. In the case where it returns false, you can call
error() to determine the cause of the error.
The following example waits up to one second for a connection
to be established:
\snippet doc/src/snippets/code/src_network_socket_qlocalsocket_unix.cpp 0
If msecs is -1, this function will not time out.
\sa connectToServer(), connected()
*/
/*!
\fn bool QLocalSocket::waitForDisconnected(int msecs)
Waits until the socket has disconnected, up to \a msecs
milliseconds. If the connection has been disconnected, this
function returns true; otherwise it returns false. In the case
where it returns false, you can call error() to determine
the cause of the error.
The following example waits up to one second for a connection
to be closed:
\snippet doc/src/snippets/code/src_network_socket_qlocalsocket_unix.cpp 1
If msecs is -1, this function will not time out.
\sa disconnectFromServer(), close()
*/
/*!
\fn bool QLocalSocket::waitForReadyRead(int msecs)
This function blocks until data is available for reading and the
\l{QIODevice::}{readyRead()} signal has been emitted. The function
will timeout after \a msecs milliseconds; the default timeout is
30000 milliseconds.
The function returns true if data is available for reading;
otherwise it returns false (if an error occurred or the
operation timed out).
\sa waitForBytesWritten()
*/
/*!
\fn void QLocalSocket::disconnected()
This signal is emitted when the socket has been disconnected.
\sa connectToServer(), disconnectFromServer(), abort(), connected()
*/
/*!
\fn void QLocalSocket::error(QLocalSocket::LocalSocketError socketError)
This signal is emitted after an error occurred. The \a socketError
parameter describes the type of error that occurred.
QLocalSocket::LocalSocketError is not a registered metatype, so for queued
connections, you will have to register it with Q_DECLARE_METATYPE.
\sa error(), errorString()
*/
/*!
\fn void QLocalSocket::stateChanged(QLocalSocket::LocalSocketState socketState)
This signal is emitted whenever QLocalSocket's state changes.
The \a socketState parameter is the new state.
QLocalSocket::SocketState is not a registered metatype, so for queued
connections, you will have to register it with Q_DECLARE_METATYPE.
\sa state()
*/
/*!
Creates a new local socket. The \a parent argument is passed to
QObject's constructor.
*/
QLocalSocket::QLocalSocket(QObject * parent)
: QIODevice(*new QLocalSocketPrivate, parent)
{
Q_D(QLocalSocket);
d->init();
}
/*!
Destroys the socket, closing the connection if necessary.
*/
QLocalSocket::~QLocalSocket()
{
close();
#ifndef Q_OS_WIN
Q_D(QLocalSocket);
d->unixSocket.setParent(0);
#endif
}
/*!
Returns the name of the peer as specified by connectToServer(), or an
empty QString if connectToServer() has not been called or it failed.
\sa connectToServer(), fullServerName()
*/
QString QLocalSocket::serverName() const
{
Q_D(const QLocalSocket);
return d->serverName;
}
/*!
Returns the server path that the socket is connected to.
Note: This is platform specific
\sa connectToServer(), serverName()
*/
QString QLocalSocket::fullServerName() const
{
Q_D(const QLocalSocket);
return d->fullServerName;
}
/*!
Returns the state of the socket.
\sa error()
*/
QLocalSocket::LocalSocketState QLocalSocket::state() const
{
Q_D(const QLocalSocket);
return d->state;
}
/*! \reimp
*/
bool QLocalSocket::isSequential() const
{
return true;
}
/*!
\enum QLocalSocket::LocalSocketError
The LocalServerError enumeration represents the errors that can occur.
The most recent error can be retrieved through a call to
\l QLocalSocket::error().
\value ConnectionRefusedError The connection was refused by
the peer (or timed out).
\value PeerClosedError The remote socket closed the connection.
Note that the client socket (i.e., this socket) will be closed
after the remote close notification has been sent.
\value ServerNotFoundError The local socket name was not found.
\value SocketAccessError The socket operation failed because the
application lacked the required privileges.
\value SocketResourceError The local system ran out of resources
(e.g., too many sockets).
\value SocketTimeoutError The socket operation timed out.
\value DatagramTooLargeError The datagram was larger than the operating
system's limit (which can be as low as 8192 bytes).
\value ConnectionError An error occurred with the connection.
\value UnsupportedSocketOperationError The requested socket operation
is not supported by the local operating system.
\value UnknownSocketError An unidentified error occurred.
*/
/*!
\enum QLocalSocket::LocalSocketState
This enum describes the different states in which a socket can be.
\sa QLocalSocket::state()
\value UnconnectedState The socket is not connected.
\value ConnectingState The socket has started establishing a connection.
\value ConnectedState A connection is established.
\value ClosingState The socket is about to close
(data may still be waiting to be written).
*/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketError error)
{
switch (error) {
case QLocalSocket::ConnectionRefusedError:
debug << "QLocalSocket::ConnectionRefusedError";
break;
case QLocalSocket::PeerClosedError:
debug << "QLocalSocket::PeerClosedError";
break;
case QLocalSocket::ServerNotFoundError:
debug << "QLocalSocket::ServerNotFoundError";
break;
case QLocalSocket::SocketAccessError:
debug << "QLocalSocket::SocketAccessError";
break;
case QLocalSocket::SocketResourceError:
debug << "QLocalSocket::SocketResourceError";
break;
case QLocalSocket::SocketTimeoutError:
debug << "QLocalSocket::SocketTimeoutError";
break;
case QLocalSocket::DatagramTooLargeError:
debug << "QLocalSocket::DatagramTooLargeError";
break;
case QLocalSocket::ConnectionError:
debug << "QLocalSocket::ConnectionError";
break;
case QLocalSocket::UnsupportedSocketOperationError:
debug << "QLocalSocket::UnsupportedSocketOperationError";
break;
case QLocalSocket::UnknownSocketError:
debug << "QLocalSocket::UnknownSocketError";
break;
default:
debug << "QLocalSocket::SocketError(" << int(error) << ')';
break;
}
return debug;
}
QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketState state)
{
switch (state) {
case QLocalSocket::UnconnectedState:
debug << "QLocalSocket::UnconnectedState";
break;
case QLocalSocket::ConnectingState:
debug << "QLocalSocket::ConnectingState";
break;
case QLocalSocket::ConnectedState:
debug << "QLocalSocket::ConnectedState";
break;
case QLocalSocket::ClosingState:
debug << "QLocalSocket::ClosingState";
break;
default:
debug << "QLocalSocket::SocketState(" << int(state) << ')';
break;
}
return debug;
}
#endif
QT_END_NAMESPACE
#endif
#include "moc_qlocalsocket.cpp"
<commit_msg>Doc: Mentioned the use of the meta-type declaration macro and the function for registering types. Additional clean-up.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qlocalsocket.h"
#include "qlocalsocket_p.h"
#ifndef QT_NO_LOCALSOCKET
QT_BEGIN_NAMESPACE
/*!
\class QLocalSocket
\since 4.4
\brief The QLocalSocket class provides a local socket.
On Windows this is a named pipe and on Unix this is a local domain socket.
If an error occurs, socketError() returns the type of error, and
errorString() can be called to get a human readable description
of what happened.
Although QLocalSocket is designed for use with an event loop, it's possible
to use it without one. In that case, you must use waitForConnected(),
waitForReadyRead(), waitForBytesWritten(), and waitForDisconnected()
which blocks until the operation is complete or the timeout expires.
Note that this feature is not supported on versions of Windows earlier than
Windows XP.
\sa QLocalServer
*/
/*!
\fn void QLocalSocket::connectToServer(const QString &name, OpenMode openMode)
Attempts to make a connection to \a name.
The socket is opened in the given \a openMode and first enters ConnectingState.
It then attempts to connect to the address or addresses returned by the lookup.
Finally, if a connection is established, QLocalSocket enters ConnectedState
and emits connected().
At any point, the socket can emit error() to signal that an error occurred.
See also state(), serverName(), and waitForConnected().
*/
/*!
\fn void QLocalSocket::connected()
This signal is emitted after connectToServer() has been called and
a connection has been successfully established.
\sa connectToServer(), disconnected()
*/
/*!
\fn bool QLocalSocket::setSocketDescriptor(quintptr socketDescriptor,
LocalSocketState socketState, OpenMode openMode)
Initializes QLocalSocket with the native socket descriptor
\a socketDescriptor. Returns true if socketDescriptor is accepted
as a valid socket descriptor; otherwise returns false. The socket is
opened in the mode specified by \a openMode, and enters the socket state
specified by \a socketState.
\note It is not possible to initialize two local sockets with the same
native socket descriptor.
\sa socketDescriptor(), state(), openMode()
*/
/*!
\fn quintptr QLocalSocket::socketDescriptor() const
Returns the native socket descriptor of the QLocalSocket object if
this is available; otherwise returns -1.
The socket descriptor is not available when QLocalSocket
is in UnconnectedState.
\sa setSocketDescriptor()
*/
/*!
\fn qint64 QLocalSocket::readData(char *data, qint64 c)
\reimp
*/
/*!
\fn qint64 QLocalSocket::writeData(const char *data, qint64 c)
\reimp
*/
/*!
\fn void QLocalSocket::abort()
Aborts the current connection and resets the socket.
Unlike disconnectFromServer(), this function immediately closes the socket,
clearing any pending data in the write buffer.
\sa disconnectFromServer(), close()
*/
/*!
\fn qint64 QLocalSocket::bytesAvailable() const
\reimp
*/
/*!
\fn qint64 QLocalSocket::bytesToWrite() const
\reimp
*/
/*!
\fn bool QLocalSocket::canReadLine() const
\reimp
*/
/*!
\fn void QLocalSocket::close()
\reimp
*/
/*!
\fn bool QLocalSocket::waitForBytesWritten(int msecs)
\reimp
*/
/*!
\fn bool QLocalSocket::flush()
This function writes as much as possible from the internal write buffer
to the socket, without blocking. If any data was written, this function
returns true; otherwise false is returned.
Call this function if you need QLocalSocket to start sending buffered data
immediately. The number of bytes successfully written depends on the
operating system. In most cases, you do not need to call this function,
because QLocalSocket will start sending data automatically once control
goes back to the event loop. In the absence of an event loop, call
waitForBytesWritten() instead.
\sa write(), waitForBytesWritten()
*/
/*!
\fn void QLocalSocket::disconnectFromServer()
Attempts to close the socket. If there is pending data waiting to be
written, QLocalSocket will enter ClosingState and wait until all data
has been written. Eventually, it will enter UnconnectedState and emit
the disconnectedFromServer() signal.
\sa connectToServer()
*/
/*!
\fn QLocalSocket::LocalSocketError QLocalSocket::error() const
Returns the type of error that last occurred.
\sa state(), errorString()
*/
/*!
\fn bool QLocalSocket::isValid() const
Returns true if the socket is valid and ready for use; otherwise
returns false.
\note The socket's state must be ConnectedState before reading
and writing can occur.
\sa state(), connectToServer()
*/
/*!
\fn qint64 QLocalSocket::readBufferSize() const
Returns the size of the internal read buffer. This limits the amount of
data that the client can receive before you call read() or readAll().
A read buffer size of 0 (the default) means that the buffer has no size
limit, ensuring that no data is lost.
\sa setReadBufferSize(), read()
*/
/*!
\fn void QLocalSocket::setReadBufferSize(qint64 size)
Sets the size of QLocalSocket's internal read buffer to be \a size bytes.
If the buffer size is limited to a certain size, QLocalSocket won't
buffer more than this size of data. Exceptionally, a buffer size of 0
means that the read buffer is unlimited and all incoming data is buffered.
This is the default.
This option is useful if you only read the data at certain points in
time (e.g., in a real-time streaming application) or if you want to
protect your socket against receiving too much data, which may eventually
cause your application to run out of memory.
\sa readBufferSize(), read()
*/
/*!
\fn bool QLocalSocket::waitForConnected(int msecs)
Waits until the socket is connected, up to \a msecs milliseconds. If the
connection has been established, this function returns true; otherwise
it returns false. In the case where it returns false, you can call
error() to determine the cause of the error.
The following example waits up to one second for a connection
to be established:
\snippet doc/src/snippets/code/src_network_socket_qlocalsocket_unix.cpp 0
If \a msecs is -1, this function will not time out.
\sa connectToServer(), connected()
*/
/*!
\fn bool QLocalSocket::waitForDisconnected(int msecs)
Waits until the socket has disconnected, up to \a msecs
milliseconds. If the connection has been disconnected, this
function returns true; otherwise it returns false. In the case
where it returns false, you can call error() to determine
the cause of the error.
The following example waits up to one second for a connection
to be closed:
\snippet doc/src/snippets/code/src_network_socket_qlocalsocket_unix.cpp 1
If \a msecs is -1, this function will not time out.
\sa disconnectFromServer(), close()
*/
/*!
\fn bool QLocalSocket::waitForReadyRead(int msecs)
This function blocks until data is available for reading and the
\l{QIODevice::}{readyRead()} signal has been emitted. The function
will timeout after \a msecs milliseconds; the default timeout is
30000 milliseconds.
The function returns true if data is available for reading;
otherwise it returns false (if an error occurred or the
operation timed out).
\sa waitForBytesWritten()
*/
/*!
\fn void QLocalSocket::disconnected()
This signal is emitted when the socket has been disconnected.
\sa connectToServer(), disconnectFromServer(), abort(), connected()
*/
/*!
\fn void QLocalSocket::error(QLocalSocket::LocalSocketError socketError)
This signal is emitted after an error occurred. The \a socketError
parameter describes the type of error that occurred.
QLocalSocket::LocalSocketError is not a registered metatype, so for queued
connections, you will have to register it with Q_DECLARE_METATYPE() and
qRegisterMetaType().
\sa error(), errorString(), {Creating Custom Qt Types}
*/
/*!
\fn void QLocalSocket::stateChanged(QLocalSocket::LocalSocketState socketState)
This signal is emitted whenever QLocalSocket's state changes.
The \a socketState parameter is the new state.
QLocalSocket::SocketState is not a registered metatype, so for queued
connections, you will have to register it with Q_DECLARE_METATYPE() and
qRegisterMetaType().
\sa state(), {Creating Custom Qt Types}
*/
/*!
Creates a new local socket. The \a parent argument is passed to
QObject's constructor.
*/
QLocalSocket::QLocalSocket(QObject * parent)
: QIODevice(*new QLocalSocketPrivate, parent)
{
Q_D(QLocalSocket);
d->init();
}
/*!
Destroys the socket, closing the connection if necessary.
*/
QLocalSocket::~QLocalSocket()
{
close();
#ifndef Q_OS_WIN
Q_D(QLocalSocket);
d->unixSocket.setParent(0);
#endif
}
/*!
Returns the name of the peer as specified by connectToServer(), or an
empty QString if connectToServer() has not been called or it failed.
\sa connectToServer(), fullServerName()
*/
QString QLocalSocket::serverName() const
{
Q_D(const QLocalSocket);
return d->serverName;
}
/*!
Returns the server path that the socket is connected to.
\note The return value of this function is platform specific.
\sa connectToServer(), serverName()
*/
QString QLocalSocket::fullServerName() const
{
Q_D(const QLocalSocket);
return d->fullServerName;
}
/*!
Returns the state of the socket.
\sa error()
*/
QLocalSocket::LocalSocketState QLocalSocket::state() const
{
Q_D(const QLocalSocket);
return d->state;
}
/*! \reimp
*/
bool QLocalSocket::isSequential() const
{
return true;
}
/*!
\enum QLocalSocket::LocalSocketError
The LocalServerError enumeration represents the errors that can occur.
The most recent error can be retrieved through a call to
\l QLocalSocket::error().
\value ConnectionRefusedError The connection was refused by
the peer (or timed out).
\value PeerClosedError The remote socket closed the connection.
Note that the client socket (i.e., this socket) will be closed
after the remote close notification has been sent.
\value ServerNotFoundError The local socket name was not found.
\value SocketAccessError The socket operation failed because the
application lacked the required privileges.
\value SocketResourceError The local system ran out of resources
(e.g., too many sockets).
\value SocketTimeoutError The socket operation timed out.
\value DatagramTooLargeError The datagram was larger than the operating
system's limit (which can be as low as 8192 bytes).
\value ConnectionError An error occurred with the connection.
\value UnsupportedSocketOperationError The requested socket operation
is not supported by the local operating system.
\value UnknownSocketError An unidentified error occurred.
*/
/*!
\enum QLocalSocket::LocalSocketState
This enum describes the different states in which a socket can be.
\sa QLocalSocket::state()
\value UnconnectedState The socket is not connected.
\value ConnectingState The socket has started establishing a connection.
\value ConnectedState A connection is established.
\value ClosingState The socket is about to close
(data may still be waiting to be written).
*/
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketError error)
{
switch (error) {
case QLocalSocket::ConnectionRefusedError:
debug << "QLocalSocket::ConnectionRefusedError";
break;
case QLocalSocket::PeerClosedError:
debug << "QLocalSocket::PeerClosedError";
break;
case QLocalSocket::ServerNotFoundError:
debug << "QLocalSocket::ServerNotFoundError";
break;
case QLocalSocket::SocketAccessError:
debug << "QLocalSocket::SocketAccessError";
break;
case QLocalSocket::SocketResourceError:
debug << "QLocalSocket::SocketResourceError";
break;
case QLocalSocket::SocketTimeoutError:
debug << "QLocalSocket::SocketTimeoutError";
break;
case QLocalSocket::DatagramTooLargeError:
debug << "QLocalSocket::DatagramTooLargeError";
break;
case QLocalSocket::ConnectionError:
debug << "QLocalSocket::ConnectionError";
break;
case QLocalSocket::UnsupportedSocketOperationError:
debug << "QLocalSocket::UnsupportedSocketOperationError";
break;
case QLocalSocket::UnknownSocketError:
debug << "QLocalSocket::UnknownSocketError";
break;
default:
debug << "QLocalSocket::SocketError(" << int(error) << ')';
break;
}
return debug;
}
QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketState state)
{
switch (state) {
case QLocalSocket::UnconnectedState:
debug << "QLocalSocket::UnconnectedState";
break;
case QLocalSocket::ConnectingState:
debug << "QLocalSocket::ConnectingState";
break;
case QLocalSocket::ConnectedState:
debug << "QLocalSocket::ConnectedState";
break;
case QLocalSocket::ClosingState:
debug << "QLocalSocket::ClosingState";
break;
default:
debug << "QLocalSocket::SocketState(" << int(state) << ')';
break;
}
return debug;
}
#endif
QT_END_NAMESPACE
#endif
#include "moc_qlocalsocket.cpp"
<|endoftext|> |
<commit_before>//===--- UnicodeNormalization.cpp - Unicode Normalization Helpers ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Functions that use ICU to do unicode normalization and collation.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Lazy.h"
#include "swift/Runtime/Config.h"
#include "swift/Runtime/Debug.h"
#include <algorithm>
#include <mutex>
#include <assert.h>
#include <unicode/ustring.h>
#include <unicode/ucol.h>
#include <unicode/ucoleitr.h>
#include <unicode/uiter.h>
#include "../SwiftShims/UnicodeShims.h"
/// Zero weight 0-8, 14-31, 127.
const int8_t _swift_stdlib_unicode_ascii_collation_table_impl[128] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 12, 16, 28, 38, 29,
27, 15, 17, 18, 24, 32, 9, 8, 14, 25, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 11, 10, 33, 34, 35, 13, 23, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70,
72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 19, 26, 20, 31,
7, 30, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81,
83, 85, 87, 89, 91, 93, 95, 97, 99, 21, 36, 22, 37, 0};
const int8_t *_swift_stdlib_unicode_ascii_collation_table =
_swift_stdlib_unicode_ascii_collation_table_impl;
static const UCollator *MakeRootCollator() {
UErrorCode ErrorCode = U_ZERO_ERROR;
UCollator *root = ucol_open("", &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("ucol_open: Failure setting up default collation.");
}
ucol_setAttribute(root, UCOL_NORMALIZATION_MODE, UCOL_ON, &ErrorCode);
ucol_setAttribute(root, UCOL_STRENGTH, UCOL_TERTIARY, &ErrorCode);
ucol_setAttribute(root, UCOL_NUMERIC_COLLATION, UCOL_OFF, &ErrorCode);
ucol_setAttribute(root, UCOL_CASE_LEVEL, UCOL_OFF, &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("ucol_setAttribute: Failure setting up default collation.");
}
return root;
}
// According to this thread in the ICU mailing list, it should be safe
// to assume the UCollator object is thread safe so long as you're only
// passing it to functions that take a const pointer to it. So, we make it
// const here to make sure we don't misuse it.
// http://sourceforge.net/p/icu/mailman/message/27427062/
static const UCollator *GetRootCollator() {
return SWIFT_LAZY_CONSTANT(MakeRootCollator());
}
/// This class caches the collation element results for the ASCII subset of
/// unicode.
class ASCIICollation {
int32_t CollationTable[128];
public:
friend class swift::Lazy<ASCIICollation>;
static swift::Lazy<ASCIICollation> theTable;
static const ASCIICollation *getTable() {
return &theTable.get();
}
/// Maps an ASCII character to a collation element priority as would be
/// returned by a call to ucol_next().
int32_t map(unsigned char c) const {
return CollationTable[c];
}
private:
/// Construct the ASCII collation table.
ASCIICollation() {
const UCollator *Collator = GetRootCollator();
for (unsigned char c = 0; c < 128; ++c) {
UErrorCode ErrorCode = U_ZERO_ERROR;
intptr_t NumCollationElts = 0;
#if defined(__CYGWIN__) || defined(_MSC_VER)
UChar Buffer[1];
#else
uint16_t Buffer[1];
#endif
Buffer[0] = c;
UCollationElements *CollationIterator =
ucol_openElements(Collator, Buffer, 1, &ErrorCode);
while (U_SUCCESS(ErrorCode)) {
intptr_t Elem = ucol_next(CollationIterator, &ErrorCode);
if (Elem != UCOL_NULLORDER) {
CollationTable[c] = Elem;
++NumCollationElts;
} else {
break;
}
}
ucol_closeElements(CollationIterator);
if (U_FAILURE(ErrorCode) || NumCollationElts != 1) {
swift::crash("Error setting up the ASCII collation table");
}
}
}
ASCIICollation &operator=(const ASCIICollation &) = delete;
ASCIICollation(const ASCIICollation &) = delete;
};
/// Compares the strings via the Unicode Collation Algorithm on the root locale.
/// Results are the usual string comparison results:
/// <0 the left string is less than the right string.
/// ==0 the strings are equal according to their collation.
/// >0 the left string is greater than the right string.
int32_t
swift::_swift_stdlib_unicode_compare_utf16_utf16(const uint16_t *LeftString,
int32_t LeftLength,
const uint16_t *RightString,
int32_t RightLength) {
#if defined(__CYGWIN__) || defined(_MSC_VER)
// ICU UChar type is platform dependent. In Cygwin, it is defined
// as wchar_t which size is 2. It seems that the underlying binary
// representation is same with swift utf16 representation.
return ucol_strcoll(GetRootCollator(),
reinterpret_cast<const UChar *>(LeftString), LeftLength,
reinterpret_cast<const UChar *>(RightString), RightLength);
#else
return ucol_strcoll(GetRootCollator(),
LeftString, LeftLength,
RightString, RightLength);
#endif
}
/// Compares the strings via the Unicode Collation Algorithm on the root locale.
/// Results are the usual string comparison results:
/// <0 the left string is less than the right string.
/// ==0 the strings are equal according to their collation.
/// >0 the left string is greater than the right string.
int32_t
swift::_swift_stdlib_unicode_compare_utf8_utf16(const unsigned char *LeftString,
int32_t LeftLength,
const uint16_t *RightString,
int32_t RightLength) {
UCharIterator LeftIterator;
UCharIterator RightIterator;
UErrorCode ErrorCode = U_ZERO_ERROR;
uiter_setUTF8(&LeftIterator, reinterpret_cast<const char *>(LeftString), LeftLength);
#if defined(__CYGWIN__) || defined(_MSC_VER)
uiter_setString(&RightIterator, reinterpret_cast<const UChar *>(RightString),
RightLength);
#else
uiter_setString(&RightIterator, RightString, RightLength);
#endif
uint32_t Diff = ucol_strcollIter(GetRootCollator(),
&LeftIterator, &RightIterator, &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("ucol_strcollIter: Unexpected error doing utf8<->utf16 string comparison.");
}
return Diff;
}
/// Compares the strings via the Unicode Collation Algorithm on the root locale.
/// Results are the usual string comparison results:
/// <0 the left string is less than the right string.
/// ==0 the strings are equal according to their collation.
/// >0 the left string is greater than the right string.
int32_t
swift::_swift_stdlib_unicode_compare_utf8_utf8(const unsigned char *LeftString,
int32_t LeftLength,
const unsigned char *RightString,
int32_t RightLength) {
UCharIterator LeftIterator;
UCharIterator RightIterator;
UErrorCode ErrorCode = U_ZERO_ERROR;
uiter_setUTF8(&LeftIterator, reinterpret_cast<const char *>(LeftString), LeftLength);
uiter_setUTF8(&RightIterator, reinterpret_cast<const char *>(RightString), RightLength);
uint32_t Diff = ucol_strcollIter(GetRootCollator(),
&LeftIterator, &RightIterator, &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("ucol_strcollIter: Unexpected error doing utf8<->utf8 string comparison.");
}
return Diff;
}
// These functions use murmurhash2 in its 32 and 64bit forms, which are
// differentiated by the constants defined below. This seems like a good choice
// for now because it operates efficiently in blocks rather than bytes, and
// the data returned from the collation iterator comes in 4byte chunks.
#if __arm__ || __i386__
#define HASH_SEED 0x88ddcc21
#define HASH_M 0x5bd1e995
#define HASH_R 24
#else
#define HASH_SEED 0x429b126688ddcc21
#define HASH_M 0xc6a4a7935bd1e995
#define HASH_R 47
#endif
static intptr_t hashChunk(const UCollator *Collator, intptr_t HashState,
const uint16_t *Str, uint32_t Length,
UErrorCode *ErrorCode) {
#if defined(__CYGWIN__) || defined(_MSC_VER)
UCollationElements *CollationIterator = ucol_openElements(
Collator, reinterpret_cast<const UChar *>(Str), Length, ErrorCode);
#else
UCollationElements *CollationIterator = ucol_openElements(
Collator, Str, Length, ErrorCode);
#endif
while (U_SUCCESS(*ErrorCode)) {
intptr_t Elem = ucol_next(CollationIterator, ErrorCode);
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if (Elem == 0)
continue;
if (Elem != UCOL_NULLORDER) {
Elem *= HASH_M;
Elem ^= Elem >> HASH_R;
Elem *= HASH_M;
HashState *= HASH_M;
HashState ^= Elem;
} else {
break;
}
}
ucol_closeElements(CollationIterator);
return HashState;
}
static intptr_t hashFinish(intptr_t HashState) {
HashState ^= HashState >> HASH_R;
HashState *= HASH_M;
HashState ^= HashState >> HASH_R;
return HashState;
}
intptr_t
swift::_swift_stdlib_unicode_hash(const uint16_t *Str, int32_t Length) {
UErrorCode ErrorCode = U_ZERO_ERROR;
intptr_t HashState = HASH_SEED;
HashState = hashChunk(GetRootCollator(), HashState, Str, Length, &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("hashChunk: Unexpected error hashing unicode string.");
}
return hashFinish(HashState);
}
intptr_t swift::_swift_stdlib_unicode_hash_ascii(const unsigned char *Str,
int32_t Length) {
const ASCIICollation *Table = ASCIICollation::getTable();
intptr_t HashState = HASH_SEED;
int32_t Pos = 0;
while (Pos < Length) {
const unsigned char c = Str[Pos++];
assert((c & 0x80) == 0 && "This table only exists for the ASCII subset");
intptr_t Elem = Table->map(c);
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if (Elem == 0)
continue;
Elem *= HASH_M;
Elem ^= Elem >> HASH_R;
Elem *= HASH_M;
HashState *= HASH_M;
HashState ^= Elem;
}
return hashFinish(HashState);
}
/// Convert the unicode string to uppercase. This function will return the
/// required buffer length as a result. If this length does not match the
/// 'DestinationCapacity' this function must be called again with a buffer of
/// the required length to get an uppercase version of the string.
int32_t
swift::_swift_stdlib_unicode_strToUpper(uint16_t *Destination,
int32_t DestinationCapacity,
const uint16_t *Source,
int32_t SourceLength) {
UErrorCode ErrorCode = U_ZERO_ERROR;
#if defined(__CYGWIN__) || defined(_MSC_VER)
uint32_t OutputLength = u_strToUpper(reinterpret_cast<UChar *>(Destination),
DestinationCapacity,
reinterpret_cast<const UChar *>(Source),
SourceLength,
"", &ErrorCode);
#else
uint32_t OutputLength = u_strToUpper(Destination, DestinationCapacity,
Source, SourceLength,
"", &ErrorCode);
#endif
if (U_FAILURE(ErrorCode) && ErrorCode != U_BUFFER_OVERFLOW_ERROR) {
swift::crash("u_strToUpper: Unexpected error uppercasing unicode string.");
}
return OutputLength;
}
/// Convert the unicode string to lowercase. This function will return the
/// required buffer length as a result. If this length does not match the
/// 'DestinationCapacity' this function must be called again with a buffer of
/// the required length to get a lowercase version of the string.
int32_t
swift::_swift_stdlib_unicode_strToLower(uint16_t *Destination,
int32_t DestinationCapacity,
const uint16_t *Source,
int32_t SourceLength) {
UErrorCode ErrorCode = U_ZERO_ERROR;
#if defined(__CYGWIN__) || defined(_MSC_VER)
uint32_t OutputLength = u_strToLower(reinterpret_cast<UChar *>(Destination),
DestinationCapacity,
reinterpret_cast<const UChar *>(Source),
SourceLength,
"", &ErrorCode);
#else
uint32_t OutputLength = u_strToLower(Destination, DestinationCapacity,
Source, SourceLength,
"", &ErrorCode);
#endif
if (U_FAILURE(ErrorCode) && ErrorCode != U_BUFFER_OVERFLOW_ERROR) {
swift::crash("u_strToLower: Unexpected error lowercasing unicode string.");
}
return OutputLength;
}
swift::Lazy<ASCIICollation> ASCIICollation::theTable;
<commit_msg>stdlib: remove an unused Unicode data table<commit_after>//===--- UnicodeNormalization.cpp - Unicode Normalization Helpers ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Functions that use ICU to do unicode normalization and collation.
//
//===----------------------------------------------------------------------===//
#include "swift/Basic/Lazy.h"
#include "swift/Runtime/Config.h"
#include "swift/Runtime/Debug.h"
#include <algorithm>
#include <mutex>
#include <assert.h>
#include <unicode/ustring.h>
#include <unicode/ucol.h>
#include <unicode/ucoleitr.h>
#include <unicode/uiter.h>
#include "../SwiftShims/UnicodeShims.h"
static const UCollator *MakeRootCollator() {
UErrorCode ErrorCode = U_ZERO_ERROR;
UCollator *root = ucol_open("", &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("ucol_open: Failure setting up default collation.");
}
ucol_setAttribute(root, UCOL_NORMALIZATION_MODE, UCOL_ON, &ErrorCode);
ucol_setAttribute(root, UCOL_STRENGTH, UCOL_TERTIARY, &ErrorCode);
ucol_setAttribute(root, UCOL_NUMERIC_COLLATION, UCOL_OFF, &ErrorCode);
ucol_setAttribute(root, UCOL_CASE_LEVEL, UCOL_OFF, &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("ucol_setAttribute: Failure setting up default collation.");
}
return root;
}
// According to this thread in the ICU mailing list, it should be safe
// to assume the UCollator object is thread safe so long as you're only
// passing it to functions that take a const pointer to it. So, we make it
// const here to make sure we don't misuse it.
// http://sourceforge.net/p/icu/mailman/message/27427062/
static const UCollator *GetRootCollator() {
return SWIFT_LAZY_CONSTANT(MakeRootCollator());
}
/// This class caches the collation element results for the ASCII subset of
/// unicode.
class ASCIICollation {
int32_t CollationTable[128];
public:
friend class swift::Lazy<ASCIICollation>;
static swift::Lazy<ASCIICollation> theTable;
static const ASCIICollation *getTable() {
return &theTable.get();
}
/// Maps an ASCII character to a collation element priority as would be
/// returned by a call to ucol_next().
int32_t map(unsigned char c) const {
return CollationTable[c];
}
private:
/// Construct the ASCII collation table.
ASCIICollation() {
const UCollator *Collator = GetRootCollator();
for (unsigned char c = 0; c < 128; ++c) {
UErrorCode ErrorCode = U_ZERO_ERROR;
intptr_t NumCollationElts = 0;
#if defined(__CYGWIN__) || defined(_MSC_VER)
UChar Buffer[1];
#else
uint16_t Buffer[1];
#endif
Buffer[0] = c;
UCollationElements *CollationIterator =
ucol_openElements(Collator, Buffer, 1, &ErrorCode);
while (U_SUCCESS(ErrorCode)) {
intptr_t Elem = ucol_next(CollationIterator, &ErrorCode);
if (Elem != UCOL_NULLORDER) {
CollationTable[c] = Elem;
++NumCollationElts;
} else {
break;
}
}
ucol_closeElements(CollationIterator);
if (U_FAILURE(ErrorCode) || NumCollationElts != 1) {
swift::crash("Error setting up the ASCII collation table");
}
}
}
ASCIICollation &operator=(const ASCIICollation &) = delete;
ASCIICollation(const ASCIICollation &) = delete;
};
/// Compares the strings via the Unicode Collation Algorithm on the root locale.
/// Results are the usual string comparison results:
/// <0 the left string is less than the right string.
/// ==0 the strings are equal according to their collation.
/// >0 the left string is greater than the right string.
int32_t
swift::_swift_stdlib_unicode_compare_utf16_utf16(const uint16_t *LeftString,
int32_t LeftLength,
const uint16_t *RightString,
int32_t RightLength) {
#if defined(__CYGWIN__) || defined(_MSC_VER)
// ICU UChar type is platform dependent. In Cygwin, it is defined
// as wchar_t which size is 2. It seems that the underlying binary
// representation is same with swift utf16 representation.
return ucol_strcoll(GetRootCollator(),
reinterpret_cast<const UChar *>(LeftString), LeftLength,
reinterpret_cast<const UChar *>(RightString), RightLength);
#else
return ucol_strcoll(GetRootCollator(),
LeftString, LeftLength,
RightString, RightLength);
#endif
}
/// Compares the strings via the Unicode Collation Algorithm on the root locale.
/// Results are the usual string comparison results:
/// <0 the left string is less than the right string.
/// ==0 the strings are equal according to their collation.
/// >0 the left string is greater than the right string.
int32_t
swift::_swift_stdlib_unicode_compare_utf8_utf16(const unsigned char *LeftString,
int32_t LeftLength,
const uint16_t *RightString,
int32_t RightLength) {
UCharIterator LeftIterator;
UCharIterator RightIterator;
UErrorCode ErrorCode = U_ZERO_ERROR;
uiter_setUTF8(&LeftIterator, reinterpret_cast<const char *>(LeftString), LeftLength);
#if defined(__CYGWIN__) || defined(_MSC_VER)
uiter_setString(&RightIterator, reinterpret_cast<const UChar *>(RightString),
RightLength);
#else
uiter_setString(&RightIterator, RightString, RightLength);
#endif
uint32_t Diff = ucol_strcollIter(GetRootCollator(),
&LeftIterator, &RightIterator, &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("ucol_strcollIter: Unexpected error doing utf8<->utf16 string comparison.");
}
return Diff;
}
/// Compares the strings via the Unicode Collation Algorithm on the root locale.
/// Results are the usual string comparison results:
/// <0 the left string is less than the right string.
/// ==0 the strings are equal according to their collation.
/// >0 the left string is greater than the right string.
int32_t
swift::_swift_stdlib_unicode_compare_utf8_utf8(const unsigned char *LeftString,
int32_t LeftLength,
const unsigned char *RightString,
int32_t RightLength) {
UCharIterator LeftIterator;
UCharIterator RightIterator;
UErrorCode ErrorCode = U_ZERO_ERROR;
uiter_setUTF8(&LeftIterator, reinterpret_cast<const char *>(LeftString), LeftLength);
uiter_setUTF8(&RightIterator, reinterpret_cast<const char *>(RightString), RightLength);
uint32_t Diff = ucol_strcollIter(GetRootCollator(),
&LeftIterator, &RightIterator, &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("ucol_strcollIter: Unexpected error doing utf8<->utf8 string comparison.");
}
return Diff;
}
// These functions use murmurhash2 in its 32 and 64bit forms, which are
// differentiated by the constants defined below. This seems like a good choice
// for now because it operates efficiently in blocks rather than bytes, and
// the data returned from the collation iterator comes in 4byte chunks.
#if __arm__ || __i386__
#define HASH_SEED 0x88ddcc21
#define HASH_M 0x5bd1e995
#define HASH_R 24
#else
#define HASH_SEED 0x429b126688ddcc21
#define HASH_M 0xc6a4a7935bd1e995
#define HASH_R 47
#endif
static intptr_t hashChunk(const UCollator *Collator, intptr_t HashState,
const uint16_t *Str, uint32_t Length,
UErrorCode *ErrorCode) {
#if defined(__CYGWIN__) || defined(_MSC_VER)
UCollationElements *CollationIterator = ucol_openElements(
Collator, reinterpret_cast<const UChar *>(Str), Length, ErrorCode);
#else
UCollationElements *CollationIterator = ucol_openElements(
Collator, Str, Length, ErrorCode);
#endif
while (U_SUCCESS(*ErrorCode)) {
intptr_t Elem = ucol_next(CollationIterator, ErrorCode);
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if (Elem == 0)
continue;
if (Elem != UCOL_NULLORDER) {
Elem *= HASH_M;
Elem ^= Elem >> HASH_R;
Elem *= HASH_M;
HashState *= HASH_M;
HashState ^= Elem;
} else {
break;
}
}
ucol_closeElements(CollationIterator);
return HashState;
}
static intptr_t hashFinish(intptr_t HashState) {
HashState ^= HashState >> HASH_R;
HashState *= HASH_M;
HashState ^= HashState >> HASH_R;
return HashState;
}
intptr_t
swift::_swift_stdlib_unicode_hash(const uint16_t *Str, int32_t Length) {
UErrorCode ErrorCode = U_ZERO_ERROR;
intptr_t HashState = HASH_SEED;
HashState = hashChunk(GetRootCollator(), HashState, Str, Length, &ErrorCode);
if (U_FAILURE(ErrorCode)) {
swift::crash("hashChunk: Unexpected error hashing unicode string.");
}
return hashFinish(HashState);
}
intptr_t swift::_swift_stdlib_unicode_hash_ascii(const unsigned char *Str,
int32_t Length) {
const ASCIICollation *Table = ASCIICollation::getTable();
intptr_t HashState = HASH_SEED;
int32_t Pos = 0;
while (Pos < Length) {
const unsigned char c = Str[Pos++];
assert((c & 0x80) == 0 && "This table only exists for the ASCII subset");
intptr_t Elem = Table->map(c);
// Ignore zero valued collation elements. They don't participate in the
// ordering relation.
if (Elem == 0)
continue;
Elem *= HASH_M;
Elem ^= Elem >> HASH_R;
Elem *= HASH_M;
HashState *= HASH_M;
HashState ^= Elem;
}
return hashFinish(HashState);
}
/// Convert the unicode string to uppercase. This function will return the
/// required buffer length as a result. If this length does not match the
/// 'DestinationCapacity' this function must be called again with a buffer of
/// the required length to get an uppercase version of the string.
int32_t
swift::_swift_stdlib_unicode_strToUpper(uint16_t *Destination,
int32_t DestinationCapacity,
const uint16_t *Source,
int32_t SourceLength) {
UErrorCode ErrorCode = U_ZERO_ERROR;
#if defined(__CYGWIN__) || defined(_MSC_VER)
uint32_t OutputLength = u_strToUpper(reinterpret_cast<UChar *>(Destination),
DestinationCapacity,
reinterpret_cast<const UChar *>(Source),
SourceLength,
"", &ErrorCode);
#else
uint32_t OutputLength = u_strToUpper(Destination, DestinationCapacity,
Source, SourceLength,
"", &ErrorCode);
#endif
if (U_FAILURE(ErrorCode) && ErrorCode != U_BUFFER_OVERFLOW_ERROR) {
swift::crash("u_strToUpper: Unexpected error uppercasing unicode string.");
}
return OutputLength;
}
/// Convert the unicode string to lowercase. This function will return the
/// required buffer length as a result. If this length does not match the
/// 'DestinationCapacity' this function must be called again with a buffer of
/// the required length to get a lowercase version of the string.
int32_t
swift::_swift_stdlib_unicode_strToLower(uint16_t *Destination,
int32_t DestinationCapacity,
const uint16_t *Source,
int32_t SourceLength) {
UErrorCode ErrorCode = U_ZERO_ERROR;
#if defined(__CYGWIN__) || defined(_MSC_VER)
uint32_t OutputLength = u_strToLower(reinterpret_cast<UChar *>(Destination),
DestinationCapacity,
reinterpret_cast<const UChar *>(Source),
SourceLength,
"", &ErrorCode);
#else
uint32_t OutputLength = u_strToLower(Destination, DestinationCapacity,
Source, SourceLength,
"", &ErrorCode);
#endif
if (U_FAILURE(ErrorCode) && ErrorCode != U_BUFFER_OVERFLOW_ERROR) {
swift::crash("u_strToLower: Unexpected error lowercasing unicode string.");
}
return OutputLength;
}
swift::Lazy<ASCIICollation> ASCIICollation::theTable;
<|endoftext|> |
<commit_before>#ifndef ITER_GROUPER_HPP_
#define ITER_GROUPER_HPP_
#include "iterbase.hpp"
#include "iteratoriterator.hpp"
#include <vector>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container>
class Grouper;
template <typename Container>
Grouper<Container> grouper(Container&&, std::size_t);
template <typename T>
Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T>, std::size_t);
template <typename Container>
class Grouper {
private:
Container container;
std::size_t group_size;
Grouper(Container&& c, std::size_t sz)
: container(std::forward<Container>(c)),
group_size{sz}
{ }
friend Grouper grouper<Container>(Container&&, std::size_t);
template <typename T>
friend Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T>, std::size_t);
using IndexVector = std::vector<iterator_type<Container>>;
using DerefVec = IterIterWrapper<IndexVector>;
public:
class Iterator :
public std::iterator<std::input_iterator_tag, DerefVec>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
DerefVec group;
std::size_t group_size = 0;
bool done() const {
return this->group.empty();
}
void refill_group() {
this->group.get().clear();
std::size_t i{0};
while (i < group_size
&& this->sub_iter != this->sub_end) {
group.get().push_back(this->sub_iter);
++this->sub_iter;
++i;
}
}
public:
Iterator(iterator_type<Container>&& in_iter,
iterator_type<Container>&& in_end,
std::size_t s)
: sub_iter{std::move(in_iter)},
sub_end{std::move(in_end)},
group_size{s}
{
this->group.get().reserve(this->group_size);
this->refill_group();
}
Iterator& operator++() {
this->refill_group();
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->done() == other.done()
&& (this->done()
|| !(this->sub_iter != other.sub_iter));
}
DerefVec& operator*() {
return this->group;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
group_size};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
group_size};
}
};
template <typename Container>
Grouper<Container> grouper(Container&& container, std::size_t group_size) {
return {std::forward<Container>(container), group_size};
}
template <typename T>
Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T> il, std::size_t group_size) {
return {std::move(il), group_size};
}
}
#endif
<commit_msg>adds -> to grouper iter<commit_after>#ifndef ITER_GROUPER_HPP_
#define ITER_GROUPER_HPP_
#include "iterbase.hpp"
#include "iteratoriterator.hpp"
#include <vector>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container>
class Grouper;
template <typename Container>
Grouper<Container> grouper(Container&&, std::size_t);
template <typename T>
Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T>, std::size_t);
template <typename Container>
class Grouper {
private:
Container container;
std::size_t group_size;
Grouper(Container&& c, std::size_t sz)
: container(std::forward<Container>(c)),
group_size{sz}
{ }
friend Grouper grouper<Container>(Container&&, std::size_t);
template <typename T>
friend Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T>, std::size_t);
using IndexVector = std::vector<iterator_type<Container>>;
using DerefVec = IterIterWrapper<IndexVector>;
public:
class Iterator :
public std::iterator<std::input_iterator_tag, DerefVec>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
DerefVec group;
std::size_t group_size = 0;
bool done() const {
return this->group.empty();
}
void refill_group() {
this->group.get().clear();
std::size_t i{0};
while (i < group_size
&& this->sub_iter != this->sub_end) {
group.get().push_back(this->sub_iter);
++this->sub_iter;
++i;
}
}
public:
Iterator(iterator_type<Container>&& in_iter,
iterator_type<Container>&& in_end,
std::size_t s)
: sub_iter{std::move(in_iter)},
sub_end{std::move(in_end)},
group_size{s}
{
this->group.get().reserve(this->group_size);
this->refill_group();
}
Iterator& operator++() {
this->refill_group();
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->done() == other.done()
&& (this->done()
|| !(this->sub_iter != other.sub_iter));
}
DerefVec& operator*() {
return this->group;
}
DerefVec *operator->() {
return &this->group;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
group_size};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
group_size};
}
};
template <typename Container>
Grouper<Container> grouper(Container&& container, std::size_t group_size) {
return {std::forward<Container>(container), group_size};
}
template <typename T>
Grouper<std::initializer_list<T>> grouper(
std::initializer_list<T> il, std::size_t group_size) {
return {std::move(il), group_size};
}
}
#endif
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage 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.
*********************************************************************/
/* Author: Arjun Menon */
#include <ros/ros.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/warehouse/planning_scene_storage.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <view_controller_msgs/CameraPlacement.h>
#include "moveit_recorder/trajectory_retimer.h"
#include "moveit_recorder/animation_recorder.h"
#include <rosbag/bag.h>
#include <rosbag/query.h>
#include <rosbag/view.h>
#include <algorithm>
bool static ready;
void animationResponseCallback(const boost::shared_ptr<std_msgs::Bool const>& msg)
{
ready = msg->data;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "playback");
ros::NodeHandle node_handle;
ros::AsyncSpinner spinner(1);
spinner.start();
sleep(20); // to let RVIZ come up
boost::program_options::options_description desc;
desc.add_options()
("help", "Show help message")
("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.")
("views",boost::program_options::value<std::string>(), "Bag file for viewpoints")
("save_dir",boost::program_options::value<std::string>(), "Directory for saving videos");
boost::program_options::variables_map vm;
boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);
boost::program_options::store(po, vm);
boost::program_options::notify(vm);
if (vm.count("help") || argc == 1) // show help if no parameters passed
{
std::cout << desc << std::endl;
return 1;
}
try
{
//connect to the DB
std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
moveit_warehouse::PlanningSceneStorage pss(host, port);
ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port);
// set up the storage directory
boost::filesystem::path storage_dir( vm.count("save_dir") ? vm["save_dir"].as<std::string>() : "/tmp" );
boost::filesystem::create_directories( storage_dir );
// create bag file to track the associated video to the scene, query, and traj that spawned it
boost::filesystem::path bagpath = storage_dir / "video_lookup.bag";
rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Write);
bag.close();
// load the viewpoints
std::string bagfilename = vm.count("views") ? vm["views"].as<std::string>() : "";
std::vector<view_controller_msgs::CameraPlacement> views;
rosbag::Bag viewbag;
viewbag.open(bagfilename, rosbag::bagmode::Read);
std::vector<std::string> topics; topics.push_back("viewpoints");
rosbag::View view_t(viewbag, rosbag::TopicQuery(topics));
BOOST_FOREACH(rosbag::MessageInstance const m, view_t)
{
view_controller_msgs::CameraPlacement::ConstPtr i = m.instantiate<view_controller_msgs::CameraPlacement>();
if (i != NULL)
views.push_back(*i);
}
viewbag.close();
ROS_INFO("%d views loaded",(int)views.size());
AnimationRecorder recorder( "/rviz/camera_placement",
"planning_scene",
"/move_group/display_planned_path",
"animation_status",
"animation_response",
node_handle);
// ask the warehouse for the scenes
std::vector<std::string> ps_names;
pss.getPlanningSceneNames( ps_names );
ROS_INFO("%d available scenes to display", (int)ps_names.size());
// iterate over scenes
std::vector<std::string>::iterator scene_name = ps_names.begin();
for(; scene_name!=ps_names.end(); ++scene_name)
{
ROS_INFO("Retrieving scene %s", scene_name->c_str());
moveit_warehouse::PlanningSceneWithMetadata pswm;
pss.getPlanningScene(pswm, *scene_name);
moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm);
// ask qarehosue for the queries
std::vector<std::string> pq_names;
pss.getPlanningQueriesNames( pq_names, *scene_name);
ROS_INFO("%d available queries to display", (int)pq_names.size());
// iterate over the queries
std::vector<std::string>::iterator query_name = pq_names.begin();
for(; query_name!=pq_names.end(); ++query_name)
{
ROS_INFO("Retrieving query %s", query_name->c_str());
moveit_warehouse::MotionPlanRequestWithMetadata mprwm;
pss.getPlanningQuery(mprwm, *scene_name, *query_name);
moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm);
// ask warehouse for stored trajectories
std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results;
pss.getPlanningResults(planning_results, *scene_name, *query_name);
ROS_INFO("Loaded %d trajectories", (int)planning_results.size());
// animate each trajectory
std::vector<moveit_warehouse::RobotTrajectoryWithMetadata>::iterator traj_w_mdata = planning_results.begin();
for(; traj_w_mdata!=planning_results.end(); ++traj_w_mdata)
{
moveit_msgs::RobotTrajectory rt_msg;
rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(**traj_w_mdata);
// retime it
TrajectoryRetimer retimer( "robot_description", mpr_msg.group_name );
retimer.configure(ps_msg, mpr_msg);
bool result = retimer.retime(rt_msg);
ROS_INFO("Retiming success? %s", result? "yes" : "no" );
//date and time based filename
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
std::string vid_filename = boost::posix_time::to_simple_string(now);
// fix filename
std::replace(vid_filename.begin(), vid_filename.end(), '-','_');
std::replace(vid_filename.begin(), vid_filename.end(), ' ','_');
std::replace(vid_filename.begin(), vid_filename.end(), ':','_');
boost::filesystem::path filename( vid_filename );
boost::filesystem::path filepath = storage_dir / filename;
// save into lookup
rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Append);
bag.write(filepath.string(), ros::Time::now(), ps_msg);
bag.write(filepath.string(), ros::Time::now(), mpr_msg);
bag.write(filepath.string(), ros::Time::now(), rt_msg);
int view_counter=0;
std::vector<view_controller_msgs::CameraPlacement>::iterator view_msg;
for(view_msg=views.begin(); view_msg!=views.end(); ++view_msg)
{
AnimationRequest req;
view_msg->time_from_start = ros::Duration(0.1);
ros::Time t_now = ros::Time::now();
view_msg->eye.header.stamp = t_now;
view_msg->focus.header.stamp = t_now;
view_msg->up.header.stamp = t_now;
req.camera_placement = *view_msg;
req.planning_scene = ps_msg;
req.motion_plan_request = mpr_msg;
req.robot_trajectory = rt_msg;
// same filename, counter for viewpoint
std::string ext = boost::lexical_cast<std::string>(view_counter++) + ".ogv";
// TODO
// bag.write(filepath.string(), ros::Time::now(), req.filepath);
std::string video_file = filepath.string()+ext;
req.filepath = video_file;
recorder.record(req);
recorder.forkedRecord();
ROS_INFO("RECORDING DONE!");
}//view
bag.close();
}//traj
}//query
}//scene
}
catch(mongo_ros::DbConnectException &ex)
{
ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again."
<< std::endl << ex.what());
}
ROS_INFO("Successfully performed trajectory playback");
ros::shutdown();
return 0;
}
<commit_msg>changed function name, remove response callback<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage 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.
*********************************************************************/
/* Author: Arjun Menon */
#include <ros/ros.h>
#include <moveit/move_group_interface/move_group.h>
#include <moveit/warehouse/planning_scene_storage.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <view_controller_msgs/CameraPlacement.h>
#include "moveit_recorder/trajectory_retimer.h"
#include "moveit_recorder/animation_recorder.h"
#include <rosbag/bag.h>
#include <rosbag/query.h>
#include <rosbag/view.h>
#include <algorithm>
bool static ready;
void animationResponseCallback(const boost::shared_ptr<std_msgs::Bool const>& msg)
{
ready = msg->data;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "playback");
ros::NodeHandle node_handle;
ros::AsyncSpinner spinner(1);
spinner.start();
sleep(20); // to let RVIZ come up
boost::program_options::options_description desc;
desc.add_options()
("help", "Show help message")
("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.")
("views",boost::program_options::value<std::string>(), "Bag file for viewpoints")
("save_dir",boost::program_options::value<std::string>(), "Directory for saving videos");
boost::program_options::variables_map vm;
boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);
boost::program_options::store(po, vm);
boost::program_options::notify(vm);
if (vm.count("help") || argc == 1) // show help if no parameters passed
{
std::cout << desc << std::endl;
return 1;
}
try
{
//connect to the DB
std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
moveit_warehouse::PlanningSceneStorage pss(host, port);
ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port);
// set up the storage directory
boost::filesystem::path storage_dir( vm.count("save_dir") ? vm["save_dir"].as<std::string>() : "/tmp" );
boost::filesystem::create_directories( storage_dir );
// create bag file to track the associated video to the scene, query, and traj that spawned it
boost::filesystem::path bagpath = storage_dir / "video_lookup.bag";
rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Write);
bag.close();
// load the viewpoints
std::string bagfilename = vm.count("views") ? vm["views"].as<std::string>() : "";
std::vector<view_controller_msgs::CameraPlacement> views;
rosbag::Bag viewbag;
viewbag.open(bagfilename, rosbag::bagmode::Read);
std::vector<std::string> topics; topics.push_back("viewpoints");
rosbag::View view_t(viewbag, rosbag::TopicQuery(topics));
BOOST_FOREACH(rosbag::MessageInstance const m, view_t)
{
view_controller_msgs::CameraPlacement::ConstPtr i = m.instantiate<view_controller_msgs::CameraPlacement>();
if (i != NULL)
views.push_back(*i);
}
viewbag.close();
ROS_INFO("%d views loaded",(int)views.size());
//TODO change these to params
AnimationRecorder recorder( "/rviz/camera_placement",
"planning_scene",
"/move_group/display_planned_path",
"animation_status",
"animation_response",
node_handle);
// ask the warehouse for the scenes
std::vector<std::string> ps_names;
pss.getPlanningSceneNames( ps_names );
ROS_INFO("%d available scenes to display", (int)ps_names.size());
// iterate over scenes
std::vector<std::string>::iterator scene_name = ps_names.begin();
for(; scene_name!=ps_names.end(); ++scene_name)
{
ROS_INFO("Retrieving scene %s", scene_name->c_str());
moveit_warehouse::PlanningSceneWithMetadata pswm;
pss.getPlanningScene(pswm, *scene_name);
moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm);
// ask qarehosue for the queries
std::vector<std::string> pq_names;
pss.getPlanningQueriesNames( pq_names, *scene_name);
ROS_INFO("%d available queries to display", (int)pq_names.size());
// iterate over the queries
std::vector<std::string>::iterator query_name = pq_names.begin();
for(; query_name!=pq_names.end(); ++query_name)
{
ROS_INFO("Retrieving query %s", query_name->c_str());
moveit_warehouse::MotionPlanRequestWithMetadata mprwm;
pss.getPlanningQuery(mprwm, *scene_name, *query_name);
moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm);
// ask warehouse for stored trajectories
std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results;
pss.getPlanningResults(planning_results, *scene_name, *query_name);
ROS_INFO("Loaded %d trajectories", (int)planning_results.size());
// animate each trajectory
std::vector<moveit_warehouse::RobotTrajectoryWithMetadata>::iterator traj_w_mdata = planning_results.begin();
for(; traj_w_mdata!=planning_results.end(); ++traj_w_mdata)
{
moveit_msgs::RobotTrajectory rt_msg;
rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(**traj_w_mdata);
// retime it
TrajectoryRetimer retimer( "robot_description", mpr_msg.group_name );
retimer.configure(ps_msg, mpr_msg);
bool result = retimer.retime(rt_msg);
ROS_INFO("Retiming success? %s", result? "yes" : "no" );
//date and time based filename
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
std::string vid_filename = boost::posix_time::to_simple_string(now);
// fix filename
std::replace(vid_filename.begin(), vid_filename.end(), '-','_');
std::replace(vid_filename.begin(), vid_filename.end(), ' ','_');
std::replace(vid_filename.begin(), vid_filename.end(), ':','_');
boost::filesystem::path filename( vid_filename );
boost::filesystem::path filepath = storage_dir / filename;
// save into lookup
rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Append);
bag.write(filepath.string(), ros::Time::now(), ps_msg);
bag.write(filepath.string(), ros::Time::now(), mpr_msg);
bag.write(filepath.string(), ros::Time::now(), rt_msg);
int view_counter=0;
std::vector<view_controller_msgs::CameraPlacement>::iterator view_msg;
for(view_msg=views.begin(); view_msg!=views.end(); ++view_msg)
{
AnimationRequest req;
view_msg->time_from_start = ros::Duration(0.1);
ros::Time t_now = ros::Time::now();
view_msg->eye.header.stamp = t_now;
view_msg->focus.header.stamp = t_now;
view_msg->up.header.stamp = t_now;
req.camera_placement = *view_msg;
req.planning_scene = ps_msg;
req.motion_plan_request = mpr_msg;
req.robot_trajectory = rt_msg;
// same filename, counter for viewpoint
std::string ext = boost::lexical_cast<std::string>(view_counter++) + ".ogv";
std_msgs::String filemsg; filemsg.data = req.filepath;
bag.write(filepath.string(), ros::Time::now(), filemsg);
std::string video_file = filepath.string()+ext;
req.filepath = video_file;
recorder.record(req);
recorder.startCapture();
ROS_INFO("RECORDING DONE!");
}//view
bag.close();
}//traj
}//query
}//scene
}
catch(mongo_ros::DbConnectException &ex)
{
ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again."
<< std::endl << ex.what());
}
ROS_INFO("Successfully performed trajectory playback");
ros::shutdown();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef SRC_NODES_GENERIC_HPP_
#define SRC_NODES_GENERIC_HPP_
#include <core/traits.hpp>
#include <ports/token_tags.hpp>
#include <ports/ports.hpp>
#include <ports/pure_ports.hpp>
#include <utility>
#include <map>
namespace fc
{
/**
* \brief generic unary node which applies transform with parameter to all inputs
*
* \tparam bin_op binary operator, argument is input of node, second is parameter
*
* \pre bin_op needs to be callable with two arguments
*/
template<class bin_op>
struct transform_node// : node_interface
{
static_assert(utils::function_traits<bin_op>::arity == 2,
"operator in transform node needs to take two parameters");
typedef result_of_t<bin_op> result_type;
typedef typename argtype_of<bin_op,1>::type param_type;
typedef typename argtype_of<bin_op,0>::type data_t;
explicit transform_node(bin_op op)
: param()
, op(op) {}
pure::state_sink<param_type> param;
decltype(auto) operator()(const data_t& in)
{
return op(in, param.get());
}
private:
bin_op op;
};
/// creates transform_node with op as operation.
template<class bin_op>
auto transform(bin_op op)
{
return transform_node<bin_op>(op);
}
/**
* \brief n_ary_switch forwards one of n inputs to output
*
* Simply connect new input ports to add them to the set for the switch.
* The switch itself is controlled by the port "control" which needs to be connected
* to a state source of a type convertible to key_t.
* is specialized for state and events, as the implementations differ.
*
* \tparam data_t type of data flowing through the switch
* \tparam tag, either event_tag or state_tag to set switch to event handling
* or forwarding of state
*
* \key_t key for lookup of inputs in switch. needs to have operator < and ==
*/
template<class data_t, class tag, class key_t = size_t> class n_ary_switch;
template<class data_t, class key_t>
class n_ary_switch<data_t, state_tag, key_t> : public tree_base_node
{
public:
n_ary_switch()
: tree_base_node("switch")
, switch_state(this)
, in_ports()
, out_port(this, [this](){return in_ports.at(switch_state.get()).get();} )
{}
/**
* \brief input port for state of type data_t corresponding to key port.
*
* \returns input port corresponding to key
* \param port, key by which port is identified.
* \post !in_ports.empty()
*/
auto& in(key_t port) noexcept
{
auto it = in_ports.find(port);
if (it == in_ports.end())
it = in_ports.emplace(std::make_pair(port, state_sink<data_t>(this))).first;
return it->second;
}
/// parameter port controlling the switch, expects state of key_t
auto& control() noexcept { return switch_state; }
auto& out() noexcept { return out_port; }
private:
/// provides the current state of the switch.
state_sink<key_t> switch_state;
std::map<key_t, state_sink<data_t>> in_ports;
state_source<data_t> out_port;
};
template<class data_t, class key_t>
class n_ary_switch<data_t, event_tag, key_t> : public tree_base_node
{
public:
n_ary_switch()
: tree_base_node("switch")
, switch_state(this)
, out_port(this)
, in_ports()
{}
/**
* \brief Get port by key. Creates port if none was found for key.
*
* \returns input port corresponding to key
* \param port, key by which port is identified.
* \post !in_ports.empty()
*/
auto& in(key_t port)
{
auto it = in_ports.find(port);
if (it == end(in_ports))
{
it = in_ports.emplace(std::make_pair
( port,
event_sink<data_t>( this,
[this, port](const data_t& in){ forward_call(in, port); })
)
).first;
} //else the port already exists, we can just return it
return it->second;
};
/// output port of events of type data_t.
auto& out() noexcept { return out_port; }
/// parameter port controlling the switch, expects state of key_t
auto& control() noexcept { return switch_state; }
private:
state_sink<key_t> switch_state;
event_source<data_t> out_port;
std::map<key_t, event_sink<data_t>> in_ports;
/// fires incoming event if and only if it is from the currently chosen port.
void forward_call(data_t event, key_t port)
{
assert(!in_ports.empty());
assert(in_ports.find(port) != end(in_ports));
if (port == switch_state.get())
out().fire(event);
}
};
/**
* \brief node which observes a state and fires an event if the state matches a predicate.
*
* Needs to be connected to a tick, which triggers the check of the predicate on the state.
*
* \tparam data_t type of data watched by the watch_node.
* \tparam predicate predicate which is tested on the observed state
* predicate needs to be a callable which takes objects convertible from data_t
* and returns a bool.
*/
template<class data_t, class predicate>
class watch_node : public tree_base_node
{
public:
explicit watch_node(predicate pred)
: tree_base_node("watcher")
, pred{std::move(pred)}
, in_port(this)
, out_port(this)
{
}
watch_node(watch_node&&) = default;
/// State input port, expects data_t.
auto& in() noexcept { return in_port; }
/// Event Output port, fires data_t.
auto& out() noexcept { return out_port; }
/// Event input port expects event of type void. Usually connected to a work_tick.
auto check_tick()
{
return [this]()
{
const auto tmp = in_port.get();
if (pred(tmp))
out_port.fire(tmp);
};
}
private:
predicate pred;
state_sink<data_t> in_port;
event_source<data_t> out_port;
};
/// Creates a watch node with a predicate.
template<class data_t, class predicate>
auto watch(predicate&& pred, data_t)
{
return watch_node<data_t, predicate>{std::forward<predicate>(pred)};
}
/**
* \brief Creates a watch_node, which fires an event, if the state changes.
*
* Does not fire the first time the state is querried.
*/
template<class data_t>
auto on_changed(data_t initial_value = data_t())
{
return watch(
[last{std::move(std::make_unique<data_t>())}](const data_t& in) mutable
{
const bool is_same = last && (*last == in);
last = std::make_unique<data_t>(in);
return !is_same;
},
initial_value);
}
} // namespace fc
#endif /* SRC_NODES_GENERIC_HPP_ */
<commit_msg>FIX generalized lambda capture of unique_ptr.<commit_after>#ifndef SRC_NODES_GENERIC_HPP_
#define SRC_NODES_GENERIC_HPP_
#include <core/traits.hpp>
#include <ports/token_tags.hpp>
#include <ports/ports.hpp>
#include <ports/pure_ports.hpp>
#include <utility>
#include <map>
namespace fc
{
/**
* \brief generic unary node which applies transform with parameter to all inputs
*
* \tparam bin_op binary operator, argument is input of node, second is parameter
*
* \pre bin_op needs to be callable with two arguments
*/
template<class bin_op>
struct transform_node// : node_interface
{
static_assert(utils::function_traits<bin_op>::arity == 2,
"operator in transform node needs to take two parameters");
typedef result_of_t<bin_op> result_type;
typedef typename argtype_of<bin_op,1>::type param_type;
typedef typename argtype_of<bin_op,0>::type data_t;
explicit transform_node(bin_op op)
: param()
, op(op) {}
pure::state_sink<param_type> param;
decltype(auto) operator()(const data_t& in)
{
return op(in, param.get());
}
private:
bin_op op;
};
/// creates transform_node with op as operation.
template<class bin_op>
auto transform(bin_op op)
{
return transform_node<bin_op>(op);
}
/**
* \brief n_ary_switch forwards one of n inputs to output
*
* Simply connect new input ports to add them to the set for the switch.
* The switch itself is controlled by the port "control" which needs to be connected
* to a state source of a type convertible to key_t.
* is specialized for state and events, as the implementations differ.
*
* \tparam data_t type of data flowing through the switch
* \tparam tag, either event_tag or state_tag to set switch to event handling
* or forwarding of state
*
* \key_t key for lookup of inputs in switch. needs to have operator < and ==
*/
template<class data_t, class tag, class key_t = size_t> class n_ary_switch;
template<class data_t, class key_t>
class n_ary_switch<data_t, state_tag, key_t> : public tree_base_node
{
public:
n_ary_switch()
: tree_base_node("switch")
, switch_state(this)
, in_ports()
, out_port(this, [this](){return in_ports.at(switch_state.get()).get();} )
{}
/**
* \brief input port for state of type data_t corresponding to key port.
*
* \returns input port corresponding to key
* \param port, key by which port is identified.
* \post !in_ports.empty()
*/
auto& in(key_t port) noexcept
{
auto it = in_ports.find(port);
if (it == in_ports.end())
it = in_ports.emplace(std::make_pair(port, state_sink<data_t>(this))).first;
return it->second;
}
/// parameter port controlling the switch, expects state of key_t
auto& control() noexcept { return switch_state; }
auto& out() noexcept { return out_port; }
private:
/// provides the current state of the switch.
state_sink<key_t> switch_state;
std::map<key_t, state_sink<data_t>> in_ports;
state_source<data_t> out_port;
};
template<class data_t, class key_t>
class n_ary_switch<data_t, event_tag, key_t> : public tree_base_node
{
public:
n_ary_switch()
: tree_base_node("switch")
, switch_state(this)
, out_port(this)
, in_ports()
{}
/**
* \brief Get port by key. Creates port if none was found for key.
*
* \returns input port corresponding to key
* \param port, key by which port is identified.
* \post !in_ports.empty()
*/
auto& in(key_t port)
{
auto it = in_ports.find(port);
if (it == end(in_ports))
{
it = in_ports.emplace(std::make_pair
( port,
event_sink<data_t>( this,
[this, port](const data_t& in){ forward_call(in, port); })
)
).first;
} //else the port already exists, we can just return it
return it->second;
};
/// output port of events of type data_t.
auto& out() noexcept { return out_port; }
/// parameter port controlling the switch, expects state of key_t
auto& control() noexcept { return switch_state; }
private:
state_sink<key_t> switch_state;
event_source<data_t> out_port;
std::map<key_t, event_sink<data_t>> in_ports;
/// fires incoming event if and only if it is from the currently chosen port.
void forward_call(data_t event, key_t port)
{
assert(!in_ports.empty());
assert(in_ports.find(port) != end(in_ports));
if (port == switch_state.get())
out().fire(event);
}
};
/**
* \brief node which observes a state and fires an event if the state matches a predicate.
*
* Needs to be connected to a tick, which triggers the check of the predicate on the state.
*
* \tparam data_t type of data watched by the watch_node.
* \tparam predicate predicate which is tested on the observed state
* predicate needs to be a callable which takes objects convertible from data_t
* and returns a bool.
*/
template<class data_t, class predicate>
class watch_node : public tree_base_node
{
public:
explicit watch_node(predicate pred)
: tree_base_node("watcher")
, pred{std::move(pred)}
, in_port(this)
, out_port(this)
{
}
watch_node(watch_node&&) = default;
/// State input port, expects data_t.
auto& in() noexcept { return in_port; }
/// Event Output port, fires data_t.
auto& out() noexcept { return out_port; }
/// Event input port expects event of type void. Usually connected to a work_tick.
auto check_tick()
{
return [this]()
{
const auto tmp = in_port.get();
if (pred(tmp))
out_port.fire(tmp);
};
}
private:
predicate pred;
state_sink<data_t> in_port;
event_source<data_t> out_port;
};
/// Creates a watch node with a predicate.
template<class data_t, class predicate>
auto watch(predicate&& pred, data_t)
{
return watch_node<data_t, predicate>{std::forward<predicate>(pred)};
}
/**
* \brief Creates a watch_node, which fires an event, if the state changes.
*
* Does not fire the first time the state is querried.
*/
template<class data_t>
auto on_changed(data_t initial_value = data_t())
{
return watch(
[last = std::make_unique<data_t>()](const data_t& in) mutable
{
const bool is_same = last && (*last == in);
last = std::make_unique<data_t>(in);
return !is_same;
},
initial_value);
}
} // namespace fc
#endif /* SRC_NODES_GENERIC_HPP_ */
<|endoftext|> |
<commit_before>/* Copyright (c) FFLAS-FFPACK
* Written by Ziad Sultan <[email protected]>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
//#include "goto-def.h"
//#define __FFLASFFPACK_USE_OPENMP
//#define __FFLASFFPACK_USE_TBB
//#define __FFLASFFPACK_USE_DATAFLOW
//#define __FFLASFFPACK_FORCE_SEQ
//#define WINOPAR_KERNEL
//#define CLASSIC_SEQ
// #define PROFILE_PLUQ
// #define MONOTONIC_CYCLES
// #define MONOTONIC_MOREPIVOTS
// #define MONOTONIC_FEWPIVOTS
#ifdef MONOTONIC_CYCLES
#define MONOTONIC_APPLYP
#endif
#ifdef MONOTONIC_MOREPIVOTS
#define MONOTONIC_APPLYP
#endif
#ifdef MONOTONIC_FEWPIVOTS
#define MONOTONIC_APPLYP
#endif
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <givaro/modular.h>
#include <givaro/givranditer.h>
#include <iostream>
#include "fflas-ffpack/config-blas.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_randommatrix.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "fflas-ffpack/ffpack/ffpack.h"
#ifdef __FFLASFFPACK_USE_KAAPI
#include "libkomp.h"
#endif
using namespace std;
typedef Givaro::ModularBalanced<double> Field;
//typedef Givaro::ModularBalanced<float> Field;
//typedef Givaro::ZRing<double> Field;
//typedef Givaro::UnparametricZRing<double> Field;
void verification_PLUQ(const Field & F, typename Field::Element * B, typename Field::Element * A,
size_t * P, size_t * Q, size_t m, size_t n, size_t R)
{
FFLAS::ParSeqHelper::Parallel<FFLAS::CuttingStrategy::Block,FFLAS::StrategyParameter::Threads> H;
Field::Element_ptr X = FFLAS::fflas_new (F, m,n);
Field::Element_ptr L, U;
L = FFLAS::fflas_new(F, m,R);
U = FFLAS::fflas_new(F, R,n);
PARFOR1D (i, m*R,H, F.init(L[i], 0.0); );
PARFOR1D (i,n*R,H, F.init(U[i], 0.0); );
PARFOR1D (i,m*n,H, F.init(X[i], 0.0); );
PARFOR1D (i,R,H,
for (size_t j=0; j<i; ++j)
F.assign ( *(U + i*n + j), F.zero);
for (size_t j=i; j<n; ++j)
F.assign (*(U + i*n + j), *(A+ i*n+j));
);
PARFOR1D (j,R,H,
for (size_t i=0; i<=j; ++i )
F.assign( *(L+i*R+j), F.zero);
F.assign(*(L+j*R+j), F.one);
for (size_t i=j+1; i<m; i++)
F.assign( *(L + i*R+j), *(A+i*n+j));
);
PAR_BLOCK{
SYNCH_GROUP(
TASK(MODE(CONSTREFERENCE(F,P,L)),
FFPACK::applyP( F, FFLAS::FflasLeft, FFLAS::FflasTrans, R,0,m, L, R, P););
TASK(MODE(CONSTREFERENCE(F,Q,U)),
FFPACK::applyP (F, FFLAS::FflasRight, FFLAS::FflasNoTrans, R,0,n, U, n, Q););
WAIT;
typename FFLAS::ParSeqHelper::Parallel<FFLAS::CuttingStrategy::Block,FFLAS::StrategyParameter::Threads> pWH (MAX_THREADS);
TASK(MODE(CONSTREFERENCE(F,U,L,X)),
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,R,
F.one, L,R, U,n, F.zero, X,n, pWH););
);
}
bool fail = false;
for(size_t i=0; i<m; ++i)
for (size_t j=0; j<n; ++j)
if (!F.areEqual (*(B+i*n+j), *(X+i*n+j))){
std::cout << " Initial["<<i<<","<<j<<"] = " << (*(B+i*n+j))
<< " Result["<<i<<","<<j<<"] = " << (*(X+i*n+j))
<< std::endl;
fail=true;
}
if (fail)
std::cout<<"FAIL"<<std::endl;
else
std::cout<<"PASS"<<std::endl;
FFLAS::fflas_delete( U);
FFLAS::fflas_delete( L);
FFLAS::fflas_delete( X);
}
void Rec_Initialize(Field &F, Field::Element * C, size_t m, size_t n, size_t ldc)
{
if(std::min(m,n) <= ldc/NUM_THREADS){
for(size_t i=0; i<m; i++)
FFLAS::fzero(F, 1, n, C+i*n, n);
}
else{
size_t M2 = m >> 1;
size_t N2 = n >> 1;
typename Field::Element * C2 = C + N2;
typename Field::Element * C3 = C + M2*ldc;
typename Field::Element * C4 = C3 + N2;
SYNCH_GROUP(
TASK(MODE(CONSTREFERENCE(F)), Rec_Initialize(F,C,M2,N2, ldc););
TASK(MODE(CONSTREFERENCE(F)), Rec_Initialize(F,C2,M2,n-N2, ldc););
TASK(MODE(CONSTREFERENCE(F)), Rec_Initialize(F,C3,m-M2,N2, ldc););
TASK(MODE(CONSTREFERENCE(F)), Rec_Initialize(F,C4,m-M2,n-N2, ldc););
);
}
}
int main(int argc, char** argv) {
size_t iter = 3 ;
bool slab=false;
int q = 131071 ;
int m = 2000 ;
int n = 2000 ;
int r = 2000 ;
int v = 0;
int t=MAX_THREADS;
int NBK = -1;
bool par=false;
bool grp =true;
Argument as[] = {
{ 's', "-s S", "Use the Slab recursive algorithm (LUdivine)instead of the tile recursive algorithm (PLUQ).", TYPE_BOOL , &slab },
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q },
{ 'm', "-m M", "Set the row dimension of A.", TYPE_INT , &m },
{ 'n', "-n N", "Set the col dimension of A.", TYPE_INT , &n },
{ 'r', "-r R", "Set the rank of matrix A.", TYPE_INT , &r },
{ 'g', "-g yes/no", "Generic rank profile (yes) or random rank profile (no).", TYPE_BOOL , &grp },
{ 'i', "-i I", "Set number of repetitions.", TYPE_INT , &iter },
{ 'v', "-v V", "Set 1 if need verification of result else 0.", TYPE_INT , &v },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t },
{ 'b', "-b B", "number of numa blocks per dimension for the numa placement", TYPE_INT , &NBK },
{ 'p', "-p P", "whether to run or not the parallel PLUQ", TYPE_BOOL , &par },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
Field F(q);
if (r > std::min(m,n)){
std::cerr<<"Warning: rank can not be greater than min (m,n). It has been forced to min (m,n)"<<std::endl;
r=std::min(m,n);
}
if (!par) { t=1;NBK=1;}
if (NBK==-1) NBK = t;
Field::Element_ptr A, Acop;
A = FFLAS::fflas_new(F,m,n);
PAR_BLOCK{
Rec_Initialize(F, A, m, n, n);
// FFLAS::pfzero(F,m,n,A,m/NBK);
if (grp){
size_t * cols = FFLAS::fflas_new<size_t>(n);
size_t * rows = FFLAS::fflas_new<size_t>(m);
for (int i=0; i<n; ++i)
cols[i] = i;
for (int i=0; i<m; ++i)
rows[i] = i;
FFPACK::RandomMatrixWithRankandRPM (F, m, n ,r, A, n, rows, cols);
FFLAS::fflas_delete(cols);
FFLAS::fflas_delete(rows);
} else
FFPACK::RandomMatrixWithRankandRandomRPM (F, m, n ,r, A, n);
}
size_t R;
FFLAS::Timer chrono;
double *time=new double[iter];
enum FFLAS::FFLAS_DIAG diag = FFLAS::FflasNonUnit;
size_t maxP, maxQ;
maxP = m;
maxQ = n;
size_t *P = FFLAS::fflas_new<size_t>(maxP);
size_t *Q = FFLAS::fflas_new<size_t>(maxQ);
Acop = FFLAS::fflas_new(F,m,n);
FFLAS::ParSeqHelper::Parallel<FFLAS::CuttingStrategy::Recursive,
FFLAS::StrategyParameter::TwoDAdaptive> parH;
PARFOR1D(i,(size_t)m,parH,
FFLAS::fassign(F, n, A + i*n, 1, Acop + i*n, 1);
// for (size_t j=0; j<(size_t)n; ++j)
// Acop[i*n+j]= A[i*n+j];
);
for (size_t i=0;i<=iter;++i){
PARFOR1D(j,maxP,parH, P[j]=0; );
PARFOR1D(j,maxQ,parH, Q[j]=0; );
PARFOR1D(k,(size_t)m,parH,
FFLAS::fassign(F, n, Acop + k*n, 1, A + k*n, 1);
// for (size_t j=0; j<(size_t)n; ++j)
// F.assign( A[k*n+j] , Acop[k*n+j]) ;
);
chrono.clear();
if (i) chrono.start();
if (par){
PAR_BLOCK{
R = FFPACK::PLUQ(F, diag, m, n, A, n, P, Q, parH);
}
}
else{
if (slab)
R = FFPACK::LUdivine (F, diag, FFLAS::FflasNoTrans, m, n, A, n, P, Q);
else
R = FFPACK::PLUQ(F, diag, m, n, A, n, P, Q);
}
if (i) {chrono.stop(); time[i-1]=chrono.realtime();}
}
std::sort(time, time+iter);
double mediantime = time[iter/2];
delete[] time;
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
#define CUBE(x) ((x)*(x)*(x))
double gflop = 2.0/3.0*CUBE(double(r)/1000.0) +2*m/1000.0*n/1000.0*double(r)/1000.0 - double(r)/1000.0*double(r)/1000.0*(m+n)/1000;
std::cout << "Time: " << mediantime
<< " Gfops: " << gflop / mediantime;
FFLAS::writeCommandString(std::cout, as) << std::endl;
//verification
if(v)
verification_PLUQ(F,Acop,A,P,Q,m,n,R);
FFLAS::fflas_delete (P);
FFLAS::fflas_delete (Q);
FFLAS::fflas_delete (A);
FFLAS::fflas_delete (Acop);
return 0;
}
/* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>Updated benchmark-pluq for PLUQ with ParSeqHelper<commit_after>/* Copyright (c) FFLAS-FFPACK
* Written by Ziad Sultan <[email protected]>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
//#include "goto-def.h"
//#define __FFLASFFPACK_USE_OPENMP
//#define __FFLASFFPACK_USE_TBB
//#define __FFLASFFPACK_USE_DATAFLOW
//#define __FFLASFFPACK_FORCE_SEQ
//#define WINOPAR_KERNEL
//#define CLASSIC_SEQ
// #define PROFILE_PLUQ
// #define MONOTONIC_CYCLES
// #define MONOTONIC_MOREPIVOTS
// #define MONOTONIC_FEWPIVOTS
#ifdef MONOTONIC_CYCLES
#define MONOTONIC_APPLYP
#endif
#ifdef MONOTONIC_MOREPIVOTS
#define MONOTONIC_APPLYP
#endif
#ifdef MONOTONIC_FEWPIVOTS
#define MONOTONIC_APPLYP
#endif
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <givaro/modular.h>
#include <givaro/givranditer.h>
#include <iostream>
#include "fflas-ffpack/config-blas.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/fflas_randommatrix.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "fflas-ffpack/ffpack/ffpack.h"
#ifdef __FFLASFFPACK_USE_KAAPI
#include "libkomp.h"
#endif
using namespace std;
typedef Givaro::ModularBalanced<double> Field;
//typedef Givaro::ModularBalanced<float> Field;
//typedef Givaro::ZRing<double> Field;
//typedef Givaro::UnparametricZRing<double> Field;
void verification_PLUQ(const Field & F, typename Field::Element * B, typename Field::Element * A,
size_t * P, size_t * Q, size_t m, size_t n, size_t R)
{
FFLAS::ParSeqHelper::Parallel<FFLAS::CuttingStrategy::Block,FFLAS::StrategyParameter::Threads> H;
Field::Element_ptr X = FFLAS::fflas_new (F, m,n);
Field::Element_ptr L, U;
L = FFLAS::fflas_new(F, m,R);
U = FFLAS::fflas_new(F, R,n);
PARFOR1D (i, m*R,H, F.init(L[i], 0.0); );
PARFOR1D (i,n*R,H, F.init(U[i], 0.0); );
PARFOR1D (i,m*n,H, F.init(X[i], 0.0); );
PARFOR1D (i,R,H,
for (size_t j=0; j<i; ++j)
F.assign ( *(U + i*n + j), F.zero);
for (size_t j=i; j<n; ++j)
F.assign (*(U + i*n + j), *(A+ i*n+j));
);
PARFOR1D (j,R,H,
for (size_t i=0; i<=j; ++i )
F.assign( *(L+i*R+j), F.zero);
F.assign(*(L+j*R+j), F.one);
for (size_t i=j+1; i<m; i++)
F.assign( *(L + i*R+j), *(A+i*n+j));
);
PAR_BLOCK{
SYNCH_GROUP(
TASK(MODE(CONSTREFERENCE(F,P,L)),
FFPACK::applyP( F, FFLAS::FflasLeft, FFLAS::FflasTrans, R,0,m, L, R, P););
TASK(MODE(CONSTREFERENCE(F,Q,U)),
FFPACK::applyP (F, FFLAS::FflasRight, FFLAS::FflasNoTrans, R,0,n, U, n, Q););
WAIT;
typename FFLAS::ParSeqHelper::Parallel<FFLAS::CuttingStrategy::Block,FFLAS::StrategyParameter::Threads> pWH (MAX_THREADS);
TASK(MODE(CONSTREFERENCE(F,U,L,X)),
FFLAS::fgemm (F, FFLAS::FflasNoTrans, FFLAS::FflasNoTrans, m,n,R,
F.one, L,R, U,n, F.zero, X,n, pWH););
);
}
bool fail = false;
for(size_t i=0; i<m; ++i)
for (size_t j=0; j<n; ++j)
if (!F.areEqual (*(B+i*n+j), *(X+i*n+j))){
std::cout << " Initial["<<i<<","<<j<<"] = " << (*(B+i*n+j))
<< " Result["<<i<<","<<j<<"] = " << (*(X+i*n+j))
<< std::endl;
fail=true;
}
if (fail)
std::cout<<"FAIL"<<std::endl;
else
std::cout<<"PASS"<<std::endl;
FFLAS::fflas_delete( U);
FFLAS::fflas_delete( L);
FFLAS::fflas_delete( X);
}
void Rec_Initialize(Field &F, Field::Element * C, size_t m, size_t n, size_t ldc)
{
if(std::min(m,n) <= ldc/NUM_THREADS){
for(size_t i=0; i<m; i++)
FFLAS::fzero(F, 1, n, C+i*n, n);
}
else{
size_t M2 = m >> 1;
size_t N2 = n >> 1;
typename Field::Element * C2 = C + N2;
typename Field::Element * C3 = C + M2*ldc;
typename Field::Element * C4 = C3 + N2;
SYNCH_GROUP(
TASK(MODE(CONSTREFERENCE(F)), Rec_Initialize(F,C,M2,N2, ldc););
TASK(MODE(CONSTREFERENCE(F)), Rec_Initialize(F,C2,M2,n-N2, ldc););
TASK(MODE(CONSTREFERENCE(F)), Rec_Initialize(F,C3,m-M2,N2, ldc););
TASK(MODE(CONSTREFERENCE(F)), Rec_Initialize(F,C4,m-M2,n-N2, ldc););
);
}
}
int main(int argc, char** argv) {
size_t iter = 3 ;
bool slab=false;
int q = 131071 ;
int m = 2000 ;
int n = 2000 ;
int r = 2000 ;
int v = 0;
int t=MAX_THREADS;
int NBK = -1;
bool par=false;
bool grp =true;
Argument as[] = {
{ 's', "-s S", "Use the Slab recursive algorithm (LUdivine)instead of the tile recursive algorithm (PLUQ).", TYPE_BOOL , &slab },
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q },
{ 'm', "-m M", "Set the row dimension of A.", TYPE_INT , &m },
{ 'n', "-n N", "Set the col dimension of A.", TYPE_INT , &n },
{ 'r', "-r R", "Set the rank of matrix A.", TYPE_INT , &r },
{ 'g', "-g yes/no", "Generic rank profile (yes) or random rank profile (no).", TYPE_BOOL , &grp },
{ 'i', "-i I", "Set number of repetitions.", TYPE_INT , &iter },
{ 'v', "-v V", "Set 1 if need verification of result else 0.", TYPE_INT , &v },
{ 't', "-t T", "number of virtual threads to drive the partition.", TYPE_INT , &t },
{ 'b', "-b B", "number of numa blocks per dimension for the numa placement", TYPE_INT , &NBK },
{ 'p', "-p P", "whether to run or not the parallel PLUQ", TYPE_BOOL , &par },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
Field F(q);
if (r > std::min(m,n)){
std::cerr<<"Warning: rank can not be greater than min (m,n). It has been forced to min (m,n)"<<std::endl;
r=std::min(m,n);
}
if (!par) { t=1;NBK=1;}
if (NBK==-1) NBK = t;
Field::Element_ptr A, Acop;
A = FFLAS::fflas_new(F,m,n);
PAR_BLOCK{
Rec_Initialize(F, A, m, n, n);
// FFLAS::pfzero(F,m,n,A,m/NBK);
if (grp){
size_t * cols = FFLAS::fflas_new<size_t>(n);
size_t * rows = FFLAS::fflas_new<size_t>(m);
for (int i=0; i<n; ++i)
cols[i] = i;
for (int i=0; i<m; ++i)
rows[i] = i;
FFPACK::RandomMatrixWithRankandRPM (F, m, n ,r, A, n, rows, cols);
FFLAS::fflas_delete(cols);
FFLAS::fflas_delete(rows);
} else
FFPACK::RandomMatrixWithRankandRandomRPM (F, m, n ,r, A, n);
}
size_t R;
FFLAS::Timer chrono;
double *time=new double[iter];
enum FFLAS::FFLAS_DIAG diag = FFLAS::FflasNonUnit;
size_t maxP, maxQ;
maxP = m;
maxQ = n;
size_t *P = FFLAS::fflas_new<size_t>(maxP);
size_t *Q = FFLAS::fflas_new<size_t>(maxQ);
Acop = FFLAS::fflas_new(F,m,n);
FFLAS::ParSeqHelper::Parallel<FFLAS::CuttingStrategy::Recursive,
FFLAS::StrategyParameter::TwoDAdaptive> parH;
PARFOR1D(i,(size_t)m,parH,
FFLAS::fassign(F, n, A + i*n, 1, Acop + i*n, 1);
// for (size_t j=0; j<(size_t)n; ++j)
// Acop[i*n+j]= A[i*n+j];
);
for (size_t i=0;i<=iter;++i){
PARFOR1D(j,maxP,parH, P[j]=0; );
PARFOR1D(j,maxQ,parH, Q[j]=0; );
PARFOR1D(k,(size_t)m,parH,
FFLAS::fassign(F, n, Acop + k*n, 1, A + k*n, 1);
// for (size_t j=0; j<(size_t)n; ++j)
// F.assign( A[k*n+j] , Acop[k*n+j]) ;
);
chrono.clear();
if (i) chrono.start();
if (par){
PAR_BLOCK{
R = FFPACK::PLUQ(F, diag, m, n, A, n, P, Q, t, parH);
}
}
else{
if (slab)
R = FFPACK::LUdivine (F, diag, FFLAS::FflasNoTrans, m, n, A, n, P, Q);
else
R = FFPACK::PLUQ(F, diag, m, n, A, n, P, Q);
}
if (i) {chrono.stop(); time[i-1]=chrono.realtime();}
}
std::sort(time, time+iter);
double mediantime = time[iter/2];
delete[] time;
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
#define CUBE(x) ((x)*(x)*(x))
double gflop = 2.0/3.0*CUBE(double(r)/1000.0) +2*m/1000.0*n/1000.0*double(r)/1000.0 - double(r)/1000.0*double(r)/1000.0*(m+n)/1000;
std::cout << "Time: " << mediantime
<< " Gfops: " << gflop / mediantime;
FFLAS::writeCommandString(std::cout, as) << std::endl;
//verification
if(v)
verification_PLUQ(F,Acop,A,P,Q,m,n,R);
FFLAS::fflas_delete (P);
FFLAS::fflas_delete (Q);
FFLAS::fflas_delete (A);
FFLAS::fflas_delete (Acop);
return 0;
}
/* -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 David Wicks
* 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.
*
* 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.
*/
#pragma once
/**
Functions for easier manipulation of STL containers.
*/
#include "Pockets.h"
namespace pockets
{
//! Remove all elements from \a map for which \a compare returns true
template<class MAP_TYPE, class COMPARATOR>
void map_erase_if( MAP_TYPE *map, COMPARATOR compare )
{
auto iter = map->begin();
while( iter != map->end() )
{
if( compare( iter->second ) )
{
map->erase( iter++ );
}
else
{
iter++;
}
}
}
// Return a vector of all the keys in a map
template<typename K, typename V>
std::vector<K> map_keys( const std::map<K, V> &map )
{
std::vector<K> ret;
for( auto &pair : map )
{
ret.push_back( pair.first );
}
return ret;
}
//! Remove all elements from \a vec that match \a compare
template<class ELEMENT_TYPE, class COMPARATOR>
void vector_erase_if( std::vector<ELEMENT_TYPE> *vec, COMPARATOR compare )
{
vec->erase( std::remove_if( vec->begin()
, vec->end()
, compare )
, vec->end() );
}
//! Remove all copies of \a element from \a vec
template<class ELEMENT_TYPE>
void vector_remove( std::vector<ELEMENT_TYPE> *vec, const ELEMENT_TYPE &element )
{
vec->erase( std::remove_if( vec->begin()
, vec->end()
, [=](const ELEMENT_TYPE &e){ return e == element; } )
, vec->end() );
}
//! Returns true if \a vec contains the element \a compare
template<class ELEMENT_TYPE>
bool vector_contains( const std::vector<ELEMENT_TYPE> &vec, const ELEMENT_TYPE &compare )
{
return std::find( vec.begin(), vec.end(), compare ) != vec.end();
}
//! Returns true if \a compare function returns true for an element in \a vec
template<class ELEMENT_TYPE, class COMPARATOR>
bool vector_contains( const std::vector<ELEMENT_TYPE> &vec, COMPARATOR compare )
{
return std::find_if( vec.begin(), vec.end(), compare ) != vec.end();
}
}
<commit_msg>Added erase_if templated method to collection utilities.<commit_after>/*
* Copyright (c) 2013 David Wicks
* 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.
*
* 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.
*/
#pragma once
/**
Functions for easier manipulation of STL containers.
*/
#include "Pockets.h"
namespace pockets
{
//! Remove all elements from \a map for which \a compare returns true
template<class MAP_TYPE, class COMPARATOR>
void map_erase_if( MAP_TYPE *map, COMPARATOR compare )
{
auto iter = map->begin();
while( iter != map->end() )
{
if( compare( iter->second ) )
{
map->erase( iter++ );
}
else
{
iter++;
}
}
}
// Return a vector of all the keys in a map
template<typename K, typename V>
std::vector<K> map_keys( const std::map<K, V> &map )
{
std::vector<K> ret;
for( auto &pair : map )
{
ret.push_back( pair.first );
}
return ret;
}
//! Remove all elements from \a vec that match \a compare
template<class ELEMENT_TYPE, class COMPARATOR>
void vector_erase_if( std::vector<ELEMENT_TYPE> *vec, COMPARATOR compare )
{
vec->erase( std::remove_if( vec->begin()
, vec->end()
, compare )
, vec->end() );
}
//! This is closer to an earlier strategy I had than vector_erase_if,
//! but that was plagued by obscure error messages. Will see if this works
//! a bit better / more flexibly
template<class CONTAINER_TYPE, class COMPARATOR>
void erase_if( CONTAINER_TYPE *container, COMPARATOR compare )
{
container->erase( std::remove_if( container->begin(),
container->end(),
compare ),
container->end() );
}
//! Remove all copies of \a element from \a vec
template<class ELEMENT_TYPE>
void vector_remove( std::vector<ELEMENT_TYPE> *vec, const ELEMENT_TYPE &element )
{
vec->erase( std::remove_if( vec->begin()
, vec->end()
, [=](const ELEMENT_TYPE &e){ return e == element; } )
, vec->end() );
}
//! Returns true if \a vec contains the element \a compare
template<class ELEMENT_TYPE>
bool vector_contains( const std::vector<ELEMENT_TYPE> &vec, const ELEMENT_TYPE &compare )
{
return std::find( vec.begin(), vec.end(), compare ) != vec.end();
}
//! Returns true if \a compare function returns true for an element in \a vec
template<class ELEMENT_TYPE, class COMPARATOR>
bool vector_contains( const std::vector<ELEMENT_TYPE> &vec, COMPARATOR compare )
{
return std::find_if( vec.begin(), vec.end(), compare ) != vec.end();
}
}
<|endoftext|> |
<commit_before>#include "ofAppQtWindow.h"
//----------------------------------------------------------
ofAppQtWindow::ofAppQtWindow(QWidget *parent){
ofLogVerbose() << "ofAppQtWindow Ctor";
bShouldClose = false;
bEnableSetupScreen = true;
buttonPressed = false;
bWindowNeedsShowing = true;
buttonInUse = 0;
iconSet = false;
orientation = OF_ORIENTATION_DEFAULT;
windowMode = OF_WINDOW;
pixelScreenCoordScale = 1;
nFramesSinceWindowResized = 0;
windowW = 0;
windowH = 0;
currentW = 0;
currentH = 0;
hasQtApp = false;
bIsWindow = false;
bSetupSucceded = false;
if (parentWidget == 0) {
parentWidget = nullptr;
}
else {
parentWidget = parent;
}
ofAppPtr = nullptr;
qtWidgetPtr = nullptr;
}
//----------------------------------------------------------
ofAppQtWindow::~ofAppQtWindow() {
// ofLogVerbose() << "ofAppQtWindow Dtor";
}
void ofAppQtWindow::close()
{
ofLogVerbose() << "close";
qtWidgetPtr->makeCurrent();
events().disable();
bWindowNeedsShowing = true;
}
void ofAppQtWindow::createQtApp()
{
int argc = 1;
char *argv = "openframeworks";
char **vptr = &argv;
qtAppPtr = new QApplication(argc, vptr);
hasQtApp = true;
}
void ofAppQtWindow::setQtAppPointer(QApplication * qtApp)
{
qtAppPtr = qtApp;
hasQtApp = true;
}
void ofAppQtWindow::setIsWindow(bool value)
{
bIsWindow = value;
if (qtWidgetPtr == 0 || qtWidgetPtr == nullptr) return;
qtWidgetPtr->setAttribute(Qt::WA_AlwaysStackOnTop, value); // very important. fixes transparency bug
}
void ofAppQtWindow::paint()
{
// ofLogVerbose() << "ofAppQtWindow paint";
ofGetMainLoop()->setCurrentWindow(this);
if (getWindowShouldClose()) {
close();
}
else {
update();
draw();
}
}
//------------------------------------------------------------
#ifdef TARGET_OPENGLES
void ofAppGLFWWindow::setup(const ofGLESWindowSettings & settings) {
#else
void ofAppQtWindow::setup(const ofGLWindowSettings & settings) {
#endif
const ofQtGLWindowSettings * glSettings = dynamic_cast<const ofQtGLWindowSettings*>(&settings);
if (glSettings) {
setup(*glSettings);
}
else {
setup(ofQtGLWindowSettings(settings));
}
}
//------------------------------------------------------------
void ofAppQtWindow::setup(const ofQtGLWindowSettings & _settings) {
ofLogVerbose() << "setup ofAppQtWindow";
if (qtWidgetPtr) {
ofLogError() << "window already setup, probably you are mixing old and new style setup";
ofLogError() << "call only ofCreateWindow(settings) or ofSetupOpenGL(...)";
ofLogError() << "calling window->setup() after ofCreateWindow() is not necesary and won't do anything";
return;
}
settings = _settings;
//////////////////////////////////////
// setup OpenGL
//////////////////////////////////////
QSurfaceFormat format;
format.setVersion(settings.glVersionMajor, settings.glVersionMinor);
format.setProfile(QSurfaceFormat::CoreProfile);
format.setAlphaBufferSize(settings.alphaBits);
format.setDepthBufferSize(settings.depthBits);
format.setStencilBufferSize(settings.stencilBits);
format.setStereo(settings.stereo);
format.setSamples(settings.numSamples);
if (settings.doubleBuffering) {
format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
}
else {
format.setSwapBehavior(QSurfaceFormat::SingleBuffer);
}
QSurfaceFormat::setDefaultFormat(format);
//////////////////////////////////////
// create renderer
//////////////////////////////////////
if (settings.glVersionMajor >= 3) {
currentRenderer = shared_ptr<ofBaseRenderer>(new ofGLProgrammableRenderer(this));
}
else {
currentRenderer = shared_ptr<ofBaseRenderer>(new ofGLRenderer(this));
}
//////////////////////////////////////
// create Qt window
//////////////////////////////////////
qtWidgetPtr = new QtGLWidget(*this, parentWidget);
setIsWindow(bIsWindow);
qtWidgetPtr->resize(settings.width, settings.height);
// qtWidgetPtr->setFormat(format);
qtWidgetPtr->setWindowTitle(settings.title);
// currentW = qtWidgetPtr->size().width();
// currentH = qtWidgetPtr->size().height();
windowW = settings.width;
windowH = settings.height;
bWindowNeedsShowing = settings.visible;
// qtWidgetPtr->setAlphabits(settings.alphaBits);
// qtWidgetPtr->setNumSamples(settings.numSamples);
qtWidgetPtr->makeCurrent();
qtWidgetPtr->show();
// int framebufferW, framebufferH;
// glfwGetFramebufferSize(qtWidgetPtr, &framebufferW, &framebufferH);
//this lets us detect if the window is running in a retina mode
//if (framebufferW != windowW) {
// pixelScreenCoordScale = framebufferW / windowW;
// auto position = getWindowPosition();
// setWindowShape(windowW, windowH);
// setWindowPosition(position.x, position.y);
//}
#ifndef TARGET_OPENGLES
static bool inited = false;
if (!inited) {
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
ofLogError("ofAppRunner") << "couldn't init GLEW: " << glewGetErrorString(err);
return;
}
inited = true;
}
#endif
ofLogVerbose() << "GL Version:" << glGetString(GL_VERSION);
//////////////////////////////////////
// setup renderer
//////////////////////////////////////
if (currentRenderer->getType() == ofGLProgrammableRenderer::TYPE) {
#ifndef TARGET_OPENGLES
static_cast<ofGLProgrammableRenderer*>(currentRenderer.get())->setup(settings.glVersionMajor, settings.glVersionMinor);
#else
static_cast<ofGLProgrammableRenderer*>(currentRenderer.get())->setup(settings.glesVersion, 0);
#endif
}
else {
static_cast<ofGLRenderer*>(currentRenderer.get())->setup();
}
//events().notifySetup();
//////////////////////////////////////
// notes
//////////////////////////////////////
// this call goes to an endless loop
// which causes no OF calls
// qtAppPtr->exec();
// we will use
// qtAppPtr->processEvents();
// so that we can call qt inside the OF loop
bSetupSucceded = true;
}
//------------------------------------------------------------
void ofAppQtWindow::update() {
// ofLogVerbose() << "update ofAppQtWindow";
qtWidgetPtr->makeCurrent();
events().notifyUpdate();
//////////////////////////////////////
// process Qt events
//////////////////////////////////////
qtWidgetPtr->makeCurrent();
qtWidgetPtr->update();
//////////////////////////////////////
//show the window right before the first draw call.
if (bWindowNeedsShowing && qtWidgetPtr) {
// GLFW update was here
bWindowNeedsShowing = false;
if (settings.windowMode == OF_FULLSCREEN) {
setFullscreen(true);
}
}
}
//------------------------------------------------------------
void ofAppQtWindow::draw() {
// ofLogVerbose() << "draw ofAppQtWindow";
currentRenderer->startRender();
if (bEnableSetupScreen) currentRenderer->setupScreen();
events().notifyDraw();
#ifdef TARGET_WIN32
if (currentRenderer->getBackgroundAuto() == false) {
// on a PC resizing a window with this method of accumulation (essentially single buffering)
// is BAD, so we clear on resize events.
if (nFramesSinceWindowResized < 3) {
currentRenderer->clear();
}
else {
if ((events().getFrameNum() < 3 || nFramesSinceWindowResized < 3) && settings.doubleBuffering) {
// needed if we want events from Of to Qt
// currently crashes on closing window
// it slows down framerate quite a lot!
if (hasQtApp) {
qtAppPtr->processEvents();
}
}
else {
glFlush();
}
}
}
else {
if (settings.doubleBuffering) {
// needed if we want events from Of to Qt
// currently crashes on closing window
// it slows down framerate quite a lot!
if (hasQtApp) {
qtAppPtr->processEvents();
}
}
else {
glFlush();
}
}
#else
if (currentRenderer->getBackgroundAuto() == false) {
// in accum mode resizing a window is BAD, so we clear on resize events.
if (nFramesSinceWindowResized < 3) {
currentRenderer->clear();
}
}
if (settings.doubleBuffering) {
glfwSwapBuffers(windowP);
}
else {
glFlush();
}
#endif
currentRenderer->finishRender();
nFramesSinceWindowResized++;
}
//------------------------------------------------------------
ofCoreEvents & ofAppQtWindow::events() {
return coreEvents;
}
//------------------------------------------------------------
shared_ptr<ofBaseRenderer> & ofAppQtWindow::renderer() {
return currentRenderer;
}
QWidget * ofAppQtWindow::getQOpenGLWidget()
{
return qtWidgetPtr;
}
//------------------------------------------------------------
void ofAppQtWindow::setAppPtr(shared_ptr<ofBaseApp> appPtr){
ofAppPtr = appPtr;
}
//------------------------------------------------------------
void ofAppQtWindow::setStatusMessage(string s) {
}
//------------------------------------------------------------
void ofAppQtWindow::exitApp() {
ofLog(OF_LOG_VERBOSE, "QT OF app is being terminated!");
OF_EXIT_APP(0);
}
////------------------------------------------------------------
//float ofAppQtWindow::getFrameRate() {
// return qtWidgetPtr->getGlFrameRate();
//}
//------------------------------------------------------------
void ofAppQtWindow::setWindowTitle(string title) {
settings.title = title;
qtWidgetPtr->setWindowTitle(title);
}
//------------------------------------------------------------
glm::vec2 ofAppQtWindow::getWindowSize() {
int width = qtWidgetPtr->width();
int height = qtWidgetPtr->height();
return glm::vec2(width, height);
}
//------------------------------------------------------------
glm::vec2 ofAppQtWindow::getWindowPosition() {
int x = qtWidgetPtr->pos().x();
int y = qtWidgetPtr->pos().y();
// cout << "getWindowPosition "<< x <<" "<< y << endl;
return glm::vec2{ x, y };
}
//------------------------------------------------------------
glm::vec2 ofAppQtWindow::getScreenSize() {
int width = qtWidgetPtr->size().width();
int height = qtWidgetPtr->size().height();
// cout << "getScreenSize " << width << " " << height << endl;
return glm::vec2{ width, height };
}
//------------------------------------------------------------
void ofAppQtWindow::setWindowPosition(int x, int y) {
// cout << "setWindowPosition " << x << " " << y << endl;
qtWidgetPtr->move(QPoint{ x, y });
}
//------------------------------------------------------------
void ofAppQtWindow::setWindowShape(int w, int h) {
if (windowMode == OF_WINDOW) {
windowW = w;
windowH = h;
}
currentW = w / pixelScreenCoordScale;
currentH = h / pixelScreenCoordScale;
#ifdef TARGET_OSX
auto pos = getWindowPosition();
windowP->resize(currentW, currentH);
if (pos != getWindowPosition()) {
setWindowPosition(pos.x, pos.y);
}
#else
// cout << "setWindowShape " << currentW << " " << currentH << endl;
qtWidgetPtr->resize(currentW, currentH);
#endif
}
//------------------------------------------------------------
void ofAppQtWindow::hideCursor() {
qtWidgetPtr->unsetCursor();
}
//------------------------------------------------------------
void ofAppQtWindow::showCursor() {
showCursor();
}
//------------------------------------------------------------
int ofAppQtWindow::getWidth() {
if (orientation == OF_ORIENTATION_DEFAULT || orientation == OF_ORIENTATION_180) {
return currentW * pixelScreenCoordScale;
}
else {
return currentH * pixelScreenCoordScale;
}
}
//------------------------------------------------------------
int ofAppQtWindow::getHeight() {
if (orientation == OF_ORIENTATION_DEFAULT || orientation == OF_ORIENTATION_180) {
return currentH * pixelScreenCoordScale;
}
else {
return currentW * pixelScreenCoordScale;
}
}
//------------------------------------------------------------
ofWindowMode ofAppQtWindow::getWindowMode() {
return windowMode;
}
//------------------------------------------------------------
void ofAppQtWindow::enableSetupScreen() {
bEnableSetupScreen = true;
}
//------------------------------------------------------------
void ofAppQtWindow::disableSetupScreen() {
bEnableSetupScreen = false;
}
void ofAppQtWindow::makeCurrent()
{
// used
qtWidgetPtr->makeCurrent();
}
void ofAppQtWindow::swapBuffers()
{
//unused
// qtWidgetPtr->swapBuffers();
}
void ofAppQtWindow::startRender()
{
//unused
// renderer()->startRender();
}
void ofAppQtWindow::finishRender()
{
//unused
// renderer()->finishRender();
}
<commit_msg>fixes to compile current of master<commit_after>#include "ofAppQtWindow.h"
//----------------------------------------------------------
ofAppQtWindow::ofAppQtWindow(QWidget *parent){
ofLogVerbose() << "ofAppQtWindow Ctor";
bShouldClose = false;
bEnableSetupScreen = true;
buttonPressed = false;
bWindowNeedsShowing = true;
buttonInUse = 0;
iconSet = false;
orientation = OF_ORIENTATION_DEFAULT;
windowMode = OF_WINDOW;
pixelScreenCoordScale = 1;
nFramesSinceWindowResized = 0;
windowW = 0;
windowH = 0;
currentW = 0;
currentH = 0;
hasQtApp = false;
bIsWindow = false;
bSetupSucceded = false;
if (parentWidget == 0) {
parentWidget = nullptr;
}
else {
parentWidget = parent;
}
ofAppPtr = nullptr;
qtWidgetPtr = nullptr;
}
//----------------------------------------------------------
ofAppQtWindow::~ofAppQtWindow() {
// ofLogVerbose() << "ofAppQtWindow Dtor";
}
void ofAppQtWindow::close()
{
ofLogVerbose() << "close";
qtWidgetPtr->makeCurrent();
events().disable();
bWindowNeedsShowing = true;
}
void ofAppQtWindow::createQtApp()
{
int argc = 1;
char *argv = "openframeworks";
char **vptr = &argv;
qtAppPtr = new QApplication(argc, vptr);
hasQtApp = true;
}
void ofAppQtWindow::setQtAppPointer(QApplication * qtApp)
{
qtAppPtr = qtApp;
hasQtApp = true;
}
void ofAppQtWindow::setIsWindow(bool value)
{
bIsWindow = value;
if (qtWidgetPtr == 0 || qtWidgetPtr == nullptr) return;
qtWidgetPtr->setAttribute(Qt::WA_AlwaysStackOnTop, value); // very important. fixes transparency bug
}
void ofAppQtWindow::paint()
{
// ofLogVerbose() << "ofAppQtWindow paint";
ofGetMainLoop()->setCurrentWindow(this);
if (getWindowShouldClose()) {
close();
}
else {
update();
draw();
}
}
//------------------------------------------------------------
#ifdef TARGET_OPENGLES
void ofAppGLFWWindow::setup(const ofGLESWindowSettings & settings) {
#else
void ofAppQtWindow::setup(const ofGLWindowSettings & settings) {
#endif
const ofQtGLWindowSettings * glSettings = dynamic_cast<const ofQtGLWindowSettings*>(&settings);
if (glSettings) {
setup(*glSettings);
}
else {
setup(ofQtGLWindowSettings(settings));
}
}
//------------------------------------------------------------
void ofAppQtWindow::setup(const ofQtGLWindowSettings & _settings) {
ofLogVerbose() << "setup ofAppQtWindow";
if (qtWidgetPtr) {
ofLogError() << "window already setup, probably you are mixing old and new style setup";
ofLogError() << "call only ofCreateWindow(settings) or ofSetupOpenGL(...)";
ofLogError() << "calling window->setup() after ofCreateWindow() is not necesary and won't do anything";
return;
}
settings = _settings;
//////////////////////////////////////
// setup OpenGL
//////////////////////////////////////
QSurfaceFormat format;
format.setVersion(settings.glVersionMajor, settings.glVersionMinor);
format.setProfile(QSurfaceFormat::CoreProfile);
format.setAlphaBufferSize(settings.alphaBits);
format.setDepthBufferSize(settings.depthBits);
format.setStencilBufferSize(settings.stencilBits);
format.setStereo(settings.stereo);
format.setSamples(settings.numSamples);
if (settings.doubleBuffering) {
format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
}
else {
format.setSwapBehavior(QSurfaceFormat::SingleBuffer);
}
QSurfaceFormat::setDefaultFormat(format);
//////////////////////////////////////
// create renderer
//////////////////////////////////////
if (settings.glVersionMajor >= 3) {
currentRenderer = shared_ptr<ofBaseRenderer>(new ofGLProgrammableRenderer(this));
}
else {
currentRenderer = shared_ptr<ofBaseRenderer>(new ofGLRenderer(this));
}
//////////////////////////////////////
// create Qt window
//////////////////////////////////////
qtWidgetPtr = new QtGLWidget(*this, parentWidget);
setIsWindow(bIsWindow);
qtWidgetPtr->resize(settings.getWidth(), settings.getHeight());
// qtWidgetPtr->setFormat(format);
qtWidgetPtr->setWindowTitle(settings.title);
// currentW = qtWidgetPtr->size().width();
// currentH = qtWidgetPtr->size().height();
windowW = settings.getWidth();
windowH = settings.getHeight();
bWindowNeedsShowing = settings.visible;
// qtWidgetPtr->setAlphabits(settings.alphaBits);
// qtWidgetPtr->setNumSamples(settings.numSamples);
qtWidgetPtr->makeCurrent();
qtWidgetPtr->show();
// int framebufferW, framebufferH;
// glfwGetFramebufferSize(qtWidgetPtr, &framebufferW, &framebufferH);
//this lets us detect if the window is running in a retina mode
//if (framebufferW != windowW) {
// pixelScreenCoordScale = framebufferW / windowW;
// auto position = getWindowPosition();
// setWindowShape(windowW, windowH);
// setWindowPosition(position.x, position.y);
//}
#ifndef TARGET_OPENGLES
static bool inited = false;
if (!inited) {
glewExperimental = GL_TRUE;
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
ofLogError("ofAppRunner") << "couldn't init GLEW: " << glewGetErrorString(err);
return;
}
inited = true;
}
#endif
ofLogVerbose() << "GL Version:" << glGetString(GL_VERSION);
//////////////////////////////////////
// setup renderer
//////////////////////////////////////
if (currentRenderer->getType() == ofGLProgrammableRenderer::TYPE) {
#ifndef TARGET_OPENGLES
static_cast<ofGLProgrammableRenderer*>(currentRenderer.get())->setup(settings.glVersionMajor, settings.glVersionMinor);
#else
static_cast<ofGLProgrammableRenderer*>(currentRenderer.get())->setup(settings.glesVersion, 0);
#endif
}
else {
static_cast<ofGLRenderer*>(currentRenderer.get())->setup();
}
//events().notifySetup();
//////////////////////////////////////
// notes
//////////////////////////////////////
// this call goes to an endless loop
// which causes no OF calls
// qtAppPtr->exec();
// we will use
// qtAppPtr->processEvents();
// so that we can call qt inside the OF loop
bSetupSucceded = true;
}
//------------------------------------------------------------
void ofAppQtWindow::update() {
// ofLogVerbose() << "update ofAppQtWindow";
qtWidgetPtr->makeCurrent();
events().notifyUpdate();
//////////////////////////////////////
// process Qt events
//////////////////////////////////////
qtWidgetPtr->makeCurrent();
qtWidgetPtr->update();
//////////////////////////////////////
//show the window right before the first draw call.
if (bWindowNeedsShowing && qtWidgetPtr) {
// GLFW update was here
bWindowNeedsShowing = false;
if (settings.windowMode == OF_FULLSCREEN) {
setFullscreen(true);
}
}
}
//------------------------------------------------------------
void ofAppQtWindow::draw() {
// ofLogVerbose() << "draw ofAppQtWindow";
currentRenderer->startRender();
if (bEnableSetupScreen) currentRenderer->setupScreen();
events().notifyDraw();
#ifdef TARGET_WIN32
if (currentRenderer->getBackgroundAuto() == false) {
// on a PC resizing a window with this method of accumulation (essentially single buffering)
// is BAD, so we clear on resize events.
if (nFramesSinceWindowResized < 3) {
currentRenderer->clear();
}
else {
if ((events().getFrameNum() < 3 || nFramesSinceWindowResized < 3) && settings.doubleBuffering) {
// needed if we want events from Of to Qt
// currently crashes on closing window
// it slows down framerate quite a lot!
if (hasQtApp) {
qtAppPtr->processEvents();
}
}
else {
glFlush();
}
}
}
else {
if (settings.doubleBuffering) {
// needed if we want events from Of to Qt
// currently crashes on closing window
// it slows down framerate quite a lot!
if (hasQtApp) {
qtAppPtr->processEvents();
}
}
else {
glFlush();
}
}
#else
if (currentRenderer->getBackgroundAuto() == false) {
// in accum mode resizing a window is BAD, so we clear on resize events.
if (nFramesSinceWindowResized < 3) {
currentRenderer->clear();
}
}
if (settings.doubleBuffering) {
glfwSwapBuffers(windowP);
}
else {
glFlush();
}
#endif
currentRenderer->finishRender();
nFramesSinceWindowResized++;
}
//------------------------------------------------------------
ofCoreEvents & ofAppQtWindow::events() {
return coreEvents;
}
//------------------------------------------------------------
shared_ptr<ofBaseRenderer> & ofAppQtWindow::renderer() {
return currentRenderer;
}
QWidget * ofAppQtWindow::getQOpenGLWidget()
{
return qtWidgetPtr;
}
//------------------------------------------------------------
void ofAppQtWindow::setAppPtr(shared_ptr<ofBaseApp> appPtr){
ofAppPtr = appPtr;
}
//------------------------------------------------------------
void ofAppQtWindow::setStatusMessage(string s) {
}
//------------------------------------------------------------
void ofAppQtWindow::exitApp() {
ofLog(OF_LOG_VERBOSE, "QT OF app is being terminated!");
OF_EXIT_APP(0);
}
////------------------------------------------------------------
//float ofAppQtWindow::getFrameRate() {
// return qtWidgetPtr->getGlFrameRate();
//}
//------------------------------------------------------------
void ofAppQtWindow::setWindowTitle(string title) {
settings.title = title;
qtWidgetPtr->setWindowTitle(title);
}
//------------------------------------------------------------
glm::vec2 ofAppQtWindow::getWindowSize() {
int width = qtWidgetPtr->width();
int height = qtWidgetPtr->height();
return glm::vec2(width, height);
}
//------------------------------------------------------------
glm::vec2 ofAppQtWindow::getWindowPosition() {
int x = qtWidgetPtr->pos().x();
int y = qtWidgetPtr->pos().y();
// cout << "getWindowPosition "<< x <<" "<< y << endl;
return glm::vec2{ x, y };
}
//------------------------------------------------------------
glm::vec2 ofAppQtWindow::getScreenSize() {
int width = qtWidgetPtr->size().width();
int height = qtWidgetPtr->size().height();
// cout << "getScreenSize " << width << " " << height << endl;
return glm::vec2{ width, height };
}
//------------------------------------------------------------
void ofAppQtWindow::setWindowPosition(int x, int y) {
// cout << "setWindowPosition " << x << " " << y << endl;
qtWidgetPtr->move(QPoint{ x, y });
}
//------------------------------------------------------------
void ofAppQtWindow::setWindowShape(int w, int h) {
if (windowMode == OF_WINDOW) {
windowW = w;
windowH = h;
}
currentW = w / pixelScreenCoordScale;
currentH = h / pixelScreenCoordScale;
#ifdef TARGET_OSX
auto pos = getWindowPosition();
windowP->resize(currentW, currentH);
if (pos != getWindowPosition()) {
setWindowPosition(pos.x, pos.y);
}
#else
// cout << "setWindowShape " << currentW << " " << currentH << endl;
qtWidgetPtr->resize(currentW, currentH);
#endif
}
//------------------------------------------------------------
void ofAppQtWindow::hideCursor() {
qtWidgetPtr->unsetCursor();
}
//------------------------------------------------------------
void ofAppQtWindow::showCursor() {
showCursor();
}
//------------------------------------------------------------
int ofAppQtWindow::getWidth() {
if (orientation == OF_ORIENTATION_DEFAULT || orientation == OF_ORIENTATION_180) {
return currentW * pixelScreenCoordScale;
}
else {
return currentH * pixelScreenCoordScale;
}
}
//------------------------------------------------------------
int ofAppQtWindow::getHeight() {
if (orientation == OF_ORIENTATION_DEFAULT || orientation == OF_ORIENTATION_180) {
return currentH * pixelScreenCoordScale;
}
else {
return currentW * pixelScreenCoordScale;
}
}
//------------------------------------------------------------
ofWindowMode ofAppQtWindow::getWindowMode() {
return windowMode;
}
//------------------------------------------------------------
void ofAppQtWindow::enableSetupScreen() {
bEnableSetupScreen = true;
}
//------------------------------------------------------------
void ofAppQtWindow::disableSetupScreen() {
bEnableSetupScreen = false;
}
void ofAppQtWindow::makeCurrent()
{
// used
qtWidgetPtr->makeCurrent();
}
void ofAppQtWindow::swapBuffers()
{
//unused
// qtWidgetPtr->swapBuffers();
}
void ofAppQtWindow::startRender()
{
//unused
// renderer()->startRender();
}
void ofAppQtWindow::finishRender()
{
//unused
// renderer()->finishRender();
}
<|endoftext|> |
<commit_before>/**
* ofxAutoUpdater.cpp
*
*
* The MIT License
*
* Copyright (c) 2012 Paul Vollmer, http://www.wng.cc
*
* 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.
*
*
* @testet_oF 0.07
* @testet_plattform MacOs 10.6
* ??? Win
* ??? Linux
* @dependencies ofxXmlSettings
* @modified 2012.05.14
* @version 0.1.1e
*/
#include "ofxAutoUpdate.h"
namespace wng {
/**
* A Constructor, usually called to initialize and start the class.
*/
ofxAutoUpdate::ofxAutoUpdate(){}
/**
* init
*
* @param
*/
void ofxAutoUpdate::init(string currentVersion, string appcastSrc){
ofRegisterURLNotification(this);
ofLoadURLAsync(appcastSrc, "load");
updater.init(currentVersion, appcastSrc);
// S
updater.mode = CHECK;
}
/**
* update
*/
void ofxAutoUpdate::update(){
//cout << updater.mode << endl;
//cout << updater.message << endl;
// DEFAULT
/*if(updater.mode == 0) {
cout << "Update DEFAULT\n";
}
// CHECK
else if(updater.mode == 1){
cout << "Update CHECK\n";
}
// LATEST_RELEASE
else if(updater.mode == 2){
cout << "Update LATEST_RELEASE\n";
}
// NEW_RELEASE
else*/ if(updater.mode == NEW_RELEASE){
// We create an integer for our notification display dialog.
// this variables can be checked later.
//string tempDesc = "Latest Version: "+updater.latestVersion+"\nCurrent Version: "+updater.currentVersion;
int tempDialog = updater.userNotificationDisplay(updater.message,
"Latest Version: "+updater.latestVersion+"\nCurrent Version: "+updater.currentVersion,
"Download Now", "Cancel", "Check changes");
switch (tempDialog) {
case 0:
cout << "Default response\n";
updater.mode = DOWNLOAD;
break;
case 1:
cout << "Alternate response\n";
updater.mode = FINISHED;
break;
case 2:
cout << "Other response\n";
ofLaunchBrowser(updater.appcastPath);
updater.mode = FINISHED;
break;
case 3:
cout << "Cancel response\n";
updater.mode = FINISHED;
break;
default:
break;
}
}
// DOWNLOAD
else if(updater.mode == DOWNLOAD){
//cout << "DOWNLOAD\n";
// At the moment we create a file at the desktop.
// I think we can handle this variable as an intern variable.
//updater.download(ofFilePath::getPathForDirectory("~/Downloads/WNGtemp.zip"));
/*updater.download(updater.appcast.getEnclosureUrl(xml, 0),
ofFilePath::getPathForDirectory("~/Downloads/WNGtemp.zip"));
*/
updater.download("http://www.wrong-entertainment.com/code/ofxAppUpdater/test_80mb.zip",
ofFilePath::getPathForDirectory("~/Downloads/WNGtemp.zip"));
updater.mode = RELAUNCH;
}
// DOWNLOADING
/*else if(updater.mode == DOWNLOADING){
cout << ofGetFrameNum() << " DOWNLOADING\n";
}*/
// RELAUNCH
else if(updater.mode == RELAUNCH){
cout << "RELAUNCH\n";
// TODO----------------------------------------------------------------
}
}
/**
* urlResponse
* based on http://forum.openframeworks.cc/index.php/topic,8398.0.html
*
* An other solution: for this we use the
* applescript system events?
*/
void ofxAutoUpdate::urlResponse(ofHttpResponse & response){
// Switch different urlResponse for different updater modes.
switch (updater.mode) {
case DEFAULT:
cout << "CHECK\n";
break;
case CHECK:
if(response.status == 200){
//cout << response.request.name << endl;
//cout << response.data.getText() << endl;
xml.loadFromBuffer(response.data);
updater.checkVersion(xml);
} else {
cout << response.status << " " << response.error << endl;
updater.mode = FINISHED;
}
// Unregister URLNotification to close event.
ofUnregisterURLNotification(this);
break;
/*
case NEW_RELEASE:
cout << "RESPONSE_NEW\n";
break;*/
default:
break;
}
}
}
<commit_msg>rename userNotificationDisplay button to "Later"<commit_after>/**
* ofxAutoUpdater.cpp
*
*
* The MIT License
*
* Copyright (c) 2012 Paul Vollmer, http://www.wng.cc
*
* 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.
*
*
* @testet_oF 0.07
* @testet_plattform MacOs 10.6
* ??? Win
* ??? Linux
* @dependencies ofxXmlSettings
* @modified 2012.05.14
* @version 0.1.1e
*/
#include "ofxAutoUpdate.h"
namespace wng {
/**
* A Constructor, usually called to initialize and start the class.
*/
ofxAutoUpdate::ofxAutoUpdate(){}
/**
* init
*
* @param
*/
void ofxAutoUpdate::init(string currentVersion, string appcastSrc){
ofRegisterURLNotification(this);
ofLoadURLAsync(appcastSrc, "load");
updater.init(currentVersion, appcastSrc);
// S
updater.mode = CHECK;
}
/**
* update
*/
void ofxAutoUpdate::update(){
//cout << updater.mode << endl;
//cout << updater.message << endl;
// DEFAULT
/*if(updater.mode == 0) {
cout << "Update DEFAULT\n";
}
// CHECK
else if(updater.mode == 1){
cout << "Update CHECK\n";
}
// LATEST_RELEASE
else if(updater.mode == 2){
cout << "Update LATEST_RELEASE\n";
}
// NEW_RELEASE
else*/ if(updater.mode == NEW_RELEASE){
// We create an integer for our notification display dialog.
// this variables can be checked later.
//string tempDesc = "Latest Version: "+updater.latestVersion+"\nCurrent Version: "+updater.currentVersion;
int tempDialog = updater.userNotificationDisplay(updater.message,
"Latest Version: "+updater.latestVersion+"\nCurrent Version: "+updater.currentVersion,
"Download Now", "Later", "Check changes");
switch (tempDialog) {
case 0:
cout << "Default response\n";
updater.mode = DOWNLOAD;
break;
case 1:
cout << "Alternate response\n";
updater.mode = FINISHED;
break;
case 2:
cout << "Other response\n";
ofLaunchBrowser(updater.appcastPath);
updater.mode = FINISHED;
break;
case 3:
cout << "Cancel response\n";
updater.mode = FINISHED;
break;
default:
break;
}
}
// DOWNLOAD
else if(updater.mode == DOWNLOAD){
//cout << "DOWNLOAD\n";
// At the moment we create a file at the desktop.
// I think we can handle this variable as an intern variable.
//updater.download(ofFilePath::getPathForDirectory("~/Downloads/WNGtemp.zip"));
/*updater.download(updater.appcast.getEnclosureUrl(xml, 0),
ofFilePath::getPathForDirectory("~/Downloads/WNGtemp.zip"));
*/
updater.download("http://www.wrong-entertainment.com/code/ofxAppUpdater/test_80mb.zip",
ofFilePath::getPathForDirectory("~/Downloads/WNGtemp.zip"));
updater.mode = RELAUNCH;
}
// DOWNLOADING
/*else if(updater.mode == DOWNLOADING){
cout << ofGetFrameNum() << " DOWNLOADING\n";
}*/
// RELAUNCH
else if(updater.mode == RELAUNCH){
cout << "RELAUNCH\n";
// TODO----------------------------------------------------------------
}
}
/**
* urlResponse
* based on http://forum.openframeworks.cc/index.php/topic,8398.0.html
*
* An other solution: for this we use the
* applescript system events?
*/
void ofxAutoUpdate::urlResponse(ofHttpResponse & response){
// Switch different urlResponse for different updater modes.
switch (updater.mode) {
case DEFAULT:
cout << "CHECK\n";
break;
case CHECK:
if(response.status == 200){
//cout << response.request.name << endl;
//cout << response.data.getText() << endl;
xml.loadFromBuffer(response.data);
updater.checkVersion(xml);
} else {
cout << response.status << " " << response.error << endl;
updater.mode = FINISHED;
}
// Unregister URLNotification to close event.
ofUnregisterURLNotification(this);
break;
/*
case NEW_RELEASE:
cout << "RESPONSE_NEW\n";
break;*/
default:
break;
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SwXMLBlockListContext.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-08-14 16:31:50 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _SW_XMLBLOCKLISTCONTEXT_HXX
#include <SwXMLBlockListContext.hxx>
#endif
#ifndef _SW_XMLBLOCKIMPORT_HXX
#include <SwXMLBlockImport.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include <SwXMLTextBlocks.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;
SwXMLBlockListContext::SwXMLBlockListContext(
SwXMLBlockListImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef (rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for (sal_Int16 i=0; i < nAttrCount; i++)
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
if ( XML_NAMESPACE_BLOCKLIST == nPrefix )
{
if ( IsXMLToken ( aLocalName, XML_LIST_NAME ) )
{
rImport.getBlockList().SetName(rAttrValue);
break;
}
}
}
}
SwXMLBlockListContext::~SwXMLBlockListContext ( void )
{
}
SvXMLImportContext *SwXMLBlockListContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
if (nPrefix == XML_NAMESPACE_BLOCKLIST &&
IsXMLToken ( rLocalName, XML_BLOCK ) )
pContext = new SwXMLBlockContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else
pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
return pContext;
}
SwXMLBlockContext::SwXMLBlockContext(
SwXMLBlockListImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
static const CharClass & rCC = GetAppCharClass();
String aShort, aLong, aPackageName;
BOOL bTextOnly = FALSE;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for (sal_Int16 i=0; i < nAttrCount; i++)
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
if (XML_NAMESPACE_BLOCKLIST == nPrefix)
{
if ( IsXMLToken ( aLocalName, XML_ABBREVIATED_NAME ) )
{
aShort = rCC.upper(rAttrValue);
}
else if ( IsXMLToken ( aLocalName, XML_NAME ) )
{
aLong = rAttrValue;
}
else if ( IsXMLToken ( aLocalName, XML_PACKAGE_NAME ) )
{
aPackageName = rAttrValue;
}
else if ( IsXMLToken ( aLocalName, XML_UNFORMATTED_TEXT ) )
{
if ( IsXMLToken ( rAttrValue, XML_TRUE ) )
bTextOnly = TRUE;
}
}
}
if (!aShort.Len() || !aLong.Len() || !aPackageName.Len())
return;
rImport.getBlockList().AddName( aShort, aLong, aPackageName, bTextOnly);
}
SwXMLBlockContext::~SwXMLBlockContext ( void )
{
}
SwXMLTextBlockDocumentContext::SwXMLTextBlockDocumentContext(
SwXMLTextBlockImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}
SvXMLImportContext *SwXMLTextBlockDocumentContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
if (nPrefix == XML_NAMESPACE_OFFICE &&
IsXMLToken ( rLocalName, XML_BODY ) )
pContext = new SwXMLTextBlockBodyContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else
pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
return pContext;
}
SwXMLTextBlockDocumentContext::~SwXMLTextBlockDocumentContext ( void )
{
}
SwXMLTextBlockTextContext::SwXMLTextBlockTextContext(
SwXMLTextBlockImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}
SvXMLImportContext *SwXMLTextBlockTextContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
if (nPrefix == XML_NAMESPACE_TEXT &&
IsXMLToken ( rLocalName, XML_P ) )
pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else
pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
return pContext;
}
SwXMLTextBlockTextContext::~SwXMLTextBlockTextContext ( void )
{
}
SwXMLTextBlockBodyContext::SwXMLTextBlockBodyContext(
SwXMLTextBlockImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}
SvXMLImportContext *SwXMLTextBlockBodyContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
if (nPrefix == XML_NAMESPACE_OFFICE &&
IsXMLToken ( rLocalName, XML_TEXT ) )
pContext = new SwXMLTextBlockTextContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else if (nPrefix == XML_NAMESPACE_TEXT &&
IsXMLToken ( rLocalName, XML_P ) )
pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else
pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
return pContext;
}
SwXMLTextBlockBodyContext::~SwXMLTextBlockBodyContext ( void )
{
}
SwXMLTextBlockParContext::SwXMLTextBlockParContext(
SwXMLTextBlockImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}
void SwXMLTextBlockParContext::Characters( const ::rtl::OUString& rChars )
{
rLocalRef.m_rText.Append ( rChars.getStr());
}
SwXMLTextBlockParContext::~SwXMLTextBlockParContext ( void )
{
if (rLocalRef.bTextOnly)
rLocalRef.m_rText.AppendAscii( "\015" );
else
{
if (rLocalRef.m_rText.GetChar ( rLocalRef.m_rText.Len()) != ' ' )
rLocalRef.m_rText.AppendAscii( " " );
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.2); FILE MERGED 2006/09/01 17:51:57 kaib 1.9.2.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SwXMLBlockListContext.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-16 21:28:24 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifndef _SW_XMLBLOCKLISTCONTEXT_HXX
#include <SwXMLBlockListContext.hxx>
#endif
#ifndef _SW_XMLBLOCKIMPORT_HXX
#include <SwXMLBlockImport.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include <SwXMLTextBlocks.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;
SwXMLBlockListContext::SwXMLBlockListContext(
SwXMLBlockListImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef (rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for (sal_Int16 i=0; i < nAttrCount; i++)
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
if ( XML_NAMESPACE_BLOCKLIST == nPrefix )
{
if ( IsXMLToken ( aLocalName, XML_LIST_NAME ) )
{
rImport.getBlockList().SetName(rAttrValue);
break;
}
}
}
}
SwXMLBlockListContext::~SwXMLBlockListContext ( void )
{
}
SvXMLImportContext *SwXMLBlockListContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
if (nPrefix == XML_NAMESPACE_BLOCKLIST &&
IsXMLToken ( rLocalName, XML_BLOCK ) )
pContext = new SwXMLBlockContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else
pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
return pContext;
}
SwXMLBlockContext::SwXMLBlockContext(
SwXMLBlockListImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
static const CharClass & rCC = GetAppCharClass();
String aShort, aLong, aPackageName;
BOOL bTextOnly = FALSE;
sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;
for (sal_Int16 i=0; i < nAttrCount; i++)
{
const OUString& rAttrName = xAttrList->getNameByIndex( i );
OUString aLocalName;
sal_uInt16 nPrefix = rImport.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
const OUString& rAttrValue = xAttrList->getValueByIndex( i );
if (XML_NAMESPACE_BLOCKLIST == nPrefix)
{
if ( IsXMLToken ( aLocalName, XML_ABBREVIATED_NAME ) )
{
aShort = rCC.upper(rAttrValue);
}
else if ( IsXMLToken ( aLocalName, XML_NAME ) )
{
aLong = rAttrValue;
}
else if ( IsXMLToken ( aLocalName, XML_PACKAGE_NAME ) )
{
aPackageName = rAttrValue;
}
else if ( IsXMLToken ( aLocalName, XML_UNFORMATTED_TEXT ) )
{
if ( IsXMLToken ( rAttrValue, XML_TRUE ) )
bTextOnly = TRUE;
}
}
}
if (!aShort.Len() || !aLong.Len() || !aPackageName.Len())
return;
rImport.getBlockList().AddName( aShort, aLong, aPackageName, bTextOnly);
}
SwXMLBlockContext::~SwXMLBlockContext ( void )
{
}
SwXMLTextBlockDocumentContext::SwXMLTextBlockDocumentContext(
SwXMLTextBlockImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}
SvXMLImportContext *SwXMLTextBlockDocumentContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
if (nPrefix == XML_NAMESPACE_OFFICE &&
IsXMLToken ( rLocalName, XML_BODY ) )
pContext = new SwXMLTextBlockBodyContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else
pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
return pContext;
}
SwXMLTextBlockDocumentContext::~SwXMLTextBlockDocumentContext ( void )
{
}
SwXMLTextBlockTextContext::SwXMLTextBlockTextContext(
SwXMLTextBlockImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}
SvXMLImportContext *SwXMLTextBlockTextContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
if (nPrefix == XML_NAMESPACE_TEXT &&
IsXMLToken ( rLocalName, XML_P ) )
pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else
pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
return pContext;
}
SwXMLTextBlockTextContext::~SwXMLTextBlockTextContext ( void )
{
}
SwXMLTextBlockBodyContext::SwXMLTextBlockBodyContext(
SwXMLTextBlockImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}
SvXMLImportContext *SwXMLTextBlockBodyContext::CreateChildContext(
sal_uInt16 nPrefix,
const OUString& rLocalName,
const Reference< xml::sax::XAttributeList > & xAttrList )
{
SvXMLImportContext *pContext = 0;
if (nPrefix == XML_NAMESPACE_OFFICE &&
IsXMLToken ( rLocalName, XML_TEXT ) )
pContext = new SwXMLTextBlockTextContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else if (nPrefix == XML_NAMESPACE_TEXT &&
IsXMLToken ( rLocalName, XML_P ) )
pContext = new SwXMLTextBlockParContext (rLocalRef, nPrefix, rLocalName, xAttrList);
else
pContext = new SvXMLImportContext( rLocalRef, nPrefix, rLocalName);
return pContext;
}
SwXMLTextBlockBodyContext::~SwXMLTextBlockBodyContext ( void )
{
}
SwXMLTextBlockParContext::SwXMLTextBlockParContext(
SwXMLTextBlockImport& rImport,
sal_uInt16 nPrefix,
const OUString& rLocalName,
const com::sun::star::uno::Reference<
com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
rLocalRef(rImport),
SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}
void SwXMLTextBlockParContext::Characters( const ::rtl::OUString& rChars )
{
rLocalRef.m_rText.Append ( rChars.getStr());
}
SwXMLTextBlockParContext::~SwXMLTextBlockParContext ( void )
{
if (rLocalRef.bTextOnly)
rLocalRef.m_rText.AppendAscii( "\015" );
else
{
if (rLocalRef.m_rText.GetChar ( rLocalRef.m_rText.Len()) != ' ' )
rLocalRef.m_rText.AppendAscii( " " );
}
}
<|endoftext|> |
<commit_before>#include "mtao/opengl/Window.h"
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <imgui.h>
#include <vector>
#include <png++/png.hpp>
#include <iomanip>
#include <mtao/logging/logger.hpp>
namespace mtao {namespace opengl {
size_t Window::s_window_count = 0;
std::map<GLFWwindow*,HotkeyManager> Window::s_hotkeys;
static void error_callback(int error, const char* description)
{
std::stringstream ss;
ss << "Error: " << description << std::endl;
throw std::runtime_error(ss.str());
}
/*
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
*/
void printGLInfo() {
logging::info() << "OpenGL Version: " << glGetString(GL_VERSION);
logging::info() << "OpenGL Vendor: " << glGetString(GL_VENDOR);
logging::info() << "OpenGL Renderer: " << glGetString(GL_RENDERER);
}
Window::Window( const std::string& name, int width, int height) {
if (s_window_count++ == 0 && !glfwInit()) {
std::cerr <<" GLFWInit faillure!" << std::endl;
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
window = glfwCreateWindow(width, height, name.c_str(), NULL, NULL);
if (!window) {
glfwTerminate();
throw std::runtime_error("GLFW window creation failed!");
}
s_hotkeys[window];
m_gui.setWindow(window);
makeCurrent();
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
printGLInfo();
glfwSetMouseButtonCallback(window, ImGuiImpl::mouseButtonCallback);
glfwSetScrollCallback(window, ImGuiImpl::scrollCallback);
glfwSetKeyCallback(window, Window::keyCallback);
glfwSetCharCallback(window, ImGuiImpl::charCallback);
setErrorCallback(error_callback);
glfwSwapInterval(1);
}
Window::~Window() {
s_window_count--;
if(window) {
glfwDestroyWindow(window);
}
if(s_window_count == 0) {
glfwTerminate();
}
}
void Window::run() {
while (!glfwWindowShouldClose(window)) {
draw();
}
}
void Window::draw(bool show_gui) {
//ImGuiIO& io = ImGui::GetIO();
makeCurrent();
glfwPollEvents();
// 1. Show a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
int display_w, display_h;
glfwGetFramebufferSize(window,&display_w, &display_h);
m_gui.newFrame();
m_gui_func();
m_render_func(display_w,display_h);
if(show_gui) {
m_gui.render();
}
glfwSwapBuffers(window);
}
void Window::setScrollCallback(GLFWscrollfun f) {
makeCurrent();
glfwSetScrollCallback(window, f);
}
void Window::setKeyCallback(GLFWkeyfun f) {
makeCurrent();
glfwSetKeyCallback(window, f);
}
void Window::setErrorCallback(GLFWerrorfun f) {
makeCurrent();
glfwSetErrorCallback(f);
}
void Window::makeCurrent() {
glfwMakeContextCurrent(window);
}
HotkeyManager& Window::hotkeys() {
return s_hotkeys.at(window);
}
const HotkeyManager& Window::hotkeys() const {
return s_hotkeys.at(window);
}
void Window::keyCallback(GLFWwindow* w,int key, int scancode, int action, int mods) {
s_hotkeys.at(w).press(key,mods,action);
ImGuiImpl::keyCallback(w,key,scancode,action,mods);
}
void Window::setSize(int w, int h) {
glfwSetWindowSize(window,w,h);
}
std::array<int,2> Window::getSize() const {
std::array<int,2> size;
glfwGetWindowSize(window,&size[0],&size[1]);
return size;
}
void Window::save_frame(const std::string& filename) {
auto [w,h] = getSize();
std::vector<unsigned char> data(4*w*h);
mtao::logging::info() << "Saving frame to disk(" << filename << "): " << w << "x" << h;
//glReadBuffer(GL_FRONT);
glReadPixels(0,0,w,h,GL_RGBA,GL_UNSIGNED_BYTE, data.data());
png::image<png::rgba_pixel> image(w,h);
std::cout << "Writing to image" << std::endl;
for (png::uint_32 y = 0; y < image.get_height(); ++y)
{
for (png::uint_32 x = 0; x < image.get_width(); ++x)
{
size_t o = 4*((h-1-y) * w+x);
image[y][x] = png::rgba_pixel(
data[o+0],
data[o+1],
data[o+2],
data[o+3]
);
}
}
image.write(filename);
}
void Window::record(const std::function<bool(int)>& f, const std::string& prefix, bool show_gui) {
for(int idx = 0; f(idx); ++idx) {
draw(show_gui);
std::stringstream ss;
ss << prefix << std::setfill('0') << std::setw(6) << idx << ".png";
save_frame(ss.str());
}
}
}}
<commit_msg>allowing for code to run without a gui<commit_after>#include "mtao/opengl/Window.h"
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <imgui.h>
#include <vector>
#include <png++/png.hpp>
#include <iomanip>
#include <mtao/logging/logger.hpp>
namespace mtao {namespace opengl {
size_t Window::s_window_count = 0;
std::map<GLFWwindow*,HotkeyManager> Window::s_hotkeys;
static void error_callback(int error, const char* description)
{
std::stringstream ss;
ss << "Error: " << description << std::endl;
throw std::runtime_error(ss.str());
}
/*
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
*/
void printGLInfo() {
logging::info() << "OpenGL Version: " << glGetString(GL_VERSION);
logging::info() << "OpenGL Vendor: " << glGetString(GL_VENDOR);
logging::info() << "OpenGL Renderer: " << glGetString(GL_RENDERER);
}
Window::Window( const std::string& name, int width, int height) {
if (s_window_count++ == 0 && !glfwInit()) {
std::cerr <<" GLFWInit faillure!" << std::endl;
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
window = glfwCreateWindow(width, height, name.c_str(), NULL, NULL);
if (!window) {
glfwTerminate();
throw std::runtime_error("GLFW window creation failed!");
}
s_hotkeys[window];
m_gui.setWindow(window);
makeCurrent();
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
printGLInfo();
glfwSetMouseButtonCallback(window, ImGuiImpl::mouseButtonCallback);
glfwSetScrollCallback(window, ImGuiImpl::scrollCallback);
glfwSetKeyCallback(window, Window::keyCallback);
glfwSetCharCallback(window, ImGuiImpl::charCallback);
setErrorCallback(error_callback);
glfwSwapInterval(1);
}
Window::~Window() {
s_window_count--;
if(window) {
glfwDestroyWindow(window);
}
if(s_window_count == 0) {
glfwTerminate();
}
}
void Window::run() {
while (!glfwWindowShouldClose(window)) {
draw();
}
}
void Window::draw(bool show_gui) {
//ImGuiIO& io = ImGui::GetIO();
makeCurrent();
glfwPollEvents();
// 1. Show a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
int display_w, display_h;
glfwGetFramebufferSize(window,&display_w, &display_h);
if(m_gui_func) {
m_gui.newFrame();
m_gui_func();
}
if(m_render_func) {
m_render_func(display_w,display_h);
}
if(m_gui_func && show_gui) {
m_gui.render();
}
glfwSwapBuffers(window);
}
void Window::setScrollCallback(GLFWscrollfun f) {
makeCurrent();
glfwSetScrollCallback(window, f);
}
void Window::setKeyCallback(GLFWkeyfun f) {
makeCurrent();
glfwSetKeyCallback(window, f);
}
void Window::setErrorCallback(GLFWerrorfun f) {
makeCurrent();
glfwSetErrorCallback(f);
}
void Window::makeCurrent() {
glfwMakeContextCurrent(window);
}
HotkeyManager& Window::hotkeys() {
return s_hotkeys.at(window);
}
const HotkeyManager& Window::hotkeys() const {
return s_hotkeys.at(window);
}
void Window::keyCallback(GLFWwindow* w,int key, int scancode, int action, int mods) {
s_hotkeys.at(w).press(key,mods,action);
ImGuiImpl::keyCallback(w,key,scancode,action,mods);
}
void Window::setSize(int w, int h) {
glfwSetWindowSize(window,w,h);
}
std::array<int,2> Window::getSize() const {
std::array<int,2> size;
glfwGetWindowSize(window,&size[0],&size[1]);
return size;
}
void Window::save_frame(const std::string& filename) {
auto [w,h] = getSize();
std::vector<unsigned char> data(4*w*h);
mtao::logging::info() << "Saving frame to disk(" << filename << "): " << w << "x" << h;
//glReadBuffer(GL_FRONT);
glReadPixels(0,0,w,h,GL_RGBA,GL_UNSIGNED_BYTE, data.data());
png::image<png::rgba_pixel> image(w,h);
std::cout << "Writing to image" << std::endl;
for (png::uint_32 y = 0; y < image.get_height(); ++y)
{
for (png::uint_32 x = 0; x < image.get_width(); ++x)
{
size_t o = 4*((h-1-y) * w+x);
image[y][x] = png::rgba_pixel(
data[o+0],
data[o+1],
data[o+2],
data[o+3]
);
}
}
image.write(filename);
}
void Window::record(const std::function<bool(int)>& f, const std::string& prefix, bool show_gui) {
for(int idx = 0; f(idx); ++idx) {
draw(show_gui);
std::stringstream ss;
ss << prefix << std::setfill('0') << std::setw(6) << idx << ".png";
save_frame(ss.str());
}
}
}}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/GLExtensions>
#include <osg/Texture2D>
#include <osg/State>
#include <osg/GLU>
using namespace osg;
Texture2D::Texture2D():
_textureWidth(0),
_textureHeight(0),
_numMipmapLevels(0)
{
setUseHardwareMipMapGeneration(true);
}
Texture2D::Texture2D(Image* image):
_textureWidth(0),
_textureHeight(0),
_numMipmapLevels(0)
{
setUseHardwareMipMapGeneration(true);
setImage(image);
}
Texture2D::Texture2D(const Texture2D& text,const CopyOp& copyop):
Texture(text,copyop),
_image(copyop(text._image.get())),
_textureWidth(text._textureWidth),
_textureHeight(text._textureHeight),
_numMipmapLevels(text._numMipmapLevels),
_subloadCallback(text._subloadCallback)
{
}
Texture2D::~Texture2D()
{
}
int Texture2D::compare(const StateAttribute& sa) const
{
// check the types are equal and then create the rhs variable
// used by the COMPARE_StateAttribute_Paramter macro's below.
COMPARE_StateAttribute_Types(Texture2D,sa)
if (_image!=rhs._image) // smart pointer comparison.
{
if (_image.valid())
{
if (rhs._image.valid())
{
int result = _image->compare(*rhs._image);
if (result!=0) return result;
}
else
{
return 1; // valid lhs._image is greater than null.
}
}
else if (rhs._image.valid())
{
return -1; // valid rhs._image is greater than null.
}
}
int result = compareTexture(rhs);
if (result!=0) return result;
// compare each paramter in turn against the rhs.
#if 1
COMPARE_StateAttribute_Parameter(_textureWidth)
COMPARE_StateAttribute_Parameter(_textureHeight)
#endif
COMPARE_StateAttribute_Parameter(_subloadCallback)
return 0; // passed all the above comparison macro's, must be equal.
}
void Texture2D::setImage(Image* image)
{
_image = image;
_modifiedTag.setAllElementsTo(0);
}
void Texture2D::apply(State& state) const
{
//state.setReportGLErrors(true);
// get the contextID (user defined ID of 0 upwards) for the
// current OpenGL context.
const unsigned int contextID = state.getContextID();
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject != 0)
{
textureObject->bind();
if (getTextureParameterDirty(state.getContextID()))
applyTexParameters(GL_TEXTURE_2D,state);
if (_subloadCallback.valid())
{
_subloadCallback->subload(*this,state);
}
else if (_image.valid() && getModifiedTag(contextID) != _image->getModifiedTag())
{
applyTexImage2D_subload(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _internalFormat, _numMipmapLevels);
// update the modified tag to show that it is upto date.
getModifiedTag(contextID) = _image->getModifiedTag();
}
}
else if (_subloadCallback.valid())
{
_textureObjectBuffer[contextID] = textureObject = generateTextureObject(contextID,GL_TEXTURE_2D);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
_subloadCallback->load(*this,state);
textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
// in theory the following line is redundent, but in practice
// have found that the first frame drawn doesn't apply the textures
// unless a second bind is called?!!
// perhaps it is the first glBind which is not required...
//glBindTexture( GL_TEXTURE_2D, handle );
}
else if (_image.valid() && _image->data())
{
// compute the internal texture format, this set the _internalFormat to an appropriate value.
computeInternalFormat();
// compute the dimensions of the texture.
computeRequiredTextureDimensions(state,*_image,_textureWidth, _textureHeight, _numMipmapLevels);
_textureObjectBuffer[contextID] = textureObject = generateTextureObject(
contextID,GL_TEXTURE_2D,_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
if (textureObject->isAllocated())
{
//std::cout<<"Reusing texture object"<<std::endl;
applyTexImage2D_subload(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _internalFormat, _numMipmapLevels);
}
else
{
//std::cout<<"Creating new texture object"<<std::endl;
applyTexImage2D_load(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _numMipmapLevels);
textureObject->setAllocated(true);
}
// update the modified tag to show that it is upto date.
getModifiedTag(contextID) = _image->getModifiedTag();
if (_unrefImageDataAfterApply && areAllTextureObjectsLoaded() && _image->getDataVariance()==STATIC)
{
Texture2D* non_const_this = const_cast<Texture2D*>(this);
non_const_this->_image = 0;
}
// in theory the following line is redundent, but in practice
// have found that the first frame drawn doesn't apply the textures
// unless a second bind is called?!!
// perhaps it is the first glBind which is not required...
//glBindTexture( GL_TEXTURE_2D, handle );
}
else
{
glBindTexture( GL_TEXTURE_2D, 0 );
}
}
void Texture2D::computeInternalFormat() const
{
if (_image.valid()) computeInternalFormatWithImage(*_image);
}
void Texture2D::copyTexImage2D(State& state, int x, int y, int width, int height )
{
const unsigned int contextID = state.getContextID();
if (_internalFormat==0) _internalFormat=GL_RGBA;
// get the globj for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
if (width==(int)_textureWidth && height==(int)_textureHeight)
{
// we have a valid texture object which is the right size
// so lets play clever and use copyTexSubImage2D instead.
// this allows use to reuse the texture object and avoid
// expensive memory allocations.
copyTexSubImage2D(state,0 ,0, x, y, width, height);
return;
}
// the relevent texture object is not of the right size so
// needs to been deleted
// remove previously bound textures.
dirtyTextureObject();
// note, dirtyTextureObject() dirties all the texture objects for
// this texture, is this right? Perhaps we should dirty just the
// one for this context. Note sure yet will leave till later.
// RO July 2001.
}
// remove any previously assigned images as these are nolonger valid.
_image = NULL;
// switch off mip-mapping.
_min_filter = LINEAR;
_mag_filter = LINEAR;
_textureObjectBuffer[contextID] = textureObject = generateTextureObject(contextID,GL_TEXTURE_2D);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
glCopyTexImage2D( GL_TEXTURE_2D, 0, _internalFormat, x, y, width, height, 0 );
_textureWidth = width;
_textureHeight = height;
_numMipmapLevels = 1;
textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
// inform state that this texture is the current one bound.
state.haveAppliedAttribute(this);
}
void Texture2D::copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height )
{
const unsigned int contextID = state.getContextID();
if (_internalFormat==0) _internalFormat=GL_RGBA;
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
// we have a valid image
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
glCopyTexSubImage2D( GL_TEXTURE_2D, 0, xoffset,yoffset, x, y, width, height);
/* Redundant, delete later */
//glBindTexture( GL_TEXTURE_2D, handle );
// inform state that this texture is the current one bound.
state.haveAppliedAttribute(this);
}
else
{
// no texture object already exsits for this context so need to
// create it upfront - simply call copyTexImage2D.
copyTexImage2D(state,x,y,width,height);
}
}
<commit_msg>Added support for hardware generated mipmaps into Textre2D::copy*() methods.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/GLExtensions>
#include <osg/Texture2D>
#include <osg/State>
#include <osg/Notify>
#include <osg/GLU>
using namespace osg;
Texture2D::Texture2D():
_textureWidth(0),
_textureHeight(0),
_numMipmapLevels(0)
{
setUseHardwareMipMapGeneration(true);
}
Texture2D::Texture2D(Image* image):
_textureWidth(0),
_textureHeight(0),
_numMipmapLevels(0)
{
setUseHardwareMipMapGeneration(true);
setImage(image);
}
Texture2D::Texture2D(const Texture2D& text,const CopyOp& copyop):
Texture(text,copyop),
_image(copyop(text._image.get())),
_textureWidth(text._textureWidth),
_textureHeight(text._textureHeight),
_numMipmapLevels(text._numMipmapLevels),
_subloadCallback(text._subloadCallback)
{
}
Texture2D::~Texture2D()
{
}
int Texture2D::compare(const StateAttribute& sa) const
{
// check the types are equal and then create the rhs variable
// used by the COMPARE_StateAttribute_Paramter macro's below.
COMPARE_StateAttribute_Types(Texture2D,sa)
if (_image!=rhs._image) // smart pointer comparison.
{
if (_image.valid())
{
if (rhs._image.valid())
{
int result = _image->compare(*rhs._image);
if (result!=0) return result;
}
else
{
return 1; // valid lhs._image is greater than null.
}
}
else if (rhs._image.valid())
{
return -1; // valid rhs._image is greater than null.
}
}
int result = compareTexture(rhs);
if (result!=0) return result;
// compare each paramter in turn against the rhs.
#if 1
COMPARE_StateAttribute_Parameter(_textureWidth)
COMPARE_StateAttribute_Parameter(_textureHeight)
#endif
COMPARE_StateAttribute_Parameter(_subloadCallback)
return 0; // passed all the above comparison macro's, must be equal.
}
void Texture2D::setImage(Image* image)
{
_image = image;
_modifiedTag.setAllElementsTo(0);
}
void Texture2D::apply(State& state) const
{
//state.setReportGLErrors(true);
// get the contextID (user defined ID of 0 upwards) for the
// current OpenGL context.
const unsigned int contextID = state.getContextID();
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject != 0)
{
textureObject->bind();
if (getTextureParameterDirty(state.getContextID()))
applyTexParameters(GL_TEXTURE_2D,state);
if (_subloadCallback.valid())
{
_subloadCallback->subload(*this,state);
}
else if (_image.valid() && getModifiedTag(contextID) != _image->getModifiedTag())
{
applyTexImage2D_subload(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _internalFormat, _numMipmapLevels);
// update the modified tag to show that it is upto date.
getModifiedTag(contextID) = _image->getModifiedTag();
}
}
else if (_subloadCallback.valid())
{
_textureObjectBuffer[contextID] = textureObject = generateTextureObject(contextID,GL_TEXTURE_2D);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
_subloadCallback->load(*this,state);
textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
// in theory the following line is redundent, but in practice
// have found that the first frame drawn doesn't apply the textures
// unless a second bind is called?!!
// perhaps it is the first glBind which is not required...
//glBindTexture( GL_TEXTURE_2D, handle );
}
else if (_image.valid() && _image->data())
{
// compute the internal texture format, this set the _internalFormat to an appropriate value.
computeInternalFormat();
// compute the dimensions of the texture.
computeRequiredTextureDimensions(state,*_image,_textureWidth, _textureHeight, _numMipmapLevels);
_textureObjectBuffer[contextID] = textureObject = generateTextureObject(
contextID,GL_TEXTURE_2D,_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
if (textureObject->isAllocated())
{
//std::cout<<"Reusing texture object"<<std::endl;
applyTexImage2D_subload(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _internalFormat, _numMipmapLevels);
}
else
{
//std::cout<<"Creating new texture object"<<std::endl;
applyTexImage2D_load(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _numMipmapLevels);
textureObject->setAllocated(true);
}
// update the modified tag to show that it is upto date.
getModifiedTag(contextID) = _image->getModifiedTag();
if (_unrefImageDataAfterApply && areAllTextureObjectsLoaded() && _image->getDataVariance()==STATIC)
{
Texture2D* non_const_this = const_cast<Texture2D*>(this);
non_const_this->_image = 0;
}
// in theory the following line is redundent, but in practice
// have found that the first frame drawn doesn't apply the textures
// unless a second bind is called?!!
// perhaps it is the first glBind which is not required...
//glBindTexture( GL_TEXTURE_2D, handle );
}
else
{
glBindTexture( GL_TEXTURE_2D, 0 );
}
}
void Texture2D::computeInternalFormat() const
{
if (_image.valid()) computeInternalFormatWithImage(*_image);
}
void Texture2D::copyTexImage2D(State& state, int x, int y, int width, int height )
{
const unsigned int contextID = state.getContextID();
if (_internalFormat==0) _internalFormat=GL_RGBA;
// get the globj for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
if (width==(int)_textureWidth && height==(int)_textureHeight)
{
// we have a valid texture object which is the right size
// so lets play clever and use copyTexSubImage2D instead.
// this allows use to reuse the texture object and avoid
// expensive memory allocations.
copyTexSubImage2D(state,0 ,0, x, y, width, height);
return;
}
// the relevent texture object is not of the right size so
// needs to been deleted
// remove previously bound textures.
dirtyTextureObject();
// note, dirtyTextureObject() dirties all the texture objects for
// this texture, is this right? Perhaps we should dirty just the
// one for this context. Note sure yet will leave till later.
// RO July 2001.
}
// remove any previously assigned images as these are nolonger valid.
_image = NULL;
// switch off mip-mapping.
//
_textureObjectBuffer[contextID] = textureObject = generateTextureObject(contextID,GL_TEXTURE_2D);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
bool needHardwareMipMap = (_min_filter != LINEAR && _min_filter != NEAREST);
bool hardwareMipMapOn = false;
if (needHardwareMipMap)
{
const Extensions* extensions = getExtensions(contextID,true);
bool generateMipMapSupported = extensions->isGenerateMipMapSupported();
hardwareMipMapOn = _useHardwareMipMapGeneration && generateMipMapSupported;
if (!hardwareMipMapOn)
{
// have to swtich off mip mapping
notify(NOTICE)<<"Warning: Texture2D::copyTexImage2D(,,,,) switch of mip mapping as hardware support not available."<<std::endl;
_min_filter = LINEAR;
}
}
if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_TRUE);
glCopyTexImage2D( GL_TEXTURE_2D, 0, _internalFormat, x, y, width, height, 0 );
if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_FALSE);
_textureWidth = width;
_textureHeight = height;
_numMipmapLevels = 1;
textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
// inform state that this texture is the current one bound.
state.haveAppliedAttribute(this);
}
void Texture2D::copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height )
{
const unsigned int contextID = state.getContextID();
if (_internalFormat==0) _internalFormat=GL_RGBA;
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
// we have a valid image
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
bool needHardwareMipMap = (_min_filter != LINEAR && _min_filter != NEAREST);
bool hardwareMipMapOn = false;
if (needHardwareMipMap)
{
const Extensions* extensions = getExtensions(contextID,true);
bool generateMipMapSupported = extensions->isGenerateMipMapSupported();
hardwareMipMapOn = _useHardwareMipMapGeneration && generateMipMapSupported;
if (!hardwareMipMapOn)
{
// have to swtich off mip mapping
notify(NOTICE)<<"Warning: Texture2D::copyTexImage2D(,,,,) switch of mip mapping as hardware support not available."<<std::endl;
_min_filter = LINEAR;
}
}
if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_TRUE);
glCopyTexSubImage2D( GL_TEXTURE_2D, 0, xoffset, yoffset, x, y, width, height);
if (hardwareMipMapOn) glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_FALSE);
// inform state that this texture is the current one bound.
state.haveAppliedAttribute(this);
}
else
{
// no texture object already exsits for this context so need to
// create it upfront - simply call copyTexImage2D.
copyTexImage2D(state,x,y,width,height);
}
}
<|endoftext|> |
<commit_before>/*
Title: Multi-Threaded Garbage Collector
Copyright (c) 2010-12 David C. J. Matthews
Based on the original garbage collector code
Copyright 2000-2008
Cambridge University Technical Services Limited
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "run_time.h"
#include "machine_dep.h"
#include "diagnostics.h"
#include "processes.h"
#include "timing.h"
#include "gc.h"
#include "scanaddrs.h"
#include "check_objects.h"
#include "osmem.h"
#include "bitmap.h"
#include "rts_module.h"
#include "memmgr.h"
#include "gctaskfarm.h"
#include "mpoly.h"
#include "statistics.h"
#include "profiling.h"
#include "heapsizing.h"
static GCTaskFarm gTaskFarm; // Global task farm.
GCTaskFarm *gpTaskFarm = &gTaskFarm;
// If the GC converts a weak ref from SOME to NONE it sets this ref. It can be
// cleared by the signal handler thread. There's no need for a lock since it
// is only set during GC and only cleared when not GCing.
bool convertedWeak = false;
/*
How the garbage collector works.
The GC has two phases. The minor (quick) GC is a copying collector that
copies data from the allocation area into the mutable and immutable area.
The major collector is started when either the mutable or the immutable
area is full. The major collector uses a mark/sweep scheme.
The GC has three phases:
1. Mark phase.
Working from the roots; which are the the permanent mutable segments and
the RTS roots (e.g. thread stacks), mark all reachable cells.
Marking involves setting bits in the bitmap for reachable words.
2. Compact phase.
Marked objects are copied to try to compact, upwards, the heap segments. When
an object is moved the length word of the object in the old location is set as
a tombstone that points to its new location. In particular this means that we
cannot reuse the space where an object previously was during the compaction phase.
Immutable objects are moved into immutable segments. When an object is moved
to a new location the bits are set in the bitmap as though the object had been
marked at that location.
3. Update phase.
The roots and objects marked during the first two phases are scanned and any
addresses for moved objects are updated. The lowest address used in the area
then becomes the base of the area for future allocations.
There is a sharing phase which may be performed before the mark phase. This
merges immutable cells with the same contents with the aim of reducing the
size of the live data. It is expensive so is not performed by default.
Updated DCJM 12/06/12
*/
static bool doGC(const POLYUNSIGNED wordsRequiredToAllocate)
{
gHeapSizeParameters.RecordAtStartOfMajorGC();
gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeStart);
globalStats.incCount(PSC_GC_FULLGC);
// Remove any empty spaces. There will not normally be any except
// if we have triggered a full GC as a result of detecting paging in the
// minor GC but in that case we want to try to stop the system writing
// out areas that are now empty.
gMem.RemoveEmptyLocals();
if (debugOptions & DEBUG_GC)
Log("GC: Full GC, %lu words required %" PRI_SIZET " spaces\n", wordsRequiredToAllocate, gMem.lSpaces.size());
if (debugOptions & DEBUG_HEAPSIZE)
gMem.ReportHeapSizes("Full GC (before)");
// Data sharing pass.
if (true || gHeapSizeParameters.PerformSharingPass())
GCSharingPhase();
/*
* There is a really weird bug somewhere. An extra bit may be set in the bitmap during
* the mark phase. It seems to be related to heavy swapping activity. Duplicating the
* bitmap causes it to occur only in one copy and write-protecting the bitmap apart from
* when it is actually being updated does not result in a seg-fault. So far I've only
* seen it on 64-bit Linux but it may be responsible for other crashes. The work-around
* is to check the number of bits set in the bitmap and repeat the mark phase if it does
* not match.
*/
for (unsigned p = 3; p > 0; p--)
{
for(std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
ASSERT (lSpace->top >= lSpace->upperAllocPtr);
ASSERT (lSpace->upperAllocPtr >= lSpace->lowerAllocPtr);
ASSERT (lSpace->lowerAllocPtr >= lSpace->bottom);
// Set upper and lower limits of weak refs.
lSpace->highestWeak = lSpace->bottom;
lSpace->lowestWeak = lSpace->top;
lSpace->fullGCLowerLimit = lSpace->top;
// Put dummy objects in the unused space. This allows
// us to scan over the whole of the space.
gMem.FillUnusedSpace(lSpace->lowerAllocPtr,
lSpace->upperAllocPtr-lSpace->lowerAllocPtr);
}
// Set limits of weak refs.
for (std::vector<PermanentMemSpace*>::iterator i = gMem.pSpaces.begin(); i < gMem.pSpaces.end(); i++)
{
PermanentMemSpace *pSpace = *i;
pSpace->highestWeak = pSpace->bottom;
pSpace->lowestWeak = pSpace->top;
}
/* Mark phase */
GCMarkPhase();
uintptr_t bitCount = 0, markCount = 0;
for (std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
markCount += lSpace->i_marked + lSpace->m_marked;
bitCount += lSpace->bitmap.CountSetBits(lSpace->spaceSize());
}
if (markCount == bitCount)
break;
else
{
// Report an error. If this happens again we crash.
Log("GC: Count error mark count %lu, bitCount %lu\n", markCount, bitCount);
if (p == 1)
{
ASSERT(markCount == bitCount);
}
}
}
for(std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
// Reset the allocation pointers. They will be set to the
// limits of the retained data.
#ifdef POLYML32IN64
lSpace->lowerAllocPtr = lSpace->bottom+1; // Must be odd-word aligned
lSpace->lowerAllocPtr[-1] = PolyWord::FromUnsigned(0);
#else
lSpace->lowerAllocPtr = lSpace->bottom;
#endif
lSpace->upperAllocPtr = lSpace->top;
}
if (debugOptions & DEBUG_GC) Log("GC: Check weak refs\n");
/* Detect unreferenced streams, windows etc. */
GCheckWeakRefs();
// Check that the heap is not overfull. We make sure the marked
// mutable and immutable data is no more than 90% of the
// corresponding areas. This is a very coarse adjustment.
{
uintptr_t iMarked = 0, mMarked = 0;
uintptr_t iSpace = 0, mSpace = 0;
for (std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
iMarked += lSpace->i_marked;
mMarked += lSpace->m_marked;
if (! lSpace->allocationSpace)
{
if (lSpace->isMutable)
mSpace += lSpace->spaceSize();
else
iSpace += lSpace->spaceSize();
}
}
// Add space if necessary and possible.
while (iMarked > iSpace - iSpace/10 && gHeapSizeParameters.AddSpaceBeforeCopyPhase(false) != 0)
iSpace += gMem.DefaultSpaceSize();
while (mMarked > mSpace - mSpace/10 && gHeapSizeParameters.AddSpaceBeforeCopyPhase(true) != 0)
mSpace += gMem.DefaultSpaceSize();
}
/* Compact phase */
GCCopyPhase();
gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeIntermediate, "Copy");
// Update Phase.
if (debugOptions & DEBUG_GC) Log("GC: Update\n");
GCUpdatePhase();
gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeIntermediate, "Update");
{
uintptr_t iUpdated = 0, mUpdated = 0, iMarked = 0, mMarked = 0;
for(std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
iMarked += lSpace->i_marked;
mMarked += lSpace->m_marked;
if (lSpace->isMutable)
mUpdated += lSpace->updated;
else
iUpdated += lSpace->updated;
}
ASSERT(iUpdated+mUpdated == iMarked+mMarked);
}
// Delete empty spaces.
gMem.RemoveEmptyLocals();
if (debugOptions & DEBUG_GC_ENHANCED)
{
for(std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
Log("GC: %s space %p %" PRI_SIZET " free in %" PRI_SIZET " words %2.1f%% full\n", lSpace->spaceTypeString(),
lSpace, lSpace->freeSpace(), lSpace->spaceSize(),
((float)lSpace->allocatedSpace()) * 100 / (float)lSpace->spaceSize());
}
}
// Compute values for statistics
globalStats.setSize(PSS_AFTER_LAST_GC, 0);
globalStats.setSize(PSS_AFTER_LAST_FULLGC, 0);
globalStats.setSize(PSS_ALLOCATION, 0);
globalStats.setSize(PSS_ALLOCATION_FREE, 0);
for (std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *space = *i;
uintptr_t free = space->freeSpace();
globalStats.incSize(PSS_AFTER_LAST_GC, free*sizeof(PolyWord));
globalStats.incSize(PSS_AFTER_LAST_FULLGC, free*sizeof(PolyWord));
if (space->allocationSpace)
{
if (space->allocatedSpace() > space->freeSpace()) // It's more than half full
gMem.ConvertAllocationSpaceToLocal(space);
else
{
globalStats.incSize(PSS_ALLOCATION, free*sizeof(PolyWord));
globalStats.incSize(PSS_ALLOCATION_FREE, free*sizeof(PolyWord));
}
}
#ifdef FILL_UNUSED_MEMORY
memset(space->bottom, 0xaa, (char*)space->upperAllocPtr - (char*)space->bottom);
#endif
if (debugOptions & DEBUG_GC_ENHANCED)
Log("GC: %s space %p %" PRI_SIZET " free in %" PRI_SIZET " words %2.1f%% full\n", space->spaceTypeString(),
space, space->freeSpace(), space->spaceSize(),
((float)space->allocatedSpace()) * 100 / (float)space->spaceSize());
}
// End of garbage collection
gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeEnd);
// Now we've finished we can adjust the heap sizes.
gHeapSizeParameters.AdjustSizeAfterMajorGC(wordsRequiredToAllocate);
gHeapSizeParameters.resetMajorTimingData();
bool haveSpace = gMem.CheckForAllocation(wordsRequiredToAllocate);
// Invariant: the bitmaps are completely clean.
if (debugOptions & DEBUG_GC)
{
if (haveSpace)
Log("GC: Completed successfully\n");
else Log("GC: Completed with insufficient space\n");
}
if (debugOptions & DEBUG_HEAPSIZE)
gMem.ReportHeapSizes("Full GC (after)");
// if (profileMode == kProfileLiveData || profileMode == kProfileLiveMutables)
// printprofile();
CheckMemory();
return haveSpace; // Completed
}
// Create the initial heap. hsize, isize and msize are the requested heap sizes
// from the user arguments in units of kbytes.
// Fills in the defaults and attempts to allocate the heap. If the heap size
// is too large it allocates as much as it can. The default heap size is half the
// physical memory.
void CreateHeap()
{
// Create an initial allocation space.
if (gMem.CreateAllocationSpace(gMem.DefaultSpaceSize()) == 0)
Exit("Insufficient memory to allocate the heap");
// Create the task farm if required
if (userOptions.gcthreads != 1)
{
if (! gTaskFarm.Initialise(userOptions.gcthreads, 100))
Crash("Unable to initialise the GC task farm");
}
// Set up the stacks for the mark phase.
initialiseMarkerTables();
}
class FullGCRequest: public MainThreadRequest
{
public:
FullGCRequest(): MainThreadRequest(MTP_GCPHASEMARK) {}
virtual void Perform()
{
doGC (0);
}
};
class QuickGCRequest: public MainThreadRequest
{
public:
QuickGCRequest(POLYUNSIGNED words): MainThreadRequest(MTP_GCPHASEMARK), wordsRequired(words) {}
virtual void Perform()
{
result =
#ifndef DEBUG_ONLY_FULL_GC
// If DEBUG_ONLY_FULL_GC is defined then we skip the partial GC.
RunQuickGC(wordsRequired) ||
#endif
doGC (wordsRequired);
}
bool result;
POLYUNSIGNED wordsRequired;
};
// Perform a full garbage collection. This is called either from ML via the full_gc RTS call
// or from various RTS functions such as open_file to try to recover dropped file handles.
void FullGC(TaskData *taskData)
{
FullGCRequest request;
processes->MakeRootRequest(taskData, &request);
if (convertedWeak)
// Notify the signal thread to broadcast on the condition var when
// the GC is complete. We mustn't call SignalArrived within the GC
// because it locks schedLock and the main GC thread already holds schedLock.
processes->SignalArrived();
}
// This is the normal call when memory is exhausted and we need to garbage collect.
bool QuickGC(TaskData *taskData, POLYUNSIGNED wordsRequiredToAllocate)
{
QuickGCRequest request(wordsRequiredToAllocate);
processes->MakeRootRequest(taskData, &request);
if (convertedWeak)
processes->SignalArrived();
return request.result;
}
// Called in RunShareData. This is called as a root function
void FullGCForShareCommonData(void)
{
doGC(0);
}
<commit_msg>Remove debugging code that enabled sharing pass on every major GC.<commit_after>/*
Title: Multi-Threaded Garbage Collector
Copyright (c) 2010-12 David C. J. Matthews
Based on the original garbage collector code
Copyright 2000-2008
Cambridge University Technical Services Limited
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#elif defined(_WIN32)
#include "winconfig.h"
#else
#error "No configuration file"
#endif
#ifdef HAVE_ASSERT_H
#include <assert.h>
#define ASSERT(x) assert(x)
#else
#define ASSERT(x)
#endif
#include "globals.h"
#include "run_time.h"
#include "machine_dep.h"
#include "diagnostics.h"
#include "processes.h"
#include "timing.h"
#include "gc.h"
#include "scanaddrs.h"
#include "check_objects.h"
#include "osmem.h"
#include "bitmap.h"
#include "rts_module.h"
#include "memmgr.h"
#include "gctaskfarm.h"
#include "mpoly.h"
#include "statistics.h"
#include "profiling.h"
#include "heapsizing.h"
static GCTaskFarm gTaskFarm; // Global task farm.
GCTaskFarm *gpTaskFarm = &gTaskFarm;
// If the GC converts a weak ref from SOME to NONE it sets this ref. It can be
// cleared by the signal handler thread. There's no need for a lock since it
// is only set during GC and only cleared when not GCing.
bool convertedWeak = false;
/*
How the garbage collector works.
The GC has two phases. The minor (quick) GC is a copying collector that
copies data from the allocation area into the mutable and immutable area.
The major collector is started when either the mutable or the immutable
area is full. The major collector uses a mark/sweep scheme.
The GC has three phases:
1. Mark phase.
Working from the roots; which are the the permanent mutable segments and
the RTS roots (e.g. thread stacks), mark all reachable cells.
Marking involves setting bits in the bitmap for reachable words.
2. Compact phase.
Marked objects are copied to try to compact, upwards, the heap segments. When
an object is moved the length word of the object in the old location is set as
a tombstone that points to its new location. In particular this means that we
cannot reuse the space where an object previously was during the compaction phase.
Immutable objects are moved into immutable segments. When an object is moved
to a new location the bits are set in the bitmap as though the object had been
marked at that location.
3. Update phase.
The roots and objects marked during the first two phases are scanned and any
addresses for moved objects are updated. The lowest address used in the area
then becomes the base of the area for future allocations.
There is a sharing phase which may be performed before the mark phase. This
merges immutable cells with the same contents with the aim of reducing the
size of the live data. It is expensive so is not performed by default.
Updated DCJM 12/06/12
*/
static bool doGC(const POLYUNSIGNED wordsRequiredToAllocate)
{
gHeapSizeParameters.RecordAtStartOfMajorGC();
gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeStart);
globalStats.incCount(PSC_GC_FULLGC);
// Remove any empty spaces. There will not normally be any except
// if we have triggered a full GC as a result of detecting paging in the
// minor GC but in that case we want to try to stop the system writing
// out areas that are now empty.
gMem.RemoveEmptyLocals();
if (debugOptions & DEBUG_GC)
Log("GC: Full GC, %lu words required %" PRI_SIZET " spaces\n", wordsRequiredToAllocate, gMem.lSpaces.size());
if (debugOptions & DEBUG_HEAPSIZE)
gMem.ReportHeapSizes("Full GC (before)");
// Data sharing pass.
if (gHeapSizeParameters.PerformSharingPass())
GCSharingPhase();
/*
* There is a really weird bug somewhere. An extra bit may be set in the bitmap during
* the mark phase. It seems to be related to heavy swapping activity. Duplicating the
* bitmap causes it to occur only in one copy and write-protecting the bitmap apart from
* when it is actually being updated does not result in a seg-fault. So far I've only
* seen it on 64-bit Linux but it may be responsible for other crashes. The work-around
* is to check the number of bits set in the bitmap and repeat the mark phase if it does
* not match.
*/
for (unsigned p = 3; p > 0; p--)
{
for(std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
ASSERT (lSpace->top >= lSpace->upperAllocPtr);
ASSERT (lSpace->upperAllocPtr >= lSpace->lowerAllocPtr);
ASSERT (lSpace->lowerAllocPtr >= lSpace->bottom);
// Set upper and lower limits of weak refs.
lSpace->highestWeak = lSpace->bottom;
lSpace->lowestWeak = lSpace->top;
lSpace->fullGCLowerLimit = lSpace->top;
// Put dummy objects in the unused space. This allows
// us to scan over the whole of the space.
gMem.FillUnusedSpace(lSpace->lowerAllocPtr,
lSpace->upperAllocPtr-lSpace->lowerAllocPtr);
}
// Set limits of weak refs.
for (std::vector<PermanentMemSpace*>::iterator i = gMem.pSpaces.begin(); i < gMem.pSpaces.end(); i++)
{
PermanentMemSpace *pSpace = *i;
pSpace->highestWeak = pSpace->bottom;
pSpace->lowestWeak = pSpace->top;
}
/* Mark phase */
GCMarkPhase();
uintptr_t bitCount = 0, markCount = 0;
for (std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
markCount += lSpace->i_marked + lSpace->m_marked;
bitCount += lSpace->bitmap.CountSetBits(lSpace->spaceSize());
}
if (markCount == bitCount)
break;
else
{
// Report an error. If this happens again we crash.
Log("GC: Count error mark count %lu, bitCount %lu\n", markCount, bitCount);
if (p == 1)
{
ASSERT(markCount == bitCount);
}
}
}
for(std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
// Reset the allocation pointers. They will be set to the
// limits of the retained data.
#ifdef POLYML32IN64
lSpace->lowerAllocPtr = lSpace->bottom+1; // Must be odd-word aligned
lSpace->lowerAllocPtr[-1] = PolyWord::FromUnsigned(0);
#else
lSpace->lowerAllocPtr = lSpace->bottom;
#endif
lSpace->upperAllocPtr = lSpace->top;
}
if (debugOptions & DEBUG_GC) Log("GC: Check weak refs\n");
/* Detect unreferenced streams, windows etc. */
GCheckWeakRefs();
// Check that the heap is not overfull. We make sure the marked
// mutable and immutable data is no more than 90% of the
// corresponding areas. This is a very coarse adjustment.
{
uintptr_t iMarked = 0, mMarked = 0;
uintptr_t iSpace = 0, mSpace = 0;
for (std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
iMarked += lSpace->i_marked;
mMarked += lSpace->m_marked;
if (! lSpace->allocationSpace)
{
if (lSpace->isMutable)
mSpace += lSpace->spaceSize();
else
iSpace += lSpace->spaceSize();
}
}
// Add space if necessary and possible.
while (iMarked > iSpace - iSpace/10 && gHeapSizeParameters.AddSpaceBeforeCopyPhase(false) != 0)
iSpace += gMem.DefaultSpaceSize();
while (mMarked > mSpace - mSpace/10 && gHeapSizeParameters.AddSpaceBeforeCopyPhase(true) != 0)
mSpace += gMem.DefaultSpaceSize();
}
/* Compact phase */
GCCopyPhase();
gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeIntermediate, "Copy");
// Update Phase.
if (debugOptions & DEBUG_GC) Log("GC: Update\n");
GCUpdatePhase();
gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeIntermediate, "Update");
{
uintptr_t iUpdated = 0, mUpdated = 0, iMarked = 0, mMarked = 0;
for(std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
iMarked += lSpace->i_marked;
mMarked += lSpace->m_marked;
if (lSpace->isMutable)
mUpdated += lSpace->updated;
else
iUpdated += lSpace->updated;
}
ASSERT(iUpdated+mUpdated == iMarked+mMarked);
}
// Delete empty spaces.
gMem.RemoveEmptyLocals();
if (debugOptions & DEBUG_GC_ENHANCED)
{
for(std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *lSpace = *i;
Log("GC: %s space %p %" PRI_SIZET " free in %" PRI_SIZET " words %2.1f%% full\n", lSpace->spaceTypeString(),
lSpace, lSpace->freeSpace(), lSpace->spaceSize(),
((float)lSpace->allocatedSpace()) * 100 / (float)lSpace->spaceSize());
}
}
// Compute values for statistics
globalStats.setSize(PSS_AFTER_LAST_GC, 0);
globalStats.setSize(PSS_AFTER_LAST_FULLGC, 0);
globalStats.setSize(PSS_ALLOCATION, 0);
globalStats.setSize(PSS_ALLOCATION_FREE, 0);
for (std::vector<LocalMemSpace*>::iterator i = gMem.lSpaces.begin(); i < gMem.lSpaces.end(); i++)
{
LocalMemSpace *space = *i;
uintptr_t free = space->freeSpace();
globalStats.incSize(PSS_AFTER_LAST_GC, free*sizeof(PolyWord));
globalStats.incSize(PSS_AFTER_LAST_FULLGC, free*sizeof(PolyWord));
if (space->allocationSpace)
{
if (space->allocatedSpace() > space->freeSpace()) // It's more than half full
gMem.ConvertAllocationSpaceToLocal(space);
else
{
globalStats.incSize(PSS_ALLOCATION, free*sizeof(PolyWord));
globalStats.incSize(PSS_ALLOCATION_FREE, free*sizeof(PolyWord));
}
}
#ifdef FILL_UNUSED_MEMORY
memset(space->bottom, 0xaa, (char*)space->upperAllocPtr - (char*)space->bottom);
#endif
if (debugOptions & DEBUG_GC_ENHANCED)
Log("GC: %s space %p %" PRI_SIZET " free in %" PRI_SIZET " words %2.1f%% full\n", space->spaceTypeString(),
space, space->freeSpace(), space->spaceSize(),
((float)space->allocatedSpace()) * 100 / (float)space->spaceSize());
}
// End of garbage collection
gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeEnd);
// Now we've finished we can adjust the heap sizes.
gHeapSizeParameters.AdjustSizeAfterMajorGC(wordsRequiredToAllocate);
gHeapSizeParameters.resetMajorTimingData();
bool haveSpace = gMem.CheckForAllocation(wordsRequiredToAllocate);
// Invariant: the bitmaps are completely clean.
if (debugOptions & DEBUG_GC)
{
if (haveSpace)
Log("GC: Completed successfully\n");
else Log("GC: Completed with insufficient space\n");
}
if (debugOptions & DEBUG_HEAPSIZE)
gMem.ReportHeapSizes("Full GC (after)");
// if (profileMode == kProfileLiveData || profileMode == kProfileLiveMutables)
// printprofile();
CheckMemory();
return haveSpace; // Completed
}
// Create the initial heap. hsize, isize and msize are the requested heap sizes
// from the user arguments in units of kbytes.
// Fills in the defaults and attempts to allocate the heap. If the heap size
// is too large it allocates as much as it can. The default heap size is half the
// physical memory.
void CreateHeap()
{
// Create an initial allocation space.
if (gMem.CreateAllocationSpace(gMem.DefaultSpaceSize()) == 0)
Exit("Insufficient memory to allocate the heap");
// Create the task farm if required
if (userOptions.gcthreads != 1)
{
if (! gTaskFarm.Initialise(userOptions.gcthreads, 100))
Crash("Unable to initialise the GC task farm");
}
// Set up the stacks for the mark phase.
initialiseMarkerTables();
}
class FullGCRequest: public MainThreadRequest
{
public:
FullGCRequest(): MainThreadRequest(MTP_GCPHASEMARK) {}
virtual void Perform()
{
doGC (0);
}
};
class QuickGCRequest: public MainThreadRequest
{
public:
QuickGCRequest(POLYUNSIGNED words): MainThreadRequest(MTP_GCPHASEMARK), wordsRequired(words) {}
virtual void Perform()
{
result =
#ifndef DEBUG_ONLY_FULL_GC
// If DEBUG_ONLY_FULL_GC is defined then we skip the partial GC.
RunQuickGC(wordsRequired) ||
#endif
doGC (wordsRequired);
}
bool result;
POLYUNSIGNED wordsRequired;
};
// Perform a full garbage collection. This is called either from ML via the full_gc RTS call
// or from various RTS functions such as open_file to try to recover dropped file handles.
void FullGC(TaskData *taskData)
{
FullGCRequest request;
processes->MakeRootRequest(taskData, &request);
if (convertedWeak)
// Notify the signal thread to broadcast on the condition var when
// the GC is complete. We mustn't call SignalArrived within the GC
// because it locks schedLock and the main GC thread already holds schedLock.
processes->SignalArrived();
}
// This is the normal call when memory is exhausted and we need to garbage collect.
bool QuickGC(TaskData *taskData, POLYUNSIGNED wordsRequiredToAllocate)
{
QuickGCRequest request(wordsRequiredToAllocate);
processes->MakeRootRequest(taskData, &request);
if (convertedWeak)
processes->SignalArrived();
return request.result;
}
// Called in RunShareData. This is called as a root function
void FullGCForShareCommonData(void)
{
doGC(0);
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin
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 "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/tracer.hpp"
#include <new>
#include "sqlite3.h"
void raise_sqlite_error(sqlite3* db);
using namespace flusspferd;
///////////////////////////
// Classes
///////////////////////////
class sqlite3 : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
typedef boost::mpl::bool_<true> constructible;
static char const* constructor_name() { return "SQLite3"; }
static void augment_constructor(object &ctor);
static object create_prototype();
};
sqlite3(object const &obj, call_context &x);
~sqlite3();
protected:
//void trace(tracer &);
private: // JS methods
sqlite3 *db;
object cursor(string sql);
};
class sqlite3_cursor : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
typedef boost::mpl::bool_<true> constructible;
static char const* constructor_name() { return "SQLite3.Cursor"; }
};
sqlite3_cursor(object const &obj, call_context &x);
~sqlite3_cursor();
private: // JS methods
sqlite3_stmt *sth;
};
///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
return load_class<sqlite3>(container);
}
///////////////////////////
// Set version properties on constructor object
void sqlite3::class_info::augment_constructor(object &ctor)
{
// Set static properties on the constructor
ctor.define_property("version", SQLITE_VERSION_NUMBER,
object::read_only_property | object::permanent_property);
ctor.define_property("versionStr", string(SQLITE_VERSION),
object::read_only_property | object::permanent_property);
load_class<sqlite3_cursor>(ctor);
}
///////////////////////////
object sqlite3::class_info::create_prototype()
{
object proto = create_object();
return proto;
}
///////////////////////////
sqlite3::sqlite3(object const &obj, call_context &x)
: native_object_base(obj),
db(NULL)
{
if (x.arg.size() == 0)
// This syntax probably isn't the best
throw exception("Usage: new SQLite3(dsn, [options])");
string dsn = x.arg[0];
// TODO: pull arguments from 2nd/options argument
if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {
if (db)
raise_sqlite_error(db);
else
throw std::bad_alloc(); // out of memory. better way to signal this?
}
}
///////////////////////////
sqlite3::~sqlite3()
{
if (db)i = new Importer(); i.paths = ['build/default/plugins/sqlite']; i.load('sqlite')
sqlite3_close(db);
}
///////////////////////////
sqlite3_cursor::sqlite3_cursor(object const &obj, call_context &)
: native_object_base(obj)
{
}
///////////////////////////
sqlite3_cursor::~sqlite3_cursor()
{
}
// Helper function
void raise_sqlite_error(sqlite3* db)
{
std::string s = "SQLite3 Error: ";
s += sqlite3_errmsg(db);
throw exception(s);
}
<commit_msg>SQLite: move classes into an anon-namespace<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin
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 "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/native_object_base.hpp"
#include "flusspferd/string.hpp"
#include "flusspferd/tracer.hpp"
#include <new>
#include "sqlite3.h"
using namespace flusspferd;
// Put everything in an anon-namespace so typeid wont clash ever.
namespace {
void raise_sqlite_error(sqlite3* db);
///////////////////////////
// Classes
///////////////////////////
class sqlite3 : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
typedef boost::mpl::bool_<true> constructible;
static char const* constructor_name() { return "SQLite3"; }
static void augment_constructor(object &ctor);
};
sqlite3(object const &obj, call_context &x);
~sqlite3();
protected:
//void trace(tracer &);
private: // JS methods
::sqlite3 *db;
object cursor(string sql);
};
class sqlite3_cursor : public native_object_base {
public:
struct class_info : public flusspferd::class_info {
typedef boost::mpl::bool_<true> constructible;
static char const* constructor_name() { return "SQLite3.Cursor"; }
};
sqlite3_cursor(object const &obj, call_context &x);
~sqlite3_cursor();
private: // JS methods
sqlite3_stmt *sth;
};
///////////////////////////
// import hook
extern "C" value flusspferd_load(object container)
{
return load_class<sqlite3>(container);
}
///////////////////////////
// Set version properties on constructor object
void sqlite3::class_info::augment_constructor(object &ctor)
{
// Set static properties on the constructor
ctor.define_property("version", SQLITE_VERSION_NUMBER,
object::read_only_property | object::permanent_property);
ctor.define_property("versionStr", string(SQLITE_VERSION),
object::read_only_property | object::permanent_property);
load_class<sqlite3_cursor>(ctor);
}
///////////////////////////
object sqlite3::class_info::create_prototype()
{
object proto = create_object();
proto.set_property("constructor",
return proto;
}
///////////////////////////
sqlite3::sqlite3(object const &obj, call_context &x)
: native_object_base(obj),
db(NULL)
{
if (x.arg.size() == 0)
// This syntax probably isn't the best
throw exception("Usage: new SQLite3(dsn, [options])");
string dsn = x.arg[0];
// TODO: pull arguments from 2nd/options argument
if (sqlite3_open(dsn.c_str(), &db) != SQLITE_OK) {
if (db)
raise_sqlite_error(db);
else
throw std::bad_alloc(); // out of memory. better way to signal this?
}
}
///////////////////////////
sqlite3::~sqlite3()
{
if (db)
sqlite3_close(db);
}
///////////////////////////
sqlite3_cursor::sqlite3_cursor(object const &obj, call_context &)
: native_object_base(obj)
{
}
///////////////////////////
sqlite3_cursor::~sqlite3_cursor()
{
}
// Helper function
void raise_sqlite_error(::sqlite3* db)
{
std::string s = "SQLite3 Error: ";
s += sqlite3_errmsg(db);
throw exception(s);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "parquet_reader.h"
using v8::Array;
using v8::Boolean;
using v8::Context;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
Nan::Persistent<Function> ParquetReader::constructor;
ParquetReader::ParquetReader(const Nan::FunctionCallbackInfo<Value>& info) : pr_(nullptr) {
String::Utf8Value param1(info[0]->ToString());
std::string from = std::string(*param1);
pr_ = parquet::ParquetFileReader::OpenFile(from);
std::cout << "from: " << from << std::endl;
}
ParquetReader::~ParquetReader() {}
void ParquetReader::Init(Local<Object> exports) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("ParquetReader").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "info", Info);
Nan::SetPrototypeMethod(tpl, "debugPrint", DebugPrint);
Nan::SetPrototypeMethod(tpl, "readSync", ReadSync);
Nan::SetPrototypeMethod(tpl, "readline", Readline);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("ParquetReader").ToLocalChecked(), tpl->GetFunction());
}
void ParquetReader::New(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = new ParquetReader(info);
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
void ParquetReader::NewInstance(const Nan::FunctionCallbackInfo<Value>& info) {
const unsigned argc = 1;
Local<Value> argv[argc] = { info[0] };
Local<Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
void ParquetReader::DebugPrint(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::list<int> columns;
bool print_values = true;
obj->pr_->DebugPrint(std::cout, columns, print_values);
info.GetReturnValue().Set(Nan::New("Hello").ToLocalChecked());
}
void ParquetReader::Info(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::shared_ptr<parquet::FileMetaData> file_metadata = obj->pr_->metadata();
Local<Object> res = Nan::New<Object>();
std::string s(file_metadata->created_by());
res->Set(Nan::New("version").ToLocalChecked(), Nan::New<Number>(file_metadata->version()));
res->Set(Nan::New("createdBy").ToLocalChecked(), Nan::New(s.c_str()).ToLocalChecked());
res->Set(Nan::New("rowGroups").ToLocalChecked(), Nan::New<Number>(file_metadata->num_row_groups()));
res->Set(Nan::New("columns").ToLocalChecked(), Nan::New<Number>(file_metadata->num_columns()));
res->Set(Nan::New("rows").ToLocalChecked() , Nan::New<Number>(file_metadata->num_rows()));
res->Set(Nan::New<Number>(2) , Nan::New<Number>(file_metadata->num_rows()));
info.GetReturnValue().Set(res);
}
void ParquetReader::ReadSync(const Nan::FunctionCallbackInfo<Value>& info) {
int colnum;
int start;
int n = 10;
int rows_read;
int64_t values_read;
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::shared_ptr<parquet::FileMetaData> file_metadata = obj->pr_->metadata();
Local<Object> res = Nan::New<Object>();
Nan::MaybeLocal<Object> buffer = Nan::NewBuffer(10 * 4);
std::shared_ptr<parquet::RowGroupReader> row_group_reader = obj->pr_->RowGroup(0);
std::shared_ptr<parquet::ColumnReader> column_reader = row_group_reader->Column(1);
parquet::Int32Reader* int32_reader = static_cast<parquet::Int32Reader*>(column_reader.get());
int32_t* result = new int32_t[n];
rows_read = int32_reader->ReadBatch(10, nullptr, nullptr, result, &values_read);
std::cout << "rows_read: " << rows_read << std::endl;
std::cout << "values_read: " << values_read << std::endl;
std::cout << "result[9]: " << result[9] << std::endl;
if (info.Length() < 3) {
Nan::ThrowTypeError("wrong number of arguments");
return;
}
if (!info[0]->IsNumber() || !info[1]->IsNumber() || !info[2]->IsNumber()) {
Nan::ThrowTypeError("wrong argument");
return;
}
colnum = info[0]->IntegerValue();
start = info[1]->IntegerValue();
n = info[2]->IntegerValue();
std::cout << "colnum: " << colnum << std::endl;
std::cout << "start: " << start << std::endl;
std::cout << "n: " << n << std::endl;
std::cout << "sizeof(bool): " << sizeof(bool) << std::endl;
const parquet::ColumnDescriptor* descr = file_metadata->schema()->Column(2);
std::cout << "type 1: " << descr->physical_type() << std::endl;
info.GetReturnValue().Set(res);
}
void ParquetReader::Readline(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::shared_ptr<parquet::FileMetaData> file_metadata = obj->pr_->metadata();
//Local<Object> res = Nan::New<Object>();
Local<Array> res = Nan::New<Array>();
std::shared_ptr<parquet::RowGroupReader> row_group_reader = obj->pr_->RowGroup(0);
int num_columns = file_metadata->num_columns();
if (!info[0]->IsNumber() || !info[1]->IsNumber()) {
Nan::ThrowTypeError("wrong argument");
return;
}
int nskip = info[0]->IntegerValue();
int nrows = info[1]->IntegerValue();
for (int l = 0; l < nrows; l++) {
//Local<Object> row_res = Nan::New<Object>();
Local<Array> row_res = Nan::New<Array>();
res->Set(Nan::New<Number>(nskip + l), row_res);
for (int i = 0; i < num_columns; i++) {
int64_t values_read;
std::shared_ptr<parquet::ColumnReader> column_reader = row_group_reader->Column(i);
//std::cout << "i: " << i << ", type: " << column_reader->type() << std::endl;
switch (column_reader->type()) {
case parquet::Type::BOOLEAN: {
bool value;
parquet::BoolReader* reader = static_cast<parquet::BoolReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Boolean>(value));
break;
}
case parquet::Type::INT32: {
int32_t value;
parquet::Int32Reader* reader = static_cast<parquet::Int32Reader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Number>(value));
break;
}
case parquet::Type::INT64: {
int64_t value;
parquet::Int64Reader* reader = static_cast<parquet::Int64Reader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Number>(value));
break;
}
case parquet::Type::INT96: {
parquet::Int96 value;
parquet::Int96Reader* reader = static_cast<parquet::Int96Reader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::CopyBuffer((char*)value.value, 12).ToLocalChecked());
break;
}
case parquet::Type::FLOAT: {
float value;
parquet::FloatReader* reader = static_cast<parquet::FloatReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Number>(value));
break;
}
case parquet::Type::DOUBLE: {
double value;
parquet::DoubleReader* reader = static_cast<parquet::DoubleReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Number>(value));
break;
}
case parquet::Type::BYTE_ARRAY: {
parquet::ByteArray value;
parquet::ByteArrayReader* reader = static_cast<parquet::ByteArrayReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::CopyBuffer((char*)value.ptr, value.len).ToLocalChecked());
break;
}
case parquet::Type::FIXED_LEN_BYTE_ARRAY: {
parquet::FixedLenByteArray value;
parquet::FixedLenByteArrayReader* reader = static_cast<parquet::FixedLenByteArrayReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::CopyBuffer((char*)value.ptr, 1).ToLocalChecked());
break;
}
}
}
}
info.GetReturnValue().Set(res);
}
<commit_msg>reader: return a string if parquet logical type is UTF8<commit_after>#include <iostream>
#include "parquet_reader.h"
using v8::Array;
using v8::Boolean;
using v8::Context;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
Nan::Persistent<Function> ParquetReader::constructor;
ParquetReader::ParquetReader(const Nan::FunctionCallbackInfo<Value>& info) : pr_(nullptr) {
String::Utf8Value param1(info[0]->ToString());
std::string from = std::string(*param1);
pr_ = parquet::ParquetFileReader::OpenFile(from);
}
ParquetReader::~ParquetReader() {}
void ParquetReader::Init(Local<Object> exports) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("ParquetReader").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "info", Info);
Nan::SetPrototypeMethod(tpl, "debugPrint", DebugPrint);
Nan::SetPrototypeMethod(tpl, "readSync", ReadSync);
Nan::SetPrototypeMethod(tpl, "readline", Readline);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("ParquetReader").ToLocalChecked(), tpl->GetFunction());
}
void ParquetReader::New(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = new ParquetReader(info);
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
void ParquetReader::NewInstance(const Nan::FunctionCallbackInfo<Value>& info) {
const unsigned argc = 1;
Local<Value> argv[argc] = { info[0] };
Local<Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(cons->NewInstance(argc, argv));
}
void ParquetReader::DebugPrint(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::list<int> columns;
bool print_values = true;
obj->pr_->DebugPrint(std::cout, columns, print_values);
info.GetReturnValue().Set(Nan::New("Hello").ToLocalChecked());
}
void ParquetReader::Info(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::shared_ptr<parquet::FileMetaData> file_metadata = obj->pr_->metadata();
Local<Object> res = Nan::New<Object>();
std::string s(file_metadata->created_by());
res->Set(Nan::New("version").ToLocalChecked(), Nan::New<Number>(file_metadata->version()));
res->Set(Nan::New("createdBy").ToLocalChecked(), Nan::New(s.c_str()).ToLocalChecked());
res->Set(Nan::New("rowGroups").ToLocalChecked(), Nan::New<Number>(file_metadata->num_row_groups()));
res->Set(Nan::New("columns").ToLocalChecked(), Nan::New<Number>(file_metadata->num_columns()));
res->Set(Nan::New("rows").ToLocalChecked() , Nan::New<Number>(file_metadata->num_rows()));
res->Set(Nan::New<Number>(2) , Nan::New<Number>(file_metadata->num_rows()));
info.GetReturnValue().Set(res);
}
void ParquetReader::ReadSync(const Nan::FunctionCallbackInfo<Value>& info) {
int colnum;
int start;
int n = 10;
int rows_read;
int64_t values_read;
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::shared_ptr<parquet::FileMetaData> file_metadata = obj->pr_->metadata();
Local<Object> res = Nan::New<Object>();
Nan::MaybeLocal<Object> buffer = Nan::NewBuffer(10 * 4);
std::shared_ptr<parquet::RowGroupReader> row_group_reader = obj->pr_->RowGroup(0);
std::shared_ptr<parquet::ColumnReader> column_reader = row_group_reader->Column(1);
parquet::Int32Reader* int32_reader = static_cast<parquet::Int32Reader*>(column_reader.get());
int32_t* result = new int32_t[n];
rows_read = int32_reader->ReadBatch(10, nullptr, nullptr, result, &values_read);
std::cout << "rows_read: " << rows_read << std::endl;
std::cout << "values_read: " << values_read << std::endl;
std::cout << "result[9]: " << result[9] << std::endl;
if (info.Length() < 3) {
Nan::ThrowTypeError("wrong number of arguments");
return;
}
if (!info[0]->IsNumber() || !info[1]->IsNumber() || !info[2]->IsNumber()) {
Nan::ThrowTypeError("wrong argument");
return;
}
colnum = info[0]->IntegerValue();
start = info[1]->IntegerValue();
n = info[2]->IntegerValue();
std::cout << "colnum: " << colnum << std::endl;
std::cout << "start: " << start << std::endl;
std::cout << "n: " << n << std::endl;
std::cout << "sizeof(bool): " << sizeof(bool) << std::endl;
const parquet::ColumnDescriptor* descr = file_metadata->schema()->Column(2);
std::cout << "type 1: " << descr->physical_type() << std::endl;
info.GetReturnValue().Set(res);
}
void ParquetReader::Readline(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::shared_ptr<parquet::FileMetaData> file_metadata = obj->pr_->metadata();
//Local<Object> res = Nan::New<Object>();
Local<Array> res = Nan::New<Array>();
std::shared_ptr<parquet::RowGroupReader> row_group_reader = obj->pr_->RowGroup(0);
int num_columns = file_metadata->num_columns();
if (!info[0]->IsNumber() || !info[1]->IsNumber()) {
Nan::ThrowTypeError("wrong argument");
return;
}
int nskip = info[0]->IntegerValue();
int nrows = info[1]->IntegerValue();
for (int l = 0; l < nrows; l++) {
//Local<Object> row_res = Nan::New<Object>();
Local<Array> row_res = Nan::New<Array>();
res->Set(Nan::New<Number>(nskip + l), row_res);
for (int i = 0; i < num_columns; i++) {
int64_t values_read;
std::shared_ptr<parquet::ColumnReader> column_reader = row_group_reader->Column(i);
parquet::LogicalType::type logical_type = column_reader->descr()->logical_type();
//std::cout << "i: " << i << ", type: " << column_reader->type() << std::endl;
switch (column_reader->type()) {
case parquet::Type::BOOLEAN: {
bool value;
parquet::BoolReader* reader = static_cast<parquet::BoolReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Boolean>(value));
break;
}
case parquet::Type::INT32: {
int32_t value;
parquet::Int32Reader* reader = static_cast<parquet::Int32Reader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Number>(value));
break;
}
case parquet::Type::INT64: {
int64_t value;
parquet::Int64Reader* reader = static_cast<parquet::Int64Reader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Number>(value));
break;
}
case parquet::Type::INT96: {
parquet::Int96 value;
parquet::Int96Reader* reader = static_cast<parquet::Int96Reader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::CopyBuffer((char*)value.value, 12).ToLocalChecked());
break;
}
case parquet::Type::FLOAT: {
float value;
parquet::FloatReader* reader = static_cast<parquet::FloatReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Number>(value));
break;
}
case parquet::Type::DOUBLE: {
double value;
parquet::DoubleReader* reader = static_cast<parquet::DoubleReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::New<Number>(value));
break;
}
case parquet::Type::BYTE_ARRAY: {
parquet::ByteArray value;
parquet::ByteArrayReader* reader = static_cast<parquet::ByteArrayReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
if (logical_type == parquet::LogicalType::UTF8) {
row_res->Set(Nan::New<Number>(i), Nan::New((char*)value.ptr, value.len).ToLocalChecked());
} else {
row_res->Set(Nan::New<Number>(i), Nan::CopyBuffer((char*)value.ptr, value.len).ToLocalChecked());
}
break;
}
case parquet::Type::FIXED_LEN_BYTE_ARRAY: {
parquet::FixedLenByteArray value;
parquet::FixedLenByteArrayReader* reader = static_cast<parquet::FixedLenByteArrayReader*>(column_reader.get());
reader->Skip(nskip + l);
reader->ReadBatch(1, nullptr, nullptr, &value, &values_read);
row_res->Set(Nan::New<Number>(i), Nan::CopyBuffer((char*)value.ptr, 1).ToLocalChecked());
break;
}
}
}
}
info.GetReturnValue().Set(res);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include "parquet_reader.h"
using v8::Array;
using v8::Boolean;
using v8::Context;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
Nan::Persistent<Function> ParquetReader::constructor;
ParquetReader::ParquetReader(const Nan::FunctionCallbackInfo<Value>& info) : parquet_file_reader_(), column_readers_({}) {
if (!info[0]->IsString()) {
Nan::ThrowTypeError("wrong argument");
return;
}
String::Utf8Value param1(info[0]->ToString());
std::string from = std::string(*param1);
try {
parquet_file_reader_ = parquet::ParquetFileReader::OpenFile(from);
std::shared_ptr<parquet::RowGroupReader> row_group_reader= parquet_file_reader_->RowGroup(0);
int num_columns = parquet_file_reader_->metadata()->num_columns();
for (int i = 0; i < num_columns; i++) {
column_readers_.push_back(row_group_reader->Column(i));
}
} catch (const std::exception& e) {
Nan::ThrowError(Nan::New(e.what()).ToLocalChecked());
}
}
ParquetReader::~ParquetReader() {}
void ParquetReader::Init(Local<Object> exports) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("ParquetReader").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "info", Info);
Nan::SetPrototypeMethod(tpl, "read", Read);
Nan::SetPrototypeMethod(tpl, "close", Close);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("ParquetReader").ToLocalChecked(), tpl->GetFunction());
}
void ParquetReader::New(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = new ParquetReader(info);
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
void ParquetReader::NewInstance(const Nan::FunctionCallbackInfo<Value>& info) {
const int argc = 1;
Local<Value> argv[argc] = { info[0] };
Local<Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
void ParquetReader::Info(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::shared_ptr<parquet::FileMetaData> file_metadata = obj->parquet_file_reader_->metadata();
Local<Object> res = Nan::New<Object>();
std::string s(file_metadata->created_by());
res->Set(Nan::New("version").ToLocalChecked(), Nan::New<Number>(file_metadata->version()));
res->Set(Nan::New("createdBy").ToLocalChecked(), Nan::New(s.c_str()).ToLocalChecked());
res->Set(Nan::New("rowGroups").ToLocalChecked(), Nan::New<Number>(file_metadata->num_row_groups()));
res->Set(Nan::New("columns").ToLocalChecked(), Nan::New<Number>(file_metadata->num_columns()));
res->Set(Nan::New("rows").ToLocalChecked() , Nan::New<Number>(file_metadata->num_rows()));
info.GetReturnValue().Set(res);
}
void ParquetReader::Close(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
obj->parquet_file_reader_->Close();
}
template <typename T, typename U, typename V>
void reader(std::shared_ptr<parquet::ColumnReader> column_reader, int16_t maxdef, int16_t maxrep, const Nan::FunctionCallbackInfo<Value>& info) {
T reader = static_cast<T>(column_reader.get());
U value;
int64_t value_read;
int16_t definition;
int16_t repetition;
if (!reader->HasNext())
return;
reader->ReadBatch(1, &definition, &repetition, &value, &value_read);
if (maxrep == 0) {
if (definition == maxdef)
info.GetReturnValue().Set(Nan::New<V>(value));
return;
}
Local<Array> array = Nan::New<Array>(3);
array->Set(Nan::New<Number>(0), Nan::New<Number>(definition));
array->Set(Nan::New<Number>(1), Nan::New<Number>(repetition));
if (definition == maxdef)
array->Set(Nan::New<Number>(2), Nan::New<V>(value));
info.GetReturnValue().Set(array);
}
template <>
void reader<parquet::Int96Reader*, parquet::Int96, Number>(std::shared_ptr<parquet::ColumnReader> column_reader, int16_t maxdef, int16_t maxrep, const Nan::FunctionCallbackInfo<Value>& info) {
parquet::Int96Reader* reader = static_cast<parquet::Int96Reader*>(column_reader.get());
parquet::Int96 value;
int64_t value_read;
int16_t definition;
int16_t repetition;
if (!reader->HasNext())
return;
reader->ReadBatch(1, &definition, &repetition, &value, &value_read);
if (maxrep == 0) {
if (definition == maxdef)
info.GetReturnValue().Set(Nan::CopyBuffer((char*)value.value, 12).ToLocalChecked());
return;
}
Local<Array> array = Nan::New<Array>(3);
array->Set(Nan::New<Number>(0), Nan::New<Number>(definition));
array->Set(Nan::New<Number>(1), Nan::New<Number>(repetition));
if (definition == maxdef)
array->Set(Nan::New<Number>(2), Nan::CopyBuffer((char*)value.value, 12).ToLocalChecked());
info.GetReturnValue().Set(array);
}
template <>
void reader<parquet::ByteArrayReader*, parquet::ByteArray, Number>(std::shared_ptr<parquet::ColumnReader> column_reader, int16_t maxdef, int16_t maxrep, const Nan::FunctionCallbackInfo<Value>& info) {
parquet::ByteArrayReader* reader = static_cast<parquet::ByteArrayReader*>(column_reader.get());
parquet::ByteArray value;
int64_t value_read;
int16_t definition = maxdef;
int16_t repetition = maxrep;
if (!reader->HasNext())
return;
reader->ReadBatch(1, &definition, &repetition, &value, &value_read);
if (maxrep == 0) {
if (definition == maxdef)
info.GetReturnValue().Set(Nan::New((char*)value.ptr, value.len).ToLocalChecked());
return;
}
Local<Array> array = Nan::New<Array>(3);
array->Set(Nan::New<Number>(0), Nan::New<Number>(definition));
array->Set(Nan::New<Number>(1), Nan::New<Number>(repetition));
if (definition == maxdef)
array->Set(Nan::New<Number>(2), Nan::New((char*)value.ptr, value.len).ToLocalChecked());
info.GetReturnValue().Set(array);
}
template <>
void reader<parquet::FixedLenByteArrayReader*, parquet::FixedLenByteArray, Number>(std::shared_ptr<parquet::ColumnReader> column_reader, int16_t maxdef, int16_t maxrep, const Nan::FunctionCallbackInfo<Value>& info) {
parquet::FixedLenByteArrayReader* reader = static_cast<parquet::FixedLenByteArrayReader*>(column_reader.get());
parquet::FixedLenByteArray value;
int64_t value_read;
int16_t definition;
int16_t repetition;
if (!reader->HasNext())
return;
reader->ReadBatch(1, &definition, &repetition, &value, &value_read);
if (maxrep == 0) {
if (definition == maxdef)
info.GetReturnValue().Set(Nan::New((char*)value.ptr, 1).ToLocalChecked());
return;
}
Local<Array> array = Nan::New<Array>(3);
array->Set(Nan::New<Number>(0), Nan::New<Number>(definition));
array->Set(Nan::New<Number>(1), Nan::New<Number>(repetition));
if (definition == maxdef)
array->Set(Nan::New<Number>(2), Nan::New((char*)value.ptr, 1).ToLocalChecked());
info.GetReturnValue().Set(array);
}
typedef void (*reader_t)(std::shared_ptr<parquet::ColumnReader>, int16_t, int16_t, const Nan::FunctionCallbackInfo<Value>& info);
// Table of parquet readers. Keep same order as in parquet::Type
static reader_t type_readers[] = {
reader<parquet::BoolReader*, bool, Boolean>,
reader<parquet::Int32Reader*, int32_t, Number>,
reader<parquet::Int64Reader*, int64_t, Number>,
reader<parquet::Int96Reader*, parquet::Int96, Number>,
reader<parquet::FloatReader*, float, Number>,
reader<parquet::DoubleReader*, double, Number>,
reader<parquet::ByteArrayReader*, parquet::ByteArray, Number>,
reader<parquet::FixedLenByteArrayReader*, parquet::FixedLenByteArray, Number>,
};
// Read one column element.
void ParquetReader::Read(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
try {
int col = info[0]->IntegerValue();
std::shared_ptr<parquet::ColumnReader> column_reader = obj->column_readers_[col];
const parquet::ColumnDescriptor* descr = column_reader->descr();
reader_t type_reader = type_readers[column_reader->type()];
type_reader(column_reader, descr->max_definition_level(), descr->max_repetition_level(), info);
} catch (const std::exception& e) {
Nan::ThrowError(Nan::New(e.what()).ToLocalChecked());
return;
}
}
<commit_msg>reader: fix uninitialized variables when reading columns<commit_after>#include <iostream>
#include <vector>
#include "parquet_reader.h"
using v8::Array;
using v8::Boolean;
using v8::Context;
using v8::Exception;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
Nan::Persistent<Function> ParquetReader::constructor;
ParquetReader::ParquetReader(const Nan::FunctionCallbackInfo<Value>& info) : parquet_file_reader_(), column_readers_({}) {
if (!info[0]->IsString()) {
Nan::ThrowTypeError("wrong argument");
return;
}
String::Utf8Value param1(info[0]->ToString());
std::string from = std::string(*param1);
try {
parquet_file_reader_ = parquet::ParquetFileReader::OpenFile(from);
std::shared_ptr<parquet::RowGroupReader> row_group_reader= parquet_file_reader_->RowGroup(0);
int num_columns = parquet_file_reader_->metadata()->num_columns();
for (int i = 0; i < num_columns; i++) {
column_readers_.push_back(row_group_reader->Column(i));
}
} catch (const std::exception& e) {
Nan::ThrowError(Nan::New(e.what()).ToLocalChecked());
}
}
ParquetReader::~ParquetReader() {}
void ParquetReader::Init(Local<Object> exports) {
Nan::HandleScope scope;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("ParquetReader").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "info", Info);
Nan::SetPrototypeMethod(tpl, "read", Read);
Nan::SetPrototypeMethod(tpl, "close", Close);
constructor.Reset(tpl->GetFunction());
exports->Set(Nan::New("ParquetReader").ToLocalChecked(), tpl->GetFunction());
}
void ParquetReader::New(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = new ParquetReader(info);
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
void ParquetReader::NewInstance(const Nan::FunctionCallbackInfo<Value>& info) {
const int argc = 1;
Local<Value> argv[argc] = { info[0] };
Local<Function> cons = Nan::New<v8::Function>(constructor);
info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked());
}
void ParquetReader::Info(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
std::shared_ptr<parquet::FileMetaData> file_metadata = obj->parquet_file_reader_->metadata();
Local<Object> res = Nan::New<Object>();
std::string s(file_metadata->created_by());
res->Set(Nan::New("version").ToLocalChecked(), Nan::New<Number>(file_metadata->version()));
res->Set(Nan::New("createdBy").ToLocalChecked(), Nan::New(s.c_str()).ToLocalChecked());
res->Set(Nan::New("rowGroups").ToLocalChecked(), Nan::New<Number>(file_metadata->num_row_groups()));
res->Set(Nan::New("columns").ToLocalChecked(), Nan::New<Number>(file_metadata->num_columns()));
res->Set(Nan::New("rows").ToLocalChecked() , Nan::New<Number>(file_metadata->num_rows()));
info.GetReturnValue().Set(res);
}
void ParquetReader::Close(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
obj->parquet_file_reader_->Close();
}
template <typename T, typename U, typename V>
void reader(std::shared_ptr<parquet::ColumnReader> column_reader, int16_t maxdef, int16_t maxrep, const Nan::FunctionCallbackInfo<Value>& info) {
T reader = static_cast<T>(column_reader.get());
U value;
int64_t value_read;
int16_t definition = maxdef;
int16_t repetition = maxrep;
if (!reader->HasNext())
return;
reader->ReadBatch(1, &definition, &repetition, &value, &value_read);
if (maxrep == 0) {
if (definition == maxdef)
info.GetReturnValue().Set(Nan::New<V>(value));
return;
}
Local<Array> array = Nan::New<Array>(3);
array->Set(Nan::New<Number>(0), Nan::New<Number>(definition));
array->Set(Nan::New<Number>(1), Nan::New<Number>(repetition));
if (definition == maxdef)
array->Set(Nan::New<Number>(2), Nan::New<V>(value));
info.GetReturnValue().Set(array);
}
template <>
void reader<parquet::Int96Reader*, parquet::Int96, Number>(std::shared_ptr<parquet::ColumnReader> column_reader, int16_t maxdef, int16_t maxrep, const Nan::FunctionCallbackInfo<Value>& info) {
parquet::Int96Reader* reader = static_cast<parquet::Int96Reader*>(column_reader.get());
parquet::Int96 value;
int64_t value_read;
int16_t definition = maxdef;
int16_t repetition = maxrep;
if (!reader->HasNext())
return;
reader->ReadBatch(1, &definition, &repetition, &value, &value_read);
if (maxrep == 0) {
if (definition == maxdef)
info.GetReturnValue().Set(Nan::CopyBuffer((char*)value.value, 12).ToLocalChecked());
return;
}
Local<Array> array = Nan::New<Array>(3);
array->Set(Nan::New<Number>(0), Nan::New<Number>(definition));
array->Set(Nan::New<Number>(1), Nan::New<Number>(repetition));
if (definition == maxdef)
array->Set(Nan::New<Number>(2), Nan::CopyBuffer((char*)value.value, 12).ToLocalChecked());
info.GetReturnValue().Set(array);
}
template <>
void reader<parquet::ByteArrayReader*, parquet::ByteArray, Number>(std::shared_ptr<parquet::ColumnReader> column_reader, int16_t maxdef, int16_t maxrep, const Nan::FunctionCallbackInfo<Value>& info) {
parquet::ByteArrayReader* reader = static_cast<parquet::ByteArrayReader*>(column_reader.get());
parquet::ByteArray value;
int64_t value_read;
int16_t definition = maxdef;
int16_t repetition = maxrep;
if (!reader->HasNext())
return;
reader->ReadBatch(1, &definition, &repetition, &value, &value_read);
if (maxrep == 0) {
if (definition == maxdef)
info.GetReturnValue().Set(Nan::New((char*)value.ptr, value.len).ToLocalChecked());
return;
}
Local<Array> array = Nan::New<Array>(3);
array->Set(Nan::New<Number>(0), Nan::New<Number>(definition));
array->Set(Nan::New<Number>(1), Nan::New<Number>(repetition));
if (definition == maxdef)
array->Set(Nan::New<Number>(2), Nan::New((char*)value.ptr, value.len).ToLocalChecked());
info.GetReturnValue().Set(array);
}
template <>
void reader<parquet::FixedLenByteArrayReader*, parquet::FixedLenByteArray, Number>(std::shared_ptr<parquet::ColumnReader> column_reader, int16_t maxdef, int16_t maxrep, const Nan::FunctionCallbackInfo<Value>& info) {
parquet::FixedLenByteArrayReader* reader = static_cast<parquet::FixedLenByteArrayReader*>(column_reader.get());
parquet::FixedLenByteArray value;
int64_t value_read;
int16_t definition = maxdef;
int16_t repetition = maxrep;
if (!reader->HasNext())
return;
reader->ReadBatch(1, &definition, &repetition, &value, &value_read);
if (maxrep == 0) {
if (definition == maxdef)
info.GetReturnValue().Set(Nan::New((char*)value.ptr, 1).ToLocalChecked());
return;
}
Local<Array> array = Nan::New<Array>(3);
array->Set(Nan::New<Number>(0), Nan::New<Number>(definition));
array->Set(Nan::New<Number>(1), Nan::New<Number>(repetition));
if (definition == maxdef)
array->Set(Nan::New<Number>(2), Nan::New((char*)value.ptr, 1).ToLocalChecked());
info.GetReturnValue().Set(array);
}
typedef void (*reader_t)(std::shared_ptr<parquet::ColumnReader>, int16_t, int16_t, const Nan::FunctionCallbackInfo<Value>& info);
// Table of parquet readers. Keep same order as in parquet::Type
static reader_t type_readers[] = {
reader<parquet::BoolReader*, bool, Boolean>,
reader<parquet::Int32Reader*, int32_t, Number>,
reader<parquet::Int64Reader*, int64_t, Number>,
reader<parquet::Int96Reader*, parquet::Int96, Number>,
reader<parquet::FloatReader*, float, Number>,
reader<parquet::DoubleReader*, double, Number>,
reader<parquet::ByteArrayReader*, parquet::ByteArray, Number>,
reader<parquet::FixedLenByteArrayReader*, parquet::FixedLenByteArray, Number>,
};
// Read one column element.
void ParquetReader::Read(const Nan::FunctionCallbackInfo<Value>& info) {
ParquetReader* obj = ObjectWrap::Unwrap<ParquetReader>(info.Holder());
try {
int col = info[0]->IntegerValue();
std::shared_ptr<parquet::ColumnReader> column_reader = obj->column_readers_[col];
const parquet::ColumnDescriptor* descr = column_reader->descr();
reader_t type_reader = type_readers[column_reader->type()];
type_reader(column_reader, descr->max_definition_level(), descr->max_repetition_level(), info);
} catch (const std::exception& e) {
Nan::ThrowError(Nan::New(e.what()).ToLocalChecked());
return;
}
}
<|endoftext|> |
<commit_before>/**
* @author Olaf Radicke <[email protected]>
* @date 2013
* @copyright GNU Affero General Public License
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or later
* version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Core/models/Config.h>
#include <Core/initcomponent.h>
#include <RouteReverse/initcomponent.h>
#include <Core/manager/TableManager.h>
#include <tnt/tntnet.h>
#include <tnt/configurator.h>
#include <string>
#include <cxxtools/log.h>
log_define("PERUSCHIM")
int main ( int argc, char* argv[] )
{
try
{
/* initialize random seed: */
srand (time(NULL));
Config& config = Config::it();
config.read();
log_init(config.logging());
// Data base update check:
TableManager tabM;
if( tabM.update() == false ){
log_error("Table update was failed! Abortion...");
std::cerr << "Table update was failed! Abortion..." << std::endl;
exit (EXIT_FAILURE);
}
// Init Application Server
tnt::Tntnet app;
tnt::Configurator tntConfigurator(app);
tntConfigurator.setSessionTimeout ( config.sessionTimeout() );
app.listen( config.appIp(), config.appPort() );
// configure static stuff
app.mapUrl("^/Core/resources/(.*)", "resources")
.setPathInfo("Core/resources/$1");
app.mapUrl("^/Core/favicon.ico$", "resources")
.setPathInfo("Core/resources/favicon.ico");
// app.mapUrl("^/Core/feed-icon.png$", "resources")
// .setPathInfo("Core/resources/feed-icon.png");
// special pages
// 1 to 1 rout
app.mapUrl( "^/(.*)$", "$1" );
// default route for /
app.mapUrl( "^/$", "home" );
// controller rout for SessionForm token check.
app.mapUrl( "^/(.*)", "SessionForm::Controller" );
// controller rout for SessionForm token check.
app.mapUrl( "^/SessionForm/NoAvailabeToken", "NoAvailabeTokenView" );
// mvc stuff
app.mapUrl( "^/(.*)$", "$1Controller" );
app.mapUrl( "^/(.*)$", "$1View" );
RouteReverse::initcomponent( app );
Core::initcomponent( app );
std::cout << "peruschim cpp is started and run on http://" << config.appIp()
<< ":" << config.appPort() << "/" << std::endl;
log_info("starting PERUSCHIM");
log_info(
"peruschim cpp is started and run on http://" << config.appIp() \
<< ":" << config.appPort() << "/"
);
app.run();
} catch ( const std::exception& e )
{
std::cerr << e.what() << std::endl;
}
}
<commit_msg>bugfix<commit_after>/**
* @author Olaf Radicke <[email protected]>
* @date 2013
* @copyright GNU Affero General Public License
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or later
* version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Core/models/Config.h>
#include <Core/initcomponent.h>
#include <RouteReverse/initcomponent.h>
#include <Core/manager/TableManager.h>
#include <tnt/tntnet.h>
#include <tnt/configurator.h>
#include <string>
#include <cxxtools/log.h>
#include <stdlib.h>
log_define("PERUSCHIM")
int main ( int argc, char* argv[] )
{
try
{
/* initialize random seed: */
srand (time(NULL));
Config& config = Config::it();
config.read();
log_init(config.logging());
// Data base update check:
TableManager tabM;
if( tabM.update() == false ){
log_error("Table update was failed! Abortion...");
std::cerr << "Table update was failed! Abortion..." << std::endl;
exit (EXIT_FAILURE);
}
// Init Application Server
tnt::Tntnet app;
tnt::Configurator tntConfigurator(app);
tntConfigurator.setSessionTimeout ( config.sessionTimeout() );
app.listen( config.appIp(), config.appPort() );
// configure static stuff
app.mapUrl("^/Core/resources/(.*)", "resources")
.setPathInfo("Core/resources/$1");
app.mapUrl("^/Core/favicon.ico$", "resources")
.setPathInfo("Core/resources/favicon.ico");
// app.mapUrl("^/Core/feed-icon.png$", "resources")
// .setPathInfo("Core/resources/feed-icon.png");
// special pages
// 1 to 1 rout
app.mapUrl( "^/(.*)$", "$1" );
// default route for /
app.mapUrl( "^/$", "home" );
// controller rout for SessionForm token check.
app.mapUrl( "^/(.*)", "SessionForm::Controller" );
// controller rout for SessionForm token check.
app.mapUrl( "^/SessionForm/NoAvailabeToken", "NoAvailabeTokenView" );
// mvc stuff
app.mapUrl( "^/(.*)$", "$1Controller" );
app.mapUrl( "^/(.*)$", "$1View" );
RouteReverse::initcomponent( app );
Core::initcomponent( app );
std::cout << "peruschim cpp is started and run on http://" << config.appIp()
<< ":" << config.appPort() << "/" << std::endl;
log_info("starting PERUSCHIM");
log_info(
"peruschim cpp is started and run on http://" << config.appIp() \
<< ":" << config.appPort() << "/"
);
app.run();
} catch ( const std::exception& e )
{
std::cerr << e.what() << std::endl;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2008 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
// NaCl inter-module communication primitives.
//
// This file implements common parts of IMC for "unix like systems" (i.e. not
// used on Windows).
// TODO(shiki): Perhaps this file should go into a platform-specific directory
// (posix? unixlike?) We have a little convention going where mac/linux stuff
// goes in the linux directory and is referenced by the mac build but that's a
// little sloppy.
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <algorithm>
#include "native_client/src/include/atomic_ops.h"
#include "native_client/src/shared/imc/nacl_imc.h"
#if NACL_LINUX && (defined(CHROMIUM_BUILD) || defined(GOOGLE_CHROME_BUILD))
#include "chrome/renderer/renderer_sandbox_support_linux.h"
#endif
namespace nacl {
namespace {
// The pathname prefix for memory objects created by CreateMemoryObject().
#if NACL_OSX
// On Mac OS X, shm_open() gives us file descriptors that the OS won't
// mmap() with PROT_EXEC, which is no good for the dynamic code
// region, so use /tmp instead.
const char kShmPrefix[] = "/tmp/google-nacl-shm-";
# define SHM_OPEN open
#else
const char kShmPrefix[] = "/google-nacl-shm-";
# define SHM_OPEN shm_open
#endif
} // namespace
bool WouldBlock() {
return (errno == EAGAIN) ? true : false;
}
int GetLastErrorString(char* buffer, size_t length) {
#if NACL_LINUX
// Note some Linux distributions provide only GNU version of strerror_r().
if (buffer == NULL || length == 0) {
errno = ERANGE;
return -1;
}
char* message = strerror_r(errno, buffer, length);
if (message != buffer) {
size_t message_bytes = strlen(message) + 1;
length = std::min(message_bytes, length);
memmove(buffer, message, length);
buffer[length - 1] = '\0';
}
return 0;
#else
return strerror_r(errno, buffer, length);
#endif
}
static AtomicWord memory_object_count = 0;
Handle CreateMemoryObject(size_t length) {
if (0 == length) {
return -1;
}
char name[PATH_MAX];
for (;;) {
snprintf(name, sizeof name, "%s-%u.%u", kShmPrefix,
getpid(),
static_cast<uint32_t>(AtomicIncrement(&memory_object_count, 1)));
int m = SHM_OPEN(name, O_RDWR | O_CREAT | O_EXCL, 0);
if (0 <= m) {
(void) shm_unlink(name);
if (ftruncate(m, length) == -1) {
close(m);
m = -1;
}
return m;
}
if (errno != EEXIST) {
#if NACL_LINUX && (defined(CHROMIUM_BUILD) || defined(GOOGLE_CHROME_BUILD))
// As a temporary measure, we try shm_open() as well as calling
// the unsandboxed browser process. This code runs in the
// context of both the renderer and (Chromium's compiled-in)
// sel_ldr. Currently sel_ldr is not sandboxed and doesn't have
// the appropriate socket FD set up for talking to the browser.
return renderer_sandbox_support::MakeSharedMemorySegmentViaIPC(length);
#endif
return -1;
}
}
}
void* Map(void* start, size_t length, int prot, int flags,
Handle memory, off_t offset) {
static const int kPosixProt[] = {
PROT_NONE,
PROT_READ,
PROT_WRITE,
PROT_READ | PROT_WRITE,
PROT_EXEC,
PROT_READ | PROT_EXEC,
PROT_WRITE | PROT_EXEC,
PROT_READ | PROT_WRITE | PROT_EXEC
};
int adjusted = 0;
if (flags & kMapShared) {
adjusted |= MAP_SHARED;
}
if (flags & kMapPrivate) {
adjusted |= MAP_PRIVATE;
}
if (flags & kMapFixed) {
adjusted |= MAP_FIXED;
}
return mmap(start, length, kPosixProt[prot & 7], adjusted, memory, offset);
}
int Unmap(void* start, size_t length) {
return munmap(start, length);
}
} // namespace nacl
<commit_msg>Fix shared memory to work again in the Chromium Mac sandbox<commit_after>/*
* Copyright 2008 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can
* be found in the LICENSE file.
*/
// NaCl inter-module communication primitives.
//
// This file implements common parts of IMC for "unix like systems" (i.e. not
// used on Windows).
// TODO(shiki): Perhaps this file should go into a platform-specific directory
// (posix? unixlike?) We have a little convention going where mac/linux stuff
// goes in the linux directory and is referenced by the mac build but that's a
// little sloppy.
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <algorithm>
#include "native_client/src/include/atomic_ops.h"
#include "native_client/src/shared/imc/nacl_imc.h"
#if NACL_LINUX && (defined(CHROMIUM_BUILD) || defined(GOOGLE_CHROME_BUILD))
#include "chrome/renderer/renderer_sandbox_support_linux.h"
#endif
namespace nacl {
namespace {
// The pathname or SHM-namespace prefixes for memory objects created
// by CreateMemoryObject().
const char kShmTempPrefix[] = "/tmp/google-nacl-shm-";
const char kShmOpenPrefix[] = "/google-nacl-shm-";
} // namespace
bool WouldBlock() {
return (errno == EAGAIN) ? true : false;
}
int GetLastErrorString(char* buffer, size_t length) {
#if NACL_LINUX
// Note some Linux distributions provide only GNU version of strerror_r().
if (buffer == NULL || length == 0) {
errno = ERANGE;
return -1;
}
char* message = strerror_r(errno, buffer, length);
if (message != buffer) {
size_t message_bytes = strlen(message) + 1;
length = std::min(message_bytes, length);
memmove(buffer, message, length);
buffer[length - 1] = '\0';
}
return 0;
#else
return strerror_r(errno, buffer, length);
#endif
}
static AtomicWord memory_object_count = 0;
static int TryShmOrTempOpen(size_t length, bool use_temp) {
if (0 == length) {
return -1;
}
char name[PATH_MAX];
for (;;) {
const char *prefix = use_temp ? kShmTempPrefix : kShmOpenPrefix;
snprintf(name, sizeof name, "%s-%u.%u", prefix,
getpid(),
static_cast<uint32_t>(AtomicIncrement(&memory_object_count, 1)));
int m;
if (use_temp) {
m = open(name, O_RDWR | O_CREAT | O_EXCL, 0);
} else {
m = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0);
}
if (0 <= m) {
(void) shm_unlink(name);
if (ftruncate(m, length) == -1) {
close(m);
m = -1;
}
return m;
}
if (errno != EEXIST) {
return -1;
}
// Retry only if we got EEXIST.
}
}
Handle CreateMemoryObject(size_t length) {
if (0 == length) {
return -1;
}
int fd;
// On Mac OS X, shm_open() gives us file descriptors that the OS
// won't mmap() with PROT_EXEC, which is no good for the dynamic
// code region. Try open()ing a file in /tmp first, but fall back
// to using shm_open() if /tmp is not available, which will be the
// case inside the Chromium sandbox. This means that dynamic
// loading will only work with --no-sandbox.
//
// TODO(mseaborn): We will probably need to do IPC to acquire SHM FDs
// inside the Chromium Mac sandbox, as on Linux.
#if NACL_OSX
// Try /tmp first. It would be OK to enable this for Linux, but
// there's no need because shm_open() (which uses /dev/shm rather
// than /tmp) is fine on Linux.
fd = TryShmOrTempOpen(length, true);
if (fd >= 0)
return fd;
#endif
// Try shm_open().
fd = TryShmOrTempOpen(length, false);
if (fd >= 0)
return fd;
#if NACL_LINUX && (defined(CHROMIUM_BUILD) || defined(GOOGLE_CHROME_BUILD))
// As a temporary measure, we try shm_open() as well as calling
// the unsandboxed browser process. This code runs in the
// context of both the renderer and (Chromium's compiled-in)
// sel_ldr. Currently sel_ldr is not sandboxed and doesn't have
// the appropriate socket FD set up for talking to the browser.
// TODO(mseaborn): Move this to be the first method tried.
return renderer_sandbox_support::MakeSharedMemorySegmentViaIPC(length);
#endif
return -1;
}
void* Map(void* start, size_t length, int prot, int flags,
Handle memory, off_t offset) {
static const int kPosixProt[] = {
PROT_NONE,
PROT_READ,
PROT_WRITE,
PROT_READ | PROT_WRITE,
PROT_EXEC,
PROT_READ | PROT_EXEC,
PROT_WRITE | PROT_EXEC,
PROT_READ | PROT_WRITE | PROT_EXEC
};
int adjusted = 0;
if (flags & kMapShared) {
adjusted |= MAP_SHARED;
}
if (flags & kMapPrivate) {
adjusted |= MAP_PRIVATE;
}
if (flags & kMapFixed) {
adjusted |= MAP_FIXED;
}
return mmap(start, length, kPosixProt[prot & 7], adjusted, memory, offset);
}
int Unmap(void* start, size_t length) {
return munmap(start, length);
}
} // namespace nacl
<|endoftext|> |
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "user_db.h"
#include "seeks_proxy.h"
#include "errlog.h"
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <vector>
#include <iostream>
namespace sp
{
std::string user_db::_db_name = "seeks_user.db";
user_db::user_db()
{
// create the db.
_hdb = tchdbnew();
//TODO: compression.
// db location.
uid_t user_id = getuid(); // get user for the calling process.
struct passwd *pw = getpwuid(user_id);
if (pw)
{
const char *pw_dir = pw->pw_dir;
if(pw_dir)
{
_name = std::string(pw_dir) + ".seeks/";
int err = mkdir(_name.c_str(),0730); // create .seeks repository in case it does not exist.
if (err != 0 && errno != EEXIST) // all but file exist errors.
{
errlog::log_error(LOG_LEVEL_ERROR,"Creating repository %s failed: %s",
_name.c_str(),strerror(errno));
_name = "";
}
else _name += user_db::_db_name;
}
}
if (_name.empty())
{
// try datadir, beware, we may not have permission to write.
if (seeks_proxy::_datadir.empty())
_name = user_db::_db_name; // write it down locally.
else _name = seeks_proxy::_datadir + user_db::_db_name;
}
}
user_db::~user_db()
{
// close the db.
close_db();
// delete db object.
tchdbdel(_hdb);
}
int user_db::open_db()
{
// try to get write access, if not, fall back to read-only access, with a warning.
if(!tchdbopen(_hdb, _name.c_str(), HDBOWRITER | HDBOCREAT))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db db open error: %s",tchdberrmsg(ecode));
errlog::log_error(LOG_LEVEL_INFO, "trying to open user_db in read-only mode");
if(!tchdbopen(_hdb, _name.c_str(), HDBOREADER | HDBOCREAT))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db read-only or creation db open error: %s",tchdberrmsg(ecode));
_opened = false;
return ecode;
}
_opened = false;
return ecode;
}
uint64_t rn = number_records();
errlog::log_error(LOG_LEVEL_INFO,"opened user_db %s, (%u records)",
_name.c_str(),rn);
_opened = true;
return 0;
}
int user_db::close_db()
{
if(!tchdbclose(_hdb))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db close error: %s",tchdberrmsg(ecode));
return ecode;
}
_opened = false;
return 0;
}
std::string user_db::generate_rkey(const std::string &key,
const std::string &plugin_name)
{
return plugin_name + ":" + key;
}
std::string user_db::extract_key(const std::string &rkey)
{
size_t pos = rkey.find_first_of(":");
if (pos == std::string::npos)
return "";
return rkey.substr(pos);
}
int user_db::add_dbr(const std::string &key,
const std::string &plugin_name,
const db_record &dbr)
{
// serialize the record.
std::string str;
dbr.serialize(str);
// create key.
std::string rkey = user_db::generate_rkey(key,plugin_name);
// add record.
size_t lrkey = rkey.length();
char keyc[lrkey];
for (size_t i=0;i<lrkey;i++)
keyc[i] = rkey[i];
size_t lstr = str.length();
char valc[lstr];
for (size_t i=0;i<lstr;i++)
valc[i] = str[i];
if (!tchdbput(_hdb,keyc,sizeof(keyc),valc,sizeof(valc))) // erase if record already exists. XXX: study async call.
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db adding record error: %s",tchdberrmsg(ecode));
return -1;
}
return 0;
}
int user_db::remove_dbr(const std::string &rkey)
{
if (!tchdbout2(_hdb,rkey.c_str()))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db removing record error: %s",tchdberrmsg(ecode));
return -1;
}
return 0;
}
int user_db::remove_dbr(const std::string &key,
const std::string &plugin_name)
{
// create key.
std::string rkey = user_db::generate_rkey(key,plugin_name);
// remove record.
return remove_dbr(rkey);
}
int user_db::clear_db()
{
if(!tchdbvanish(_hdb))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db clearing error: %s",tchdberrmsg(ecode));
return ecode;
}
return 0;
}
int user_db::prune_db(const time_t &date)
{
void *key = NULL;
int key_size;
std::vector<std::string> to_remove;
tchdbiterinit(_hdb);
while((key = tchdbiternext(_hdb,&key_size)) != NULL)
{
int value_size;
void *value = tchdbget(_hdb, key, key_size, &value_size);
if(value)
{
std::string str = std::string((char*)value,value_size);
free(value);
db_record dbr(str);
if (dbr._creation_time < date)
to_remove.push_back(std::string((char*)key));
}
free(key);
}
int err = 0;
size_t trs = to_remove.size();
for (size_t i=0;i<trs;i++)
err += remove_dbr(to_remove.at(i));
return err;
}
int user_db::prune_db(const std::string &plugin_name)
{
void *key = NULL;
int key_size;
std::vector<std::string> to_remove;
tchdbiterinit(_hdb);
while((key = tchdbiternext(_hdb,&key_size)) != NULL)
{
int value_size;
void *value = tchdbget(_hdb, key, key_size, &value_size);
if(value)
{
std::string str = std::string((char*)value,value_size);
free(value);
db_record dbr(str);
if (dbr._plugin_name == plugin_name)
to_remove.push_back(std::string((char*)key));
}
free(key);
}
int err = 0;
size_t trs = to_remove.size();
for (size_t i=0;i<trs;i++)
err += remove_dbr(to_remove.at(i));
return err;
}
uint64_t user_db::disk_size() const
{
return tchdbfsiz(_hdb);
}
uint64_t user_db::number_records() const
{
return tchdbrnum(_hdb);
}
void user_db::read() const
{
/* traverse records */
void *key = NULL;
void *value = NULL;
int key_size;
tchdbiterinit(_hdb);
while((key = tchdbiternext(_hdb,&key_size)) != NULL)
{
int value_size;
value = tchdbget(_hdb, key, key_size, &value_size);
if(value)
{
std::string str = std::string((char*)value,value_size);
db_record dbr(str);
std::cerr << "db_record[" << user_db::extract_key(std::string((char*)key))
<< "]: plugin_name: " << dbr._plugin_name << " - creation time: " << dbr._creation_time << std::endl;
free(value);
}
free(key);
}
}
} /* end of namespace. */
<commit_msg>fixed wrong path in user db opening call<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2010 Emmanuel Benazera, [email protected]
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "user_db.h"
#include "seeks_proxy.h"
#include "errlog.h"
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <vector>
#include <iostream>
namespace sp
{
std::string user_db::_db_name = "seeks_user.db";
user_db::user_db()
{
// create the db.
_hdb = tchdbnew();
//TODO: compression.
// db location.
uid_t user_id = getuid(); // get user for the calling process.
struct passwd *pw = getpwuid(user_id);
if (pw)
{
const char *pw_dir = pw->pw_dir;
if(pw_dir)
{
_name = std::string(pw_dir) + "/.seeks/";
int err = mkdir(_name.c_str(),0730); // create .seeks repository in case it does not exist.
if (err != 0 && errno != EEXIST) // all but file exist errors.
{
errlog::log_error(LOG_LEVEL_ERROR,"Creating repository %s failed: %s",
_name.c_str(),strerror(errno));
_name = "";
}
else _name += user_db::_db_name;
}
}
if (_name.empty())
{
// try datadir, beware, we may not have permission to write.
if (seeks_proxy::_datadir.empty())
_name = user_db::_db_name; // write it down locally.
else _name = seeks_proxy::_datadir + user_db::_db_name;
}
}
user_db::~user_db()
{
// close the db.
close_db();
// delete db object.
tchdbdel(_hdb);
}
int user_db::open_db()
{
// try to get write access, if not, fall back to read-only access, with a warning.
if(!tchdbopen(_hdb, _name.c_str(), HDBOWRITER | HDBOCREAT))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db db open error: %s",tchdberrmsg(ecode));
errlog::log_error(LOG_LEVEL_INFO, "trying to open user_db in read-only mode");
if(!tchdbopen(_hdb, _name.c_str(), HDBOREADER | HDBOCREAT))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db read-only or creation db open error: %s",tchdberrmsg(ecode));
_opened = false;
return ecode;
}
_opened = false;
return ecode;
}
uint64_t rn = number_records();
errlog::log_error(LOG_LEVEL_INFO,"opened user_db %s, (%u records)",
_name.c_str(),rn);
_opened = true;
return 0;
}
int user_db::close_db()
{
if(!tchdbclose(_hdb))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db close error: %s",tchdberrmsg(ecode));
return ecode;
}
_opened = false;
return 0;
}
std::string user_db::generate_rkey(const std::string &key,
const std::string &plugin_name)
{
return plugin_name + ":" + key;
}
std::string user_db::extract_key(const std::string &rkey)
{
size_t pos = rkey.find_first_of(":");
if (pos == std::string::npos)
return "";
return rkey.substr(pos);
}
int user_db::add_dbr(const std::string &key,
const std::string &plugin_name,
const db_record &dbr)
{
// serialize the record.
std::string str;
dbr.serialize(str);
// create key.
std::string rkey = user_db::generate_rkey(key,plugin_name);
// add record.
size_t lrkey = rkey.length();
char keyc[lrkey];
for (size_t i=0;i<lrkey;i++)
keyc[i] = rkey[i];
size_t lstr = str.length();
char valc[lstr];
for (size_t i=0;i<lstr;i++)
valc[i] = str[i];
if (!tchdbput(_hdb,keyc,sizeof(keyc),valc,sizeof(valc))) // erase if record already exists. XXX: study async call.
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db adding record error: %s",tchdberrmsg(ecode));
return -1;
}
return 0;
}
int user_db::remove_dbr(const std::string &rkey)
{
if (!tchdbout2(_hdb,rkey.c_str()))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db removing record error: %s",tchdberrmsg(ecode));
return -1;
}
return 0;
}
int user_db::remove_dbr(const std::string &key,
const std::string &plugin_name)
{
// create key.
std::string rkey = user_db::generate_rkey(key,plugin_name);
// remove record.
return remove_dbr(rkey);
}
int user_db::clear_db()
{
if(!tchdbvanish(_hdb))
{
int ecode = tchdbecode(_hdb);
errlog::log_error(LOG_LEVEL_ERROR,"user db clearing error: %s",tchdberrmsg(ecode));
return ecode;
}
return 0;
}
int user_db::prune_db(const time_t &date)
{
void *key = NULL;
int key_size;
std::vector<std::string> to_remove;
tchdbiterinit(_hdb);
while((key = tchdbiternext(_hdb,&key_size)) != NULL)
{
int value_size;
void *value = tchdbget(_hdb, key, key_size, &value_size);
if(value)
{
std::string str = std::string((char*)value,value_size);
free(value);
db_record dbr(str);
if (dbr._creation_time < date)
to_remove.push_back(std::string((char*)key));
}
free(key);
}
int err = 0;
size_t trs = to_remove.size();
for (size_t i=0;i<trs;i++)
err += remove_dbr(to_remove.at(i));
return err;
}
int user_db::prune_db(const std::string &plugin_name)
{
void *key = NULL;
int key_size;
std::vector<std::string> to_remove;
tchdbiterinit(_hdb);
while((key = tchdbiternext(_hdb,&key_size)) != NULL)
{
int value_size;
void *value = tchdbget(_hdb, key, key_size, &value_size);
if(value)
{
std::string str = std::string((char*)value,value_size);
free(value);
db_record dbr(str);
if (dbr._plugin_name == plugin_name)
to_remove.push_back(std::string((char*)key));
}
free(key);
}
int err = 0;
size_t trs = to_remove.size();
for (size_t i=0;i<trs;i++)
err += remove_dbr(to_remove.at(i));
return err;
}
uint64_t user_db::disk_size() const
{
return tchdbfsiz(_hdb);
}
uint64_t user_db::number_records() const
{
return tchdbrnum(_hdb);
}
void user_db::read() const
{
/* traverse records */
void *key = NULL;
void *value = NULL;
int key_size;
tchdbiterinit(_hdb);
while((key = tchdbiternext(_hdb,&key_size)) != NULL)
{
int value_size;
value = tchdbget(_hdb, key, key_size, &value_size);
if(value)
{
std::string str = std::string((char*)value,value_size);
db_record dbr(str);
std::cerr << "db_record[" << user_db::extract_key(std::string((char*)key))
<< "]: plugin_name: " << dbr._plugin_name << " - creation time: " << dbr._creation_time << std::endl;
free(value);
}
free(key);
}
}
} /* end of namespace. */
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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 <pybind11/embed.h>
#include <iostream>
namespace py = pybind11;
using namespace pybind11::literals;
constexpr auto MarshalScript = R"(
import marshal
with open(source, 'r') as f:
src = f.read()
compiled = compile(src, source, 'exec')
marshalled = marshal.dumps(compiled)
)";
int
main(int argc, const char **argv)
{
py::scoped_interpreter guard;
if (argc != 2) {
std::cerr << "Usage: marshal PYSOURCE" << std::endl;
exit(1);
}
auto locals = py::dict("source"_a=argv[1]);
py::exec(MarshalScript, py::globals(), locals);
auto marshalled = locals["marshalled"].cast<std::string>();
std::cout << marshalled;
return 0;
}
<commit_msg>python: Pull most of the logic in marshal.cc into python.<commit_after>/*
* Copyright (c) 2019 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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 <pybind11/embed.h>
namespace py = pybind11;
constexpr auto MarshalScript = R"(
import marshal
import sys
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} PYSOURCE", file=sys.stderr)
sys.exit(1)
source = sys.argv[1]
with open(source, 'r') as f:
src = f.read()
compiled = compile(src, source, 'exec')
marshalled = marshal.dumps(compiled)
sys.stdout.buffer.write(marshalled)
)";
int
main(int argc, const char **argv)
{
py::scoped_interpreter guard;
// Embedded python doesn't set up sys.argv, so we'll do that ourselves.
py::list py_argv;
auto sys = py::module::import("sys");
if (py::hasattr(sys, "argv")) {
// sys.argv already exists, so grab that.
py_argv = sys.attr("argv");
} else {
// sys.argv doesn't exist, so create it.
sys.add_object("argv", py_argv);
}
// Clear out argv just in case it has something in it.
py_argv.attr("clear")();
// Fill it with our argvs.
for (int i = 0; i < argc; i++)
py_argv.append(argv[i]);
// Actually call the script.
py::exec(MarshalScript, py::globals());
return 0;
}
<|endoftext|> |
<commit_before>#include "nlt_store.hpp"
#include <terark/int_vector.hpp>
#include <typeinfo>
#include <float.h>
#include <mutex>
#include <random>
namespace terark { namespace db { namespace dfadb {
TERARK_DB_REGISTER_STORE("nlt", NestLoudsTrieStore);
NestLoudsTrieStore::NestLoudsTrieStore(const Schema& schema) : m_schema(schema) {
}
NestLoudsTrieStore::NestLoudsTrieStore(const Schema& schema, BlobStore* blobStore)
: m_schema(schema), m_store(blobStore) {
}
NestLoudsTrieStore::~NestLoudsTrieStore() {
}
llong NestLoudsTrieStore::dataStorageSize() const {
return m_store->mem_size();
}
llong NestLoudsTrieStore::dataInflateSize() const {
return m_store->total_data_size();
}
llong NestLoudsTrieStore::numDataRows() const {
return m_store->num_records();
}
void NestLoudsTrieStore::getValueAppend(llong id, valvec<byte>* val, DbContext* ctx) const {
m_store->get_record_append(size_t(id), val);
}
StoreIterator* NestLoudsTrieStore::createStoreIterForward(DbContext*) const {
return nullptr; // not needed
}
StoreIterator* NestLoudsTrieStore::createStoreIterBackward(DbContext*) const {
return nullptr; // not needed
}
template<class Class>
static
Class* doBuild(const NestLoudsTrieConfig& conf,
const Schema& schema, SortableStrVec& strVec) {
std::unique_ptr<Class> trie(new Class());
trie->build_from(strVec, conf);
return trie.release();
}
static
void initConfigFromSchema(NestLoudsTrieConfig& conf, const Schema& schema) {
conf.initFromEnv();
if (schema.m_sufarrMinFreq) {
conf.saFragMinFreq = (byte_t)schema.m_sufarrMinFreq;
}
if (schema.m_minFragLen) {
conf.minFragLen = schema.m_minFragLen;
}
if (schema.m_maxFragLen) {
conf.maxFragLen = schema.m_maxFragLen;
}
if (schema.m_nltDelims.size()) {
conf.setBestDelims(schema.m_nltDelims.c_str());
}
conf.nestLevel = schema.m_nltNestLevel;
}
static
BlobStore* nltBuild(const Schema& schema, SortableStrVec& strVec) {
NestLoudsTrieConfig conf;
initConfigFromSchema(conf, schema);
switch (schema.m_rankSelectClass) {
case -256:
return doBuild<NestLoudsTrieBlobStore_IL>(conf, schema, strVec);
case +256:
return doBuild<NestLoudsTrieBlobStore_SE>(conf, schema, strVec);
case +512:
return doBuild<NestLoudsTrieBlobStore_SE_512>(conf, schema, strVec);
default:
fprintf(stderr, "WARN: invalid schema(%s).rs = %d, use default: se_512\n"
, schema.m_name.c_str(), schema.m_rankSelectClass);
return doBuild<NestLoudsTrieBlobStore_SE_512>(conf, schema, strVec);
}
}
void NestLoudsTrieStore::build(const Schema& schema, SortableStrVec& strVec) {
if (schema.m_dictZipSampleRatio > 0) {
m_store.reset(DictZipBlobStore::build_none_local_match(
strVec, schema.m_dictZipSampleRatio));
}
else if (schema.m_useFastZip) {
std::unique_ptr<FastZipBlobStore> fzds(new FastZipBlobStore());
NestLoudsTrieConfig conf;
initConfigFromSchema(conf, schema);
fzds->build_from(strVec, conf);
m_store.reset(fzds.release());
}
else {
m_store.reset(nltBuild(schema, strVec));
}
}
std::mutex& DictZip_reduceMemMutex() {
static std::mutex m;
return m;
}
void emptyCheckProtect(size_t sampleLenSum, fstring rec,
DictZipBlobStore::ZipBuilder& builder) {
if (0 == sampleLenSum) {
if (rec.empty())
builder.addSample("Hello World!"); // for fallback
else
builder.addSample(rec);
}
}
std::unique_ptr<DictZipBlobStore::ZipBuilder>
createDictZipBlobStoreBuilder(const Schema& schema) {
typedef DictZipBlobStore::Options::EntropyAlgo EntropyAlgo;
DictZipBlobStore::Options opt;
opt.checksumLevel = schema.m_checksumLevel;
opt.entropyAlgo = EntropyAlgo(schema.m_dictZipEntropyType);
opt.useSuffixArrayLocalMatch = schema.m_dictZipUseSuffixArrayLocalMatch;
return std::unique_ptr<DictZipBlobStore::ZipBuilder>
(DictZipBlobStore::createZipBuilder(opt));
}
void
NestLoudsTrieStore::build_by_iter(const Schema& schema, PathRef fpath,
StoreIterator& iter,
const bm_uint_t* isDel,
const febitvec* isPurged) {
TERARK_RT_assert(schema.m_dictZipSampleRatio >= 0, std::invalid_argument);
std::unique_ptr<DictZipBlobStore::ZipBuilder>
builder(createDictZipBlobStoreBuilder(schema));
double sampleRatio = schema.m_dictZipSampleRatio > FLT_EPSILON
? schema.m_dictZipSampleRatio : 0.05;
{
TERARK_RT_assert(nullptr != iter.getStore(), std::invalid_argument);
llong dataSize = iter.getStore()->dataInflateSize();
if (dataSize * sampleRatio >= INT32_MAX * 0.95) {
sampleRatio = INT32_MAX * 0.95 / dataSize;
}
sampleRatio = std::min(sampleRatio, 0.5);
}
// 1. sample memory usage = inputBytes*sampleRatio, and will
// linear scan the input data
// 2. builder->prepare() will build the suffix array and cache
// for suffix array, and this is all in-memery computing,
// the memory usage is about 5*inputBytes*sampleRatio, after
// `prepare` finished, the total memory usage is about
// 6*inputBytes*sampleRatio
// 3. builder->addRecord() will send the records into compressing
// pipeline, records will be compressed parallel, this will
// take a long time, the total memory during compressing is
// 6*inputBytes*sampleRatio, plus few additional working memory
// 4. using lock, the concurrent large memory using durations in
// multi threads are serialized, then the peak memory usage
// is reduced
std::mutex& reduceMemMutex = DictZip_reduceMemMutex();
// the lock will be hold for a long time, maybe several minutes
std::unique_lock<std::mutex> lock(reduceMemMutex, std::defer_lock);
valvec<byte> rec;
std::mt19937_64 random;
// (random.max() - random.min()) + 1 may overflow
// do not +1 to avoid overflow
uint64_t sampleUpperBound = random.min() +
(random.max() - random.min()) * sampleRatio;
if (NULL == isPurged || isPurged->size() == 0) {
llong recId;
size_t sampled = 0;
while (iter.increment(&recId, &rec)) {
if (NULL == isDel || !terark_bit_test(isDel, recId)) {
if (!rec.empty() && random() < sampleUpperBound) {
builder->addSample(rec);
sampled++;
}
}
}
emptyCheckProtect(sampled, rec, *builder);
lock.lock(); // start lock
builder->prepare(recId + 1, fpath.string());
iter.reset();
while (iter.increment(&recId, &rec)) {
if (NULL == isDel || !terark_bit_test(isDel, recId)) {
builder->addRecord(rec);
}
}
}
else {
assert(NULL != isDel);
llong newPhysicId = 0;
llong physicId = 0;
size_t logicNum = isPurged->size();
size_t physicNum = iter.getStore()->numDataRows();
size_t sampled = 0;
const bm_uint_t* isPurgedptr = isPurged->bldata();
for (size_t logicId = 0; logicId < logicNum; ++logicId) {
if (!terark_bit_test(isPurgedptr, logicId)) {
if (!terark_bit_test(isDel, logicId)) {
bool hasData = iter.seekExact(physicId, &rec);
if (!hasData) {
fprintf(stderr
, "ERROR: %s:%d: logicId = %zd, physicId = %lld, logicNum = %zd, physicNum = %zd\n"
, __FILE__, __LINE__, logicId, physicId, logicNum, physicNum);
fflush(stderr);
abort(); // there are some bugs
}
// if (hasData && rec.empty()) {
// hasData = false;
// }
if (!rec.empty() && random() < sampleUpperBound) {
builder->addSample(rec);
sampled++;
}
newPhysicId++;
}
physicId++;
}
}
if (size_t(physicId) != physicNum) {
fprintf(stderr
, "ERROR: %s:%d: physicId != physicNum: physicId = %lld, physicNum = %zd, logicNum = %zd\n"
, __FILE__, __LINE__, physicId, physicNum, logicNum);
}
emptyCheckProtect(sampled, rec, *builder);
lock.lock(); // start lock
builder->prepare(newPhysicId, fpath.string());
iter.reset();
physicId = 0;
for (size_t logicId = 0; logicId < logicNum; ++logicId) {
if (!terark_bit_test(isPurgedptr, logicId)) {
llong physicId2 = -1;
bool hasData = iter.increment(&physicId2, &rec);
if (!hasData || physicId != physicId2) {
fprintf(stderr
, "ERROR: %s:%d: hasData = %d, logicId = %zd, physicId = %lld, physicId2 = %lld, physicNum = %zd, logicNum = %zd\n"
, __FILE__, __LINE__, hasData, logicId, physicId, physicId2, physicNum, logicNum);
fflush(stderr);
abort(); // there are some bugs
}
if (!terark_bit_test(isDel, logicId)) {
builder->addRecord(rec);
}
physicId++;
}
}
if (size_t(physicId) != physicNum) {
fprintf(stderr
, "ERROR: %s:%d: physicId != physicNum: physicId = %lld, physicNum = %zd, logicNum = %zd\n"
, __FILE__, __LINE__, physicId, physicNum, logicNum);
}
}
m_store.reset(builder->finish());
builder.reset(); // explicit destory builder, before lock.unlock
}
void NestLoudsTrieStore::load(PathRef path) {
std::string fpath = fstring(path.string()).endsWith(".nlt")
? path.string()
: path.string() + ".nlt";
m_store.reset(BlobStore::load_from(fpath, m_schema.m_mmapPopulate));
}
void NestLoudsTrieStore::save(PathRef path) const {
std::string fpath = fstring(path.string()).endsWith(".nlt")
? path.string()
: path.string() + ".nlt";
if (BaseDFA* dfa = dynamic_cast<BaseDFA*>(&*m_store)) {
dfa->save_mmap(fpath.c_str());
}
else if (auto zds = dynamic_cast<FastZipBlobStore*>(&*m_store)) {
zds->save_mmap(fpath);
}
else if (auto zds = dynamic_cast<DictZipBlobStore*>(&*m_store)) {
zds->save_mmap(fpath);
}
else {
THROW_STD(invalid_argument, "Unexpected");
}
}
}}} // namespace terark::db::dfadb
<commit_msg>nlt_store.cpp: Minor fix<commit_after>#include "nlt_store.hpp"
#include <terark/int_vector.hpp>
#include <typeinfo>
#include <float.h>
#include <mutex>
#include <random>
namespace terark { namespace db { namespace dfadb {
TERARK_DB_REGISTER_STORE("nlt", NestLoudsTrieStore);
NestLoudsTrieStore::NestLoudsTrieStore(const Schema& schema) : m_schema(schema) {
}
NestLoudsTrieStore::NestLoudsTrieStore(const Schema& schema, BlobStore* blobStore)
: m_schema(schema), m_store(blobStore) {
}
NestLoudsTrieStore::~NestLoudsTrieStore() {
}
llong NestLoudsTrieStore::dataStorageSize() const {
return m_store->mem_size();
}
llong NestLoudsTrieStore::dataInflateSize() const {
return m_store->total_data_size();
}
llong NestLoudsTrieStore::numDataRows() const {
return m_store->num_records();
}
void NestLoudsTrieStore::getValueAppend(llong id, valvec<byte>* val, DbContext* ctx) const {
m_store->get_record_append(size_t(id), val);
}
StoreIterator* NestLoudsTrieStore::createStoreIterForward(DbContext*) const {
return nullptr; // not needed
}
StoreIterator* NestLoudsTrieStore::createStoreIterBackward(DbContext*) const {
return nullptr; // not needed
}
template<class Class>
static
Class* doBuild(const NestLoudsTrieConfig& conf,
const Schema& schema, SortableStrVec& strVec) {
std::unique_ptr<Class> trie(new Class());
trie->build_from(strVec, conf);
return trie.release();
}
static
void initConfigFromSchema(NestLoudsTrieConfig& conf, const Schema& schema) {
conf.initFromEnv();
if (schema.m_sufarrMinFreq) {
conf.saFragMinFreq = (byte_t)schema.m_sufarrMinFreq;
}
if (schema.m_minFragLen) {
conf.minFragLen = schema.m_minFragLen;
}
if (schema.m_maxFragLen) {
conf.maxFragLen = schema.m_maxFragLen;
}
if (schema.m_nltDelims.size()) {
conf.setBestDelims(schema.m_nltDelims.c_str());
}
conf.nestLevel = schema.m_nltNestLevel;
}
static
BlobStore* nltBuild(const Schema& schema, SortableStrVec& strVec) {
NestLoudsTrieConfig conf;
initConfigFromSchema(conf, schema);
switch (schema.m_rankSelectClass) {
case -256:
return doBuild<NestLoudsTrieBlobStore_IL>(conf, schema, strVec);
case +256:
return doBuild<NestLoudsTrieBlobStore_SE>(conf, schema, strVec);
case +512:
return doBuild<NestLoudsTrieBlobStore_SE_512>(conf, schema, strVec);
default:
fprintf(stderr, "WARN: invalid schema(%s).rs = %d, use default: se_512\n"
, schema.m_name.c_str(), schema.m_rankSelectClass);
return doBuild<NestLoudsTrieBlobStore_SE_512>(conf, schema, strVec);
}
}
void NestLoudsTrieStore::build(const Schema& schema, SortableStrVec& strVec) {
if (schema.m_dictZipSampleRatio > 0) {
m_store.reset(DictZipBlobStore::build_none_local_match(
strVec, schema.m_dictZipSampleRatio));
}
else if (schema.m_useFastZip) {
std::unique_ptr<FastZipBlobStore> fzds(new FastZipBlobStore());
NestLoudsTrieConfig conf;
initConfigFromSchema(conf, schema);
fzds->build_from(strVec, conf);
m_store.reset(fzds.release());
}
else {
m_store.reset(nltBuild(schema, strVec));
}
}
std::mutex& DictZip_reduceMemMutex() {
static std::mutex m;
return m;
}
void emptyCheckProtect(size_t sampleLenSum, fstring rec,
DictZipBlobStore::ZipBuilder& builder) {
if (0 == sampleLenSum) {
if (rec.empty() || rec.size() >= 10*1024*1024)
builder.addSample("Hello World!"); // for fallback
else
builder.addSample(rec);
}
}
std::unique_ptr<DictZipBlobStore::ZipBuilder>
createDictZipBlobStoreBuilder(const Schema& schema) {
typedef DictZipBlobStore::Options::EntropyAlgo EntropyAlgo;
DictZipBlobStore::Options opt;
opt.checksumLevel = schema.m_checksumLevel;
opt.entropyAlgo = EntropyAlgo(schema.m_dictZipEntropyType);
opt.useSuffixArrayLocalMatch = schema.m_dictZipUseSuffixArrayLocalMatch;
return std::unique_ptr<DictZipBlobStore::ZipBuilder>
(DictZipBlobStore::createZipBuilder(opt));
}
void
NestLoudsTrieStore::build_by_iter(const Schema& schema, PathRef fpath,
StoreIterator& iter,
const bm_uint_t* isDel,
const febitvec* isPurged) {
TERARK_RT_assert(schema.m_dictZipSampleRatio >= 0, std::invalid_argument);
std::unique_ptr<DictZipBlobStore::ZipBuilder>
builder(createDictZipBlobStoreBuilder(schema));
double sampleRatio = schema.m_dictZipSampleRatio > FLT_EPSILON
? schema.m_dictZipSampleRatio : 0.05;
{
TERARK_RT_assert(nullptr != iter.getStore(), std::invalid_argument);
llong dataSize = iter.getStore()->dataInflateSize();
if (dataSize * sampleRatio >= INT32_MAX * 0.95) {
sampleRatio = INT32_MAX * 0.95 / dataSize;
}
sampleRatio = std::min(sampleRatio, 0.5);
}
// 1. sample memory usage = inputBytes*sampleRatio, and will
// linear scan the input data
// 2. builder->prepare() will build the suffix array and cache
// for suffix array, and this is all in-memery computing,
// the memory usage is about 5*inputBytes*sampleRatio, after
// `prepare` finished, the total memory usage is about
// 6*inputBytes*sampleRatio
// 3. builder->addRecord() will send the records into compressing
// pipeline, records will be compressed parallel, this will
// take a long time, the total memory during compressing is
// 6*inputBytes*sampleRatio, plus few additional working memory
// 4. using lock, the concurrent large memory using durations in
// multi threads are serialized, then the peak memory usage
// is reduced
std::mutex& reduceMemMutex = DictZip_reduceMemMutex();
// the lock will be hold for a long time, maybe several minutes
std::unique_lock<std::mutex> lock(reduceMemMutex, std::defer_lock);
valvec<byte> rec;
std::mt19937_64 random;
// (random.max() - random.min()) + 1 may overflow
// do not +1 to avoid overflow
uint64_t sampleUpperBound = random.min() +
(random.max() - random.min()) * sampleRatio;
if (NULL == isPurged || isPurged->size() == 0) {
llong recId;
size_t sampled = 0;
while (iter.increment(&recId, &rec)) {
if (NULL == isDel || !terark_bit_test(isDel, recId)) {
if (!rec.empty() && random() < sampleUpperBound) {
builder->addSample(rec);
sampled++;
}
}
}
emptyCheckProtect(sampled, rec, *builder);
lock.lock(); // start lock
builder->prepare(recId + 1, fpath.string());
iter.reset();
while (iter.increment(&recId, &rec)) {
if (NULL == isDel || !terark_bit_test(isDel, recId)) {
builder->addRecord(rec);
}
}
}
else {
assert(NULL != isDel);
llong newPhysicId = 0;
llong physicId = 0;
size_t logicNum = isPurged->size();
size_t physicNum = iter.getStore()->numDataRows();
size_t sampled = 0;
const bm_uint_t* isPurgedptr = isPurged->bldata();
for (size_t logicId = 0; logicId < logicNum; ++logicId) {
if (!terark_bit_test(isPurgedptr, logicId)) {
if (!terark_bit_test(isDel, logicId)) {
bool hasData = iter.seekExact(physicId, &rec);
if (!hasData) {
fprintf(stderr
, "ERROR: %s:%d: logicId = %zd, physicId = %lld, logicNum = %zd, physicNum = %zd\n"
, __FILE__, __LINE__, logicId, physicId, logicNum, physicNum);
fflush(stderr);
abort(); // there are some bugs
}
// if (hasData && rec.empty()) {
// hasData = false;
// }
if (!rec.empty() && random() < sampleUpperBound) {
builder->addSample(rec);
sampled++;
}
newPhysicId++;
}
physicId++;
}
}
if (size_t(physicId) != physicNum) {
fprintf(stderr
, "ERROR: %s:%d: physicId != physicNum: physicId = %lld, physicNum = %zd, logicNum = %zd\n"
, __FILE__, __LINE__, physicId, physicNum, logicNum);
}
emptyCheckProtect(sampled, rec, *builder);
lock.lock(); // start lock
builder->prepare(newPhysicId, fpath.string());
iter.reset();
physicId = 0;
for (size_t logicId = 0; logicId < logicNum; ++logicId) {
if (!terark_bit_test(isPurgedptr, logicId)) {
llong physicId2 = -1;
bool hasData = iter.increment(&physicId2, &rec);
if (!hasData || physicId != physicId2) {
fprintf(stderr
, "ERROR: %s:%d: hasData = %d, logicId = %zd, physicId = %lld, physicId2 = %lld, physicNum = %zd, logicNum = %zd\n"
, __FILE__, __LINE__, hasData, logicId, physicId, physicId2, physicNum, logicNum);
fflush(stderr);
abort(); // there are some bugs
}
if (!terark_bit_test(isDel, logicId)) {
builder->addRecord(rec);
}
physicId++;
}
}
if (size_t(physicId) != physicNum) {
fprintf(stderr
, "ERROR: %s:%d: physicId != physicNum: physicId = %lld, physicNum = %zd, logicNum = %zd\n"
, __FILE__, __LINE__, physicId, physicNum, logicNum);
}
}
m_store.reset(builder->finish());
builder.reset(); // explicit destory builder, before lock.unlock
}
void NestLoudsTrieStore::load(PathRef path) {
std::string fpath = fstring(path.string()).endsWith(".nlt")
? path.string()
: path.string() + ".nlt";
m_store.reset(BlobStore::load_from(fpath, m_schema.m_mmapPopulate));
}
void NestLoudsTrieStore::save(PathRef path) const {
std::string fpath = fstring(path.string()).endsWith(".nlt")
? path.string()
: path.string() + ".nlt";
if (BaseDFA* dfa = dynamic_cast<BaseDFA*>(&*m_store)) {
dfa->save_mmap(fpath.c_str());
}
else if (auto zds = dynamic_cast<FastZipBlobStore*>(&*m_store)) {
zds->save_mmap(fpath);
}
else if (auto zds = dynamic_cast<DictZipBlobStore*>(&*m_store)) {
zds->save_mmap(fpath);
}
else {
THROW_STD(invalid_argument, "Unexpected");
}
}
}}} // namespace terark::db::dfadb
<|endoftext|> |
<commit_before>/*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011
*/
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "guiutil.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "addresstablemodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QLocale>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QDebug>
#include <iostream>
BitcoinGUI::BitcoinGUI(QWidget *parent):
QMainWindow(parent),
clientModel(0),
walletModel(0),
trayIcon(0)
{
resize(850, 550);
setWindowTitle(tr("Bitcoin Wallet"));
setWindowIcon(QIcon(":icons/bitcoin"));
createActions();
// Menus
QMenu *file = menuBar()->addMenu("&File");
file->addAction(sendCoinsAction);
file->addAction(receiveCoinsAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = menuBar()->addMenu("&Settings");
settings->addAction(optionsAction);
QMenu *help = menuBar()->addMenu("&Help");
help->addAction(aboutAction);
// Toolbar
QToolBar *toolbar = addToolBar("Main toolbar");
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
QToolBar *toolbar2 = addToolBar("Transactions toolbar");
toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar2->addAction(exportAction);
// Overview page
overviewPage = new OverviewPage();
QVBoxLayout *vbox = new QVBoxLayout();
transactionView = new TransactionView(this);
connect(transactionView, SIGNAL(doubleClicked(const QModelIndex&)), transactionView, SLOT(transactionDetails()));
vbox->addWidget(transactionView);
transactionsPage = new QWidget(this);
transactionsPage->setLayout(vbox);
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(this);
centralWidget = new QStackedWidget(this);
centralWidget->addWidget(overviewPage);
centralWidget->addWidget(transactionsPage);
centralWidget->addWidget(addressBookPage);
centralWidget->addWidget(receiveCoinsPage);
centralWidget->addWidget(sendCoinsPage);
setCentralWidget(centralWidget);
// Create status bar
statusBar();
labelConnections = new QLabel();
labelConnections->setFrameStyle(QFrame::Panel | QFrame::Sunken);
labelConnections->setMinimumWidth(150);
labelConnections->setMaximumWidth(150);
labelConnections->setToolTip(tr("Number of connections to other clients"));
labelBlocks = new QLabel();
labelBlocks->setFrameStyle(QFrame::Panel | QFrame::Sunken);
labelBlocks->setMinimumWidth(150);
labelBlocks->setMaximumWidth(150);
labelBlocks->setToolTip(tr("Number of blocks in the block chain"));
// Progress bar for blocks download
progressBarLabel = new QLabel(tr("Synchronizing with network..."));
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setToolTip(tr("Block chain synchronization in progress"));
progressBar->setVisible(false);
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(labelConnections);
statusBar()->addPermanentWidget(labelBlocks);
createTrayIcon();
gotoOverviewPage();
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setCheckable(true);
tabGroup->addAction(overviewAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setCheckable(true);
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setCheckable(true);
tabGroup->addAction(addressBookAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setCheckable(true);
tabGroup->addAction(receiveCoinsAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
sendCoinsAction->setToolTip(tr("Send coins to a bitcoin address"));
sendCoinsAction->setCheckable(true);
tabGroup->addAction(sendCoinsAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("&Exit"), this);
quitAction->setToolTip(tr("Quit application"));
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About"), this);
aboutAction->setToolTip(tr("Show information about Bitcoin"));
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setToolTip(tr("Modify configuration options for bitcoin"));
openBitcoinAction = new QAction(QIcon(":/icons/bitcoin"), tr("Open &Bitcoin"), this);
openBitcoinAction->setToolTip(tr("Show the Bitcoin window"));
exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
exportAction->setToolTip(tr("Export data in current view to a file"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(openBitcoinAction, SIGNAL(triggered()), this, SLOT(show()));
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel->isTestNet())
{
QString title_testnet = windowTitle() + QString(" ") + tr("[testnet]");
setWindowTitle(title_testnet);
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
if(trayIcon)
{
trayIcon->setToolTip(title_testnet);
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
}
}
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks());
connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
// Report errors from network/worker thread
connect(clientModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
}
void BitcoinGUI::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
// Report errors from wallet thread
connect(walletModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
// Balloon popup for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
this, SLOT(incomingTransaction(const QModelIndex &, int, int)));
}
void BitcoinGUI::createTrayIcon()
{
QMenu *trayIconMenu = new QMenu(this);
trayIconMenu->addAction(openBitcoinAction);
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(optionsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setToolTip("Bitcoin client");
trayIcon->setIcon(QIcon(":/icons/toolbar"));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->show();
}
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::DoubleClick)
{
// Doubleclick on system tray icon triggers "open bitcoin"
openBitcoinAction->trigger();
}
}
void BitcoinGUI::optionsClicked()
{
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnections->setTextFormat(Qt::RichText);
labelConnections->setText("<img src=\""+icon+"\"> " + tr("%n connection(s)", "", count));
}
void BitcoinGUI::setNumBlocks(int count)
{
int total = clientModel->getTotalBlocksEstimate();
if(count < total)
{
progressBarLabel->setVisible(true);
progressBar->setVisible(true);
progressBar->setMaximum(total);
progressBar->setValue(count);
}
else
{
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
QDateTime now = QDateTime::currentDateTime();
QDateTime lastBlockDate = clientModel->getLastBlockDate();
int secs = lastBlockDate.secsTo(now);
QString text;
QString icon = ":/icons/notsynced";
// "Up to date" icon, and outdated icon
if(secs < 30*60)
{
text = "Up to date";
icon = ":/icons/synced";
}
else if(secs < 60*60)
{
text = tr("%n minute(s) ago","",secs/60);
}
else if(secs < 24*60*60)
{
text = tr("%n hour(s) ago","",secs/(60*60));
}
else
{
text = tr("%n day(s) ago","",secs/(60*60*24));
}
labelBlocks->setText("<img src=\""+icon+"\"> " + text);
labelBlocks->setToolTip(tr("Downloaded %n block(s) of transaction history. Last block was generated %1.", "", count)
.arg(QLocale::system().toString(lastBlockDate)));
}
void BitcoinGUI::error(const QString &title, const QString &message)
{
// Report errors from network/worker thread
if(trayIcon->supportsMessages())
{
// Show as "balloon" message if possible
trayIcon->showMessage(title, message, QSystemTrayIcon::Critical);
}
else
{
// Fall back to old fashioned popup dialog if not
QMessageBox::critical(this, title,
message,
QMessageBox::Ok, QMessageBox::Ok);
}
}
void BitcoinGUI::changeEvent(QEvent *e)
{
if (e->type() == QEvent::WindowStateChange)
{
if(clientModel->getOptionsModel()->getMinimizeToTray())
{
if (isMinimized())
{
hide();
e->ignore();
}
else
{
e->accept();
}
}
}
QMainWindow::changeEvent(e);
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
qApp->quit();
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage =
tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(GUIUtil::formatMoney(nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Sending..."), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
{
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
.data(Qt::EditRole).toULongLong();
if(amount>0 && !clientModel->inInitialBlockDownload())
{
// On incoming transaction, make an info balloon
// Unless the initial block download is in progress, to prevent balloon-spam
QString date = ttm->index(start, TransactionTableModel::Date, parent)
.data().toString();
QString type = ttm->index(start, TransactionTableModel::Type, parent)
.data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
.data().toString();
trayIcon->showMessage(tr("Incoming transaction"),
tr("Date: ") + date + "\n" +
tr("Amount: ") + GUIUtil::formatMoney(amount, true) + "\n" +
tr("Type: ") + type + "\n" +
tr("Address: ") + address + "\n",
QSystemTrayIcon::Information);
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
centralWidget->setCurrentWidget(overviewPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
centralWidget->setCurrentWidget(transactionsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
}
void BitcoinGUI::gotoAddressBookPage()
{
addressBookAction->setChecked(true);
centralWidget->setCurrentWidget(addressBookPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(receiveCoinsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoSendCoinsPage()
{
sendCoinsAction->setChecked(true);
sendCoinsPage->clear();
centralWidget->setCurrentWidget(sendCoinsPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
<commit_msg>also show balloon on sent transaction, to notify when coins sent<commit_after>/*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011
*/
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "guiutil.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "addresstablemodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QLocale>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QDebug>
#include <iostream>
BitcoinGUI::BitcoinGUI(QWidget *parent):
QMainWindow(parent),
clientModel(0),
walletModel(0),
trayIcon(0)
{
resize(850, 550);
setWindowTitle(tr("Bitcoin Wallet"));
setWindowIcon(QIcon(":icons/bitcoin"));
createActions();
// Menus
QMenu *file = menuBar()->addMenu("&File");
file->addAction(sendCoinsAction);
file->addAction(receiveCoinsAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = menuBar()->addMenu("&Settings");
settings->addAction(optionsAction);
QMenu *help = menuBar()->addMenu("&Help");
help->addAction(aboutAction);
// Toolbar
QToolBar *toolbar = addToolBar("Main toolbar");
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
QToolBar *toolbar2 = addToolBar("Transactions toolbar");
toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar2->addAction(exportAction);
// Overview page
overviewPage = new OverviewPage();
QVBoxLayout *vbox = new QVBoxLayout();
transactionView = new TransactionView(this);
connect(transactionView, SIGNAL(doubleClicked(const QModelIndex&)), transactionView, SLOT(transactionDetails()));
vbox->addWidget(transactionView);
transactionsPage = new QWidget(this);
transactionsPage->setLayout(vbox);
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(this);
centralWidget = new QStackedWidget(this);
centralWidget->addWidget(overviewPage);
centralWidget->addWidget(transactionsPage);
centralWidget->addWidget(addressBookPage);
centralWidget->addWidget(receiveCoinsPage);
centralWidget->addWidget(sendCoinsPage);
setCentralWidget(centralWidget);
// Create status bar
statusBar();
labelConnections = new QLabel();
labelConnections->setFrameStyle(QFrame::Panel | QFrame::Sunken);
labelConnections->setMinimumWidth(150);
labelConnections->setMaximumWidth(150);
labelConnections->setToolTip(tr("Number of connections to other clients"));
labelBlocks = new QLabel();
labelBlocks->setFrameStyle(QFrame::Panel | QFrame::Sunken);
labelBlocks->setMinimumWidth(150);
labelBlocks->setMaximumWidth(150);
labelBlocks->setToolTip(tr("Number of blocks in the block chain"));
// Progress bar for blocks download
progressBarLabel = new QLabel(tr("Synchronizing with network..."));
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setToolTip(tr("Block chain synchronization in progress"));
progressBar->setVisible(false);
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(labelConnections);
statusBar()->addPermanentWidget(labelBlocks);
createTrayIcon();
gotoOverviewPage();
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setCheckable(true);
tabGroup->addAction(overviewAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setCheckable(true);
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setCheckable(true);
tabGroup->addAction(addressBookAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setCheckable(true);
tabGroup->addAction(receiveCoinsAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
sendCoinsAction->setToolTip(tr("Send coins to a bitcoin address"));
sendCoinsAction->setCheckable(true);
tabGroup->addAction(sendCoinsAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("&Exit"), this);
quitAction->setToolTip(tr("Quit application"));
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About"), this);
aboutAction->setToolTip(tr("Show information about Bitcoin"));
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setToolTip(tr("Modify configuration options for bitcoin"));
openBitcoinAction = new QAction(QIcon(":/icons/bitcoin"), tr("Open &Bitcoin"), this);
openBitcoinAction->setToolTip(tr("Show the Bitcoin window"));
exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
exportAction->setToolTip(tr("Export data in current view to a file"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(openBitcoinAction, SIGNAL(triggered()), this, SLOT(show()));
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel->isTestNet())
{
QString title_testnet = windowTitle() + QString(" ") + tr("[testnet]");
setWindowTitle(title_testnet);
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
if(trayIcon)
{
trayIcon->setToolTip(title_testnet);
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
}
}
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks());
connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(setNumBlocks(int)));
// Report errors from network/worker thread
connect(clientModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
}
void BitcoinGUI::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
// Report errors from wallet thread
connect(walletModel, SIGNAL(error(QString,QString)), this, SLOT(error(QString,QString)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
// Balloon popup for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(const QModelIndex &, int, int)),
this, SLOT(incomingTransaction(const QModelIndex &, int, int)));
}
void BitcoinGUI::createTrayIcon()
{
QMenu *trayIconMenu = new QMenu(this);
trayIconMenu->addAction(openBitcoinAction);
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(optionsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setToolTip("Bitcoin client");
trayIcon->setIcon(QIcon(":/icons/toolbar"));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->show();
}
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::DoubleClick)
{
// Doubleclick on system tray icon triggers "open bitcoin"
openBitcoinAction->trigger();
}
}
void BitcoinGUI::optionsClicked()
{
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnections->setTextFormat(Qt::RichText);
labelConnections->setText("<img src=\""+icon+"\"> " + tr("%n connection(s)", "", count));
}
void BitcoinGUI::setNumBlocks(int count)
{
int total = clientModel->getTotalBlocksEstimate();
if(count < total)
{
progressBarLabel->setVisible(true);
progressBar->setVisible(true);
progressBar->setMaximum(total);
progressBar->setValue(count);
}
else
{
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
QDateTime now = QDateTime::currentDateTime();
QDateTime lastBlockDate = clientModel->getLastBlockDate();
int secs = lastBlockDate.secsTo(now);
QString text;
QString icon = ":/icons/notsynced";
// "Up to date" icon, and outdated icon
if(secs < 30*60)
{
text = "Up to date";
icon = ":/icons/synced";
}
else if(secs < 60*60)
{
text = tr("%n minute(s) ago","",secs/60);
}
else if(secs < 24*60*60)
{
text = tr("%n hour(s) ago","",secs/(60*60));
}
else
{
text = tr("%n day(s) ago","",secs/(60*60*24));
}
labelBlocks->setText("<img src=\""+icon+"\"> " + text);
labelBlocks->setToolTip(tr("Downloaded %n block(s) of transaction history. Last block was generated %1.", "", count)
.arg(QLocale::system().toString(lastBlockDate)));
}
void BitcoinGUI::error(const QString &title, const QString &message)
{
// Report errors from network/worker thread
if(trayIcon->supportsMessages())
{
// Show as "balloon" message if possible
trayIcon->showMessage(title, message, QSystemTrayIcon::Critical);
}
else
{
// Fall back to old fashioned popup dialog if not
QMessageBox::critical(this, title,
message,
QMessageBox::Ok, QMessageBox::Ok);
}
}
void BitcoinGUI::changeEvent(QEvent *e)
{
if (e->type() == QEvent::WindowStateChange)
{
if(clientModel->getOptionsModel()->getMinimizeToTray())
{
if (isMinimized())
{
hide();
e->ignore();
}
else
{
e->accept();
}
}
}
QMainWindow::changeEvent(e);
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
qApp->quit();
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage =
tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(GUIUtil::formatMoney(nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Sending..."), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
{
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
.data(Qt::EditRole).toULongLong();
if(!clientModel->inInitialBlockDownload())
{
// On incoming transaction, make an info balloon
// Unless the initial block download is in progress, to prevent balloon-spam
QString date = ttm->index(start, TransactionTableModel::Date, parent)
.data().toString();
QString type = ttm->index(start, TransactionTableModel::Type, parent)
.data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
.data().toString();
trayIcon->showMessage((amount)<0 ? tr("Sent transaction") :
tr("Incoming transaction"),
tr("Date: ") + date + "\n" +
tr("Amount: ") + GUIUtil::formatMoney(amount, true) + "\n" +
tr("Type: ") + type + "\n" +
tr("Address: ") + address + "\n",
QSystemTrayIcon::Information);
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
centralWidget->setCurrentWidget(overviewPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
centralWidget->setCurrentWidget(transactionsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
}
void BitcoinGUI::gotoAddressBookPage()
{
addressBookAction->setChecked(true);
centralWidget->setCurrentWidget(addressBookPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(receiveCoinsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoSendCoinsPage()
{
sendCoinsAction->setChecked(true);
sendCoinsPage->clear();
centralWidget->setCurrentWidget(sendCoinsPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/tonalutils.h>
#include <QFont>
#include <QFontMetrics>
#include <QRegExp>
#include <QRegExpValidator>
#include <QString>
static const QList<QChar> tonal_digits{0xe9df, 0xe9de, 0xe9dd, 0xe9dc, 0xe9db, 0xe9da, 0xe9d9, '8', '7', '6', '5', '4', '3', '2', '1', '0'};
namespace {
bool font_supports_tonal(const QFont& font)
{
const QFontMetrics fm(font);
QString s = "000";
const QSize sz = fm.size(0, s);
for (const auto& c : tonal_digits) {
if (!fm.inFont(c)) return false;
s[0] = s[1] = s[2] = c;
if (sz != fm.size(0, s)) return false;
}
return true;
}
} // anon namespace
bool TonalUtils::Supported()
{
QFont default_font;
if (font_supports_tonal(default_font)) return true;
QFont last_resort_font(default_font.lastResortFamily());
if (font_supports_tonal(last_resort_font)) return true;
return false;
}
#define RE_TONAL_DIGIT "[\\d\\xe8e0-\\xe8ef\\xe9d0-\\xe9df]"
static QRegExpValidator tv(QRegExp("-?(?:" RE_TONAL_DIGIT "+\\.?|" RE_TONAL_DIGIT "*\\." RE_TONAL_DIGIT "*)"), NULL);
QValidator::State TonalUtils::validate(QString&input, int&pos)
{
return tv.validate(input, pos);
}
void TonalUtils::ConvertFromHex(QString&str)
{
for (int i = 0; i < str.size(); ++i)
{
ushort c = str[i].unicode();
if (c == '9')
str[i] = 0xe9d9;
else
if (c >= 'A' && c <= 'F')
str[i] = c + 0xe999;
else
if (c >= 'a' && c <= 'f')
str[i] = c + 0xe979;
}
}
void TonalUtils::ConvertToHex(QString&str)
{
for (int i = 0; i < str.size(); ++i)
{
ushort c = str[i].unicode();
if (c == '9')
str[i] = 'a';
else
if (c >= 0xe8e0 && c <= 0xe8e9) { // UCSUR 0-9
str[i] = c - (0xe8e0 - '0');
} else if (c >= 0xe8ea && c <= 0xe8ef) { // UCSUR a-f
str[i] = c - (0xe8ea - 'a');
} else if (c >= 0xe9d0 && c <= 0xe9d9) {
str[i] = c - (0xe9d0 - '0');
} else
if (c >= 0xe9da && c <= 0xe9df)
str[i] = c - 0xe999;
}
}
<commit_msg>qt/tonalutils: Use UCSUR codepoints for Tonal output<commit_after>// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/tonalutils.h>
#include <QFont>
#include <QFontMetrics>
#include <QRegExp>
#include <QRegExpValidator>
#include <QString>
static const QList<QChar> tonal_digits{0xe8ef, 0xe8ee, 0xe8ed, 0xe8ec, 0xe8eb, 0xe8ea, 0xe8e9, '8', '7', '6', '5', '4', '3', '2', '1', '0'};
namespace {
bool font_supports_tonal(const QFont& font)
{
const QFontMetrics fm(font);
QString s = "000";
const QSize sz = fm.size(0, s);
for (const auto& c : tonal_digits) {
if (!fm.inFont(c)) return false;
s[0] = s[1] = s[2] = c;
if (sz != fm.size(0, s)) return false;
}
return true;
}
} // anon namespace
bool TonalUtils::Supported()
{
QFont default_font;
if (font_supports_tonal(default_font)) return true;
QFont last_resort_font(default_font.lastResortFamily());
if (font_supports_tonal(last_resort_font)) return true;
return false;
}
#define RE_TONAL_DIGIT "[\\d\\xe8e0-\\xe8ef\\xe9d0-\\xe9df]"
static QRegExpValidator tv(QRegExp("-?(?:" RE_TONAL_DIGIT "+\\.?|" RE_TONAL_DIGIT "*\\." RE_TONAL_DIGIT "*)"), NULL);
QValidator::State TonalUtils::validate(QString&input, int&pos)
{
return tv.validate(input, pos);
}
void TonalUtils::ConvertFromHex(QString&str)
{
for (int i = 0; i < str.size(); ++i)
{
ushort c = str[i].unicode();
if (c == '9')
str[i] = 0xe8e9;
else
if (c >= 'A' && c <= 'F')
str[i] = c + (0xe8ea - 'A');
else
if (c >= 'a' && c <= 'f')
str[i] = c + (0xe8ea - 'a');
}
}
void TonalUtils::ConvertToHex(QString&str)
{
for (int i = 0; i < str.size(); ++i)
{
ushort c = str[i].unicode();
if (c == '9')
str[i] = 'a';
else
if (c >= 0xe8e0 && c <= 0xe8e9) { // UCSUR 0-9
str[i] = c - (0xe8e0 - '0');
} else if (c >= 0xe8ea && c <= 0xe8ef) { // UCSUR a-f
str[i] = c - (0xe8ea - 'a');
} else if (c >= 0xe9d0 && c <= 0xe9d9) {
str[i] = c - (0xe9d0 - '0');
} else
if (c >= 0xe9da && c <= 0xe9df)
str[i] = c - 0xe999;
}
}
<|endoftext|> |
<commit_before>#include "okui/shaders/DistanceFieldShader.h"
namespace okui {
namespace shaders {
std::string DistanceFieldShader::FragmentShader() {
bool useStandardDerivatives = !scraps::opengl::kIsOpenGLES || scraps::opengl::MajorVersion() >= 3;
std::vector<std::string> extensions;
if (!useStandardDerivatives && scraps::opengl::HasExtension("GL_OES_standard_derivatives")) {
useStandardDerivatives = true;
extensions.emplace_back("GL_OES_standard_derivatives");
}
return CommonOKUIFragmentShaderHeader(extensions) +
R"(
VARYING_IN vec4 color;
VARYING_IN vec2 textureCoord;
uniform sampler2D textureSampler;
uniform float edge;
uniform bool supersample;
void main() {
vec4 sample = SAMPLE(textureSampler, textureCoord);
float aa = )" + (useStandardDerivatives ? "fwidth(sample.a) * 0.75;" : "0.03") + R"(
float alpha = smoothstep(edge - aa, edge + aa, sample.a);
if (supersample) {
vec2 derivUV = )" + (useStandardDerivatives ? "0.35355 * (dFdx(textureCoord) + dFdy(textureCoord));" : "vec2(0.002, 0.0015);") + R"(
vec4 box = vec4(textureCoord-derivUV, textureCoord+derivUV);
float sum = smoothstep(edge - aa, edge + aa, SAMPLE(textureSampler, box.xy).a)
+ smoothstep(edge - aa, edge + aa, SAMPLE(textureSampler, box.zw).a)
+ smoothstep(edge - aa, edge + aa, SAMPLE(textureSampler, box.xw).a)
+ smoothstep(edge - aa, edge + aa, SAMPLE(textureSampler, box.zy).a);
// Weighted average of the other points with the center point: give each of the 4 supersampled points
// a 0.5 weight, and the center a wieght of 1, so the total is 0.5*4 + 1 = 3
alpha = (alpha + 0.5 * sum) / 3.0;
}
COLOR_OUT = multipliedOutput(vec4(color.rgb, color.a * alpha));
}
)";
}
DistanceFieldShader::DistanceFieldShader() : TextureShader(FragmentShader()) {
_program.use();
_edgeUniform = _program.uniform("edge");
_supersampleUniform = _program.uniform("supersample");
}
void DistanceFieldShader::flush() {
_program.use();
_edgeUniform = (GLfloat)_edge;
_supersampleUniform = (GLboolean)_supersample;
TextureShader::flush();
}
} } // namespace okui::shaders
<commit_msg>fix shader on fire stick<commit_after>#include "okui/shaders/DistanceFieldShader.h"
namespace okui {
namespace shaders {
std::string DistanceFieldShader::FragmentShader() {
bool useStandardDerivatives = !scraps::opengl::kIsOpenGLES || scraps::opengl::MajorVersion() >= 3;
std::vector<std::string> extensions;
if (!useStandardDerivatives && scraps::opengl::HasExtension("GL_OES_standard_derivatives")) {
useStandardDerivatives = true;
extensions.emplace_back("GL_OES_standard_derivatives");
}
return CommonOKUIFragmentShaderHeader(extensions) +
R"(
VARYING_IN vec4 color;
VARYING_IN vec2 textureCoord;
uniform sampler2D textureSampler;
uniform float edge;
uniform bool supersample;
void main() {
vec4 sample = SAMPLE(textureSampler, textureCoord);
float aa = )" + (useStandardDerivatives ? "fwidth(sample.a) * 0.75" : "0.03") + R"(;
float alpha = smoothstep(edge - aa, edge + aa, sample.a);
if (supersample) {
vec2 derivUV = )" + (useStandardDerivatives ? "0.35355 * (dFdx(textureCoord) + dFdy(textureCoord));" : "vec2(0.002, 0.0015);") + R"(
vec4 box = vec4(textureCoord-derivUV, textureCoord+derivUV);
float sum = smoothstep(edge - aa, edge + aa, SAMPLE(textureSampler, box.xy).a)
+ smoothstep(edge - aa, edge + aa, SAMPLE(textureSampler, box.zw).a)
+ smoothstep(edge - aa, edge + aa, SAMPLE(textureSampler, box.xw).a)
+ smoothstep(edge - aa, edge + aa, SAMPLE(textureSampler, box.zy).a);
// Weighted average of the other points with the center point: give each of the 4 supersampled points
// a 0.5 weight, and the center a wieght of 1, so the total is 0.5*4 + 1 = 3
alpha = (alpha + 0.5 * sum) / 3.0;
}
COLOR_OUT = multipliedOutput(vec4(color.rgb, color.a * alpha));
}
)";
}
DistanceFieldShader::DistanceFieldShader() : TextureShader(FragmentShader()) {
_program.use();
_edgeUniform = _program.uniform("edge");
_supersampleUniform = _program.uniform("supersample");
}
void DistanceFieldShader::flush() {
_program.use();
_edgeUniform = (GLfloat)_edge;
_supersampleUniform = (GLboolean)_supersample;
TextureShader::flush();
}
} } // namespace okui::shaders
<|endoftext|> |
<commit_before>/*
Copyright 2016 Mitchell Young
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.
*/
#pragma once
#include "core/core_mesh.hpp"
#include "util/h5file.hpp"
#include "util/pugifwd.hpp"
#include "core/source.hpp"
#include "core/transport_sweeper.hpp"
#include "solver.hpp"
namespace mocc {
class FixedSourceSolver : public Solver {
public:
/**
* Initialize a FSS using an XML node and CoreMesh. This expects the passed
* XML node to be a valid \<solver\> tag containing a relevant \<sweeper\>
* tag, which is needed by the \ref TransportSweeperFactory() to generate a
* \ref TransportSweeper.
*/
FixedSourceSolver(const pugi::xml_node &input, const CoreMesh &mesh);
~FixedSourceSolver()
{
}
/**
* For now, there is no actual implementation of this method, since there is
* no functionality for specifying a user-defined Source. In practice, the
* FSS is driven via the \ref step() routine by the \ref EigenSolver.
*
* Ideally, this would solve a fixed source problem subject to the
* configuration in the XML input. This can either be to some sort of
* tolerance, or for a fixed number of group sweeps.
*/
void solve();
/**
* Instructs the sweeper to store the old value of the flux, then performs a
* group sweep.
*/
void step();
/**
* Initialize the state of the FSS to start a new problem. For now this just
* calls the same routine on the \ref TransportSweeper, which in turn
* initializes the scalar flux, boundary conditions, etc. to some sort of
* halfway-reasonable starting values.
*/
void initialize()
{
sweeper_->initialize();
}
/**
* Set the group-independent fission source. The group-dependent fission
* source is calculated internally by the \ref Source object, typically at
* the behest of an \ref EigenSolver
*/
void set_fission_source(const ArrayB1 *fs)
{
assert((int)fs->size() == sweeper()->n_reg());
fs_ = fs;
}
/**
* Return the number of mesh regions.
*/
unsigned int n_reg()
{
return sweeper_->n_reg();
}
/**
* Return the number of energy groups
*/
unsigned int n_group()
{
return ng_;
}
const TransportSweeper *sweeper() const
{
return sweeper_.get();
}
/**
* Return a pointer to the the \ref TransportSweeper. Use with care.
*/
TransportSweeper *sweeper()
{
return sweeper_.get();
}
void output(H5Node &node) const;
private:
UP_Sweeper_t sweeper_;
UP_Source_t source_;
// Pointer to the group-independent fission source. Usually comes from an
// eigenvalue solver, if present
const ArrayB1 *fs_;
size_t ng_;
// Stuff that we should only need if we are doing a standalone FS solve
bool fixed_source_;
size_t max_iter_;
real_t flux_tol_;
};
}
<commit_msg>Use n_reg_fission() in FSS<commit_after>/*
Copyright 2016 Mitchell Young
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.
*/
#pragma once
#include "core/core_mesh.hpp"
#include "util/h5file.hpp"
#include "util/pugifwd.hpp"
#include "core/source.hpp"
#include "core/transport_sweeper.hpp"
#include "solver.hpp"
namespace mocc {
class FixedSourceSolver : public Solver {
public:
/**
* Initialize a FSS using an XML node and CoreMesh. This expects the passed
* XML node to be a valid \<solver\> tag containing a relevant \<sweeper\>
* tag, which is needed by the \ref TransportSweeperFactory() to generate a
* \ref TransportSweeper.
*/
FixedSourceSolver(const pugi::xml_node &input, const CoreMesh &mesh);
~FixedSourceSolver()
{
}
/**
* For now, there is no actual implementation of this method, since there is
* no functionality for specifying a user-defined Source. In practice, the
* FSS is driven via the \ref step() routine by the \ref EigenSolver.
*
* Ideally, this would solve a fixed source problem subject to the
* configuration in the XML input. This can either be to some sort of
* tolerance, or for a fixed number of group sweeps.
*/
void solve();
/**
* Instructs the sweeper to store the old value of the flux, then performs a
* group sweep.
*/
void step();
/**
* Initialize the state of the FSS to start a new problem. For now this just
* calls the same routine on the \ref TransportSweeper, which in turn
* initializes the scalar flux, boundary conditions, etc. to some sort of
* halfway-reasonable starting values.
*/
void initialize()
{
sweeper_->initialize();
}
/**
* Set the group-independent fission source. The group-dependent fission
* source is calculated internally by the \ref Source object, typically at
* the behest of an \ref EigenSolver
*/
void set_fission_source(const ArrayB1 *fs)
{
assert((int)fs->size() == sweeper()->n_reg_fission());
fs_ = fs;
}
/**
* Return the number of mesh regions.
*/
unsigned int n_reg()
{
return sweeper_->n_reg();
}
/**
* Return the number of energy groups
*/
unsigned int n_group()
{
return ng_;
}
const TransportSweeper *sweeper() const
{
return sweeper_.get();
}
/**
* Return a pointer to the the \ref TransportSweeper. Use with care.
*/
TransportSweeper *sweeper()
{
return sweeper_.get();
}
void output(H5Node &node) const;
private:
UP_Sweeper_t sweeper_;
UP_Source_t source_;
// Pointer to the group-independent fission source. Usually comes from an
// eigenvalue solver, if present
const ArrayB1 *fs_;
size_t ng_;
// Stuff that we should only need if we are doing a standalone FS solve
bool fixed_source_;
size_t max_iter_;
real_t flux_tol_;
};
}
<|endoftext|> |
<commit_before>
#include <QScrollBar>
#include "cmd.h"
#include "editm.h"
#include "form.h"
#include "pane.h"
#include "wd.h"
#include "../base/plaintextedit.h"
#include "../base/state.h"
#ifndef QT_NO_PRINTER
#ifdef QT50
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrinterInfo>
#include <QtPrintSupport/QPrintPreviewDialog>
#else
#include <QPrinter>
#include <QPrinterInfo>
#include <QPrintPreviewDialog>
#endif
#endif
// ---------------------------------------------------------------------
Editm::Editm(string n, string s, Form *f, Pane *p) : Child(n,s,f,p)
{
type="editm";
EditmPTE *w=new EditmPTE;
w->pchild=this;
widget=(QWidget*) w;
QString qn=s2q(n);
QStringList opt=qsplit(s);
if (invalidopt(n,opt,"readonly selectable")) return;
w->setObjectName(qn);
childStyle(opt);
if (opt.contains("readonly")) {
w->setReadOnly(true);
if (opt.contains("selectable"))
w->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
}
}
// ---------------------------------------------------------------------
void Editm::cmd(string p,string v)
{
QStringList opt=qsplit(v);
if (p=="print") {
#ifndef QT_NO_PRINTER
((EditmPTE*) widget)->printPreview(config.Printer);
#endif
} else if (p=="printpreview") {
#ifndef QT_NO_PRINTER
QPrintPreviewDialog *dlg = new QPrintPreviewDialog(config.Printer, pform);
dlg->setWindowTitle("Preview Document");
QObject::connect(dlg,SIGNAL(paintRequested(QPrinter *)),((EditmPTE*) widget),SLOT(printPreview(QPrinter *)));
dlg->exec();
delete dlg;
config.Printer->setPrintRange(QPrinter::AllPages);
#endif
} else Child::set(p,v);
}
// ---------------------------------------------------------------------
string Editm::get(string p,string v)
{
EditmPTE *w=(EditmPTE*) widget;
string r;
if (p=="property") {
r+=string("limit")+"\012"+ "readonly"+"\012"+ "scroll"+"\012"+ "select"+"\012"+ "text"+"\012"+ "wrap"+"\012";
r+=Child::get(p,v);
} else if (p=="text")
r=q2s(w->toPlainText());
else if (p=="select"||p=="scroll") {
QTextCursor c=w->textCursor();
int b,e;
b=c.selectionStart();
e=c.selectionEnd();
QScrollBar *vb=w->verticalScrollBar();
if (p=="select")
r=i2s(b)+" "+i2s(e);
else
r=i2s(vb->value());
} else if (p=="limit")
r=i2s(w->maximumBlockCount());
else if (p=="readonly")
r=i2s(w->isReadOnly());
else if (p=="wrap")
r=i2s(w->lineWrapMode());
else
r=Child::get(p,v);
return r;
}
// ---------------------------------------------------------------------
void Editm::set(string p,string v)
{
EditmPTE *w=(EditmPTE*) widget;
string r;
QStringList opt=qsplit(v);
QScrollBar *sb;
int bgn,end,pos=0;
if (p=="limit") {
if (opt.isEmpty()) {
error("set limit requires 1 number: " + id + " " + p);
return;
}
w->setMaximumBlockCount(c_strtoi(q2s(opt.at(0))));
} else if (p=="readonly")
w->setReadOnly(remquotes(v)!="0");
else if (p=="text")
w->setPlainText(s2q(remquotes(v)));
else if (p=="select") {
if (opt.isEmpty())
w->selectAll();
else {
bgn=end=c_strtoi(q2s(opt.at(0)));
if (opt.size()>1)
end=c_strtoi(q2s(opt.at(1)));
setselect(w,bgn,end);
}
} else if (p=="scroll") {
if (opt.size()) {
sb=w->verticalScrollBar();
if (opt.at(0)=="min")
pos=sb->minimum();
else if (opt.at(0)=="max")
pos=sb->maximum();
else
pos=c_strtoi(q2s(opt.at(0)));
sb->setValue(pos);
} else {
error("set scroll requires additional parameters: " + id + " " + p);
return;
}
} else if (p=="wrap") {
w->setLineWrapMode((remquotes(v)!="0")?PlainTextEdit::WidgetWidth:PlainTextEdit::NoWrap);
} else if (p=="find") {
w->find(opt.at(0));
} else Child::set(p,v);
}
// ---------------------------------------------------------------------
void Editm::setselect(PlainTextEdit *w, int bgn, int end)
{
QTextCursor c = w->textCursor();
c.setPosition(end,QTextCursor::MoveAnchor);
c.setPosition(bgn,QTextCursor::KeepAnchor);
w->setTextCursor(c);
}
// ---------------------------------------------------------------------
string Editm::state()
{
EditmPTE *w=(EditmPTE*) widget;
QTextCursor c=w->textCursor();
int b,e;
b=c.selectionStart();
e=c.selectionEnd();
QScrollBar *v=w->verticalScrollBar();
string r;
r+=spair(id,q2s(w->toPlainText()));
r+=spair(id+"_select",i2s(b)+" "+i2s(e));
r+=spair(id+"_scroll",i2s(v->value()));
return r;
}
// ---------------------------------------------------------------------
EditmPTE::EditmPTE(QWidget *parent) : PlainTextEdit(parent) {}
// ---------------------------------------------------------------------
void EditmPTE::keyPressEvent(QKeyEvent *event)
{
int key=event->key();
if (ismodifier(key)) return;
if ((key==Qt::Key_Enter || key==Qt::Key_Return) && !(event->modifiers() & Qt::CTRL) && !(event->modifiers() & Qt::SHIFT)) {
if (isReadOnly()) {
char sysmodifiers[20];
sprintf(sysmodifiers , "%d", (2*(!!(event->modifiers() & Qt::CTRL))) + (!!(event->modifiers() & Qt::SHIFT)));
pchild->event=string("button");
pchild->sysmodifiers=string(sysmodifiers);
pchild->pform->signalevent(pchild);
return;
}
}
int key1=0;
if ((key>0x10000ff)||((key>=Qt::Key_F1)&&(key<=Qt::Key_F35))) {
PlainTextEdit::keyPressEvent(event);
return;
} else
key1=translateqkey(key);
char sysmodifiers[20];
int sysmod = (2*(!!(event->modifiers() & Qt::CTRL))) + (!!(event->modifiers() & Qt::SHIFT));
if (!(2 & sysmod)) { // Ctrl+anything becomes (possibly) a _fkey event; others become _char
sprintf(sysmodifiers , "%d", sysmod);
char sysdata[20];
if (key==key1)
sprintf(sysdata , "%s", event->text().toUtf8().constData());
else sprintf(sysdata , "%s", QString(QChar(key1)).toUtf8().constData());
pchild->event=string("char");
pchild->sysmodifiers=string(sysmodifiers);
pchild->sysdata=string(sysdata);
pchild->pform->signalevent(pchild);
PlainTextEdit::keyPressEvent(event);
}
}
<commit_msg>Remove _char event from editm<commit_after>
#include <QScrollBar>
#include "cmd.h"
#include "editm.h"
#include "form.h"
#include "pane.h"
#include "wd.h"
#include "../base/plaintextedit.h"
#include "../base/state.h"
#ifndef QT_NO_PRINTER
#ifdef QT50
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrinterInfo>
#include <QtPrintSupport/QPrintPreviewDialog>
#else
#include <QPrinter>
#include <QPrinterInfo>
#include <QPrintPreviewDialog>
#endif
#endif
// ---------------------------------------------------------------------
Editm::Editm(string n, string s, Form *f, Pane *p) : Child(n,s,f,p)
{
type="editm";
EditmPTE *w=new EditmPTE;
w->pchild=this;
widget=(QWidget*) w;
QString qn=s2q(n);
QStringList opt=qsplit(s);
if (invalidopt(n,opt,"readonly selectable")) return;
w->setObjectName(qn);
childStyle(opt);
if (opt.contains("readonly")) {
w->setReadOnly(true);
if (opt.contains("selectable"))
w->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
}
}
// ---------------------------------------------------------------------
void Editm::cmd(string p,string v)
{
QStringList opt=qsplit(v);
if (p=="print") {
#ifndef QT_NO_PRINTER
((EditmPTE*) widget)->printPreview(config.Printer);
#endif
} else if (p=="printpreview") {
#ifndef QT_NO_PRINTER
QPrintPreviewDialog *dlg = new QPrintPreviewDialog(config.Printer, pform);
dlg->setWindowTitle("Preview Document");
QObject::connect(dlg,SIGNAL(paintRequested(QPrinter *)),((EditmPTE*) widget),SLOT(printPreview(QPrinter *)));
dlg->exec();
delete dlg;
config.Printer->setPrintRange(QPrinter::AllPages);
#endif
} else Child::set(p,v);
}
// ---------------------------------------------------------------------
string Editm::get(string p,string v)
{
EditmPTE *w=(EditmPTE*) widget;
string r;
if (p=="property") {
r+=string("limit")+"\012"+ "readonly"+"\012"+ "scroll"+"\012"+ "select"+"\012"+ "text"+"\012"+ "wrap"+"\012";
r+=Child::get(p,v);
} else if (p=="text")
r=q2s(w->toPlainText());
else if (p=="select"||p=="scroll") {
QTextCursor c=w->textCursor();
int b,e;
b=c.selectionStart();
e=c.selectionEnd();
QScrollBar *vb=w->verticalScrollBar();
if (p=="select")
r=i2s(b)+" "+i2s(e);
else
r=i2s(vb->value());
} else if (p=="limit")
r=i2s(w->maximumBlockCount());
else if (p=="readonly")
r=i2s(w->isReadOnly());
else if (p=="wrap")
r=i2s(w->lineWrapMode());
else
r=Child::get(p,v);
return r;
}
// ---------------------------------------------------------------------
void Editm::set(string p,string v)
{
EditmPTE *w=(EditmPTE*) widget;
string r;
QStringList opt=qsplit(v);
QScrollBar *sb;
int bgn,end,pos=0;
if (p=="limit") {
if (opt.isEmpty()) {
error("set limit requires 1 number: " + id + " " + p);
return;
}
w->setMaximumBlockCount(c_strtoi(q2s(opt.at(0))));
} else if (p=="readonly")
w->setReadOnly(remquotes(v)!="0");
else if (p=="text")
w->setPlainText(s2q(remquotes(v)));
else if (p=="select") {
if (opt.isEmpty())
w->selectAll();
else {
bgn=end=c_strtoi(q2s(opt.at(0)));
if (opt.size()>1)
end=c_strtoi(q2s(opt.at(1)));
setselect(w,bgn,end);
}
} else if (p=="scroll") {
if (opt.size()) {
sb=w->verticalScrollBar();
if (opt.at(0)=="min")
pos=sb->minimum();
else if (opt.at(0)=="max")
pos=sb->maximum();
else
pos=c_strtoi(q2s(opt.at(0)));
sb->setValue(pos);
} else {
error("set scroll requires additional parameters: " + id + " " + p);
return;
}
} else if (p=="wrap") {
w->setLineWrapMode((remquotes(v)!="0")?PlainTextEdit::WidgetWidth:PlainTextEdit::NoWrap);
} else if (p=="find") {
w->find(opt.at(0));
} else Child::set(p,v);
}
// ---------------------------------------------------------------------
void Editm::setselect(PlainTextEdit *w, int bgn, int end)
{
QTextCursor c = w->textCursor();
c.setPosition(end,QTextCursor::MoveAnchor);
c.setPosition(bgn,QTextCursor::KeepAnchor);
w->setTextCursor(c);
}
// ---------------------------------------------------------------------
string Editm::state()
{
EditmPTE *w=(EditmPTE*) widget;
QTextCursor c=w->textCursor();
int b,e;
b=c.selectionStart();
e=c.selectionEnd();
QScrollBar *v=w->verticalScrollBar();
string r;
r+=spair(id,q2s(w->toPlainText()));
r+=spair(id+"_select",i2s(b)+" "+i2s(e));
r+=spair(id+"_scroll",i2s(v->value()));
return r;
}
// ---------------------------------------------------------------------
EditmPTE::EditmPTE(QWidget *parent) : PlainTextEdit(parent) {}
// ---------------------------------------------------------------------
void EditmPTE::keyPressEvent(QKeyEvent *event)
{
int key=event->key();
if (ismodifier(key)) return;
if ((key==Qt::Key_Enter || key==Qt::Key_Return) && !(event->modifiers() & Qt::CTRL) && !(event->modifiers() & Qt::SHIFT)) {
if (isReadOnly()) {
char sysmodifiers[20];
sprintf(sysmodifiers , "%d", (2*(!!(event->modifiers() & Qt::CTRL))) + (!!(event->modifiers() & Qt::SHIFT)));
pchild->event=string("button");
pchild->sysmodifiers=string(sysmodifiers);
pchild->pform->signalevent(pchild);
return;
// note we don't fall through to handle keyPressEvent in the widget.
// it shouldn't do anything but move the cursor, and we have already jabbed the
// _button event, so don't let the widget override something the button calls for
}
}
// _char events not given from editm now, so just pass the event on
PlainTextEdit::keyPressEvent(event);
}
<|endoftext|> |
<commit_before>/**************************************************************************
Copyright (c) 2021 sewenew
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 "async_connection.h"
#include <hiredis/async.h>
#include "errors.h"
#include "async_shards_pool.h"
#include "cmd_formatter.h"
namespace {
using namespace sw::redis;
void set_options_callback(redisAsyncContext *ctx, void *r, void *) {
assert(ctx != nullptr);
auto *context = static_cast<AsyncContext *>(ctx->data);
assert(context != nullptr);
auto &connection = context->connection;
assert(connection);
redisReply *reply = static_cast<redisReply *>(r);
if (reply == nullptr) {
// Connection has bee closed.
// TODO: not sure if we should set this to be State::BROKEN
return;
}
try {
if (reply::is_error(*reply)) {
throw_error(*reply);
}
reply::parse<void>(*reply);
} catch (const Error &e) {
// TODO: disconnect and connect_callback might throw
connection->disconnect(std::make_exception_ptr(e));
return;
}
connection->connect_callback();
}
}
namespace sw {
namespace redis {
AsyncConnection::AsyncConnection(const ConnectionOptions &opts,
EventLoop *loop,
AsyncConnectionMode mode) :
_opts(opts),
_loop(loop),
_create_time(std::chrono::steady_clock::now()),
_last_active(std::chrono::steady_clock::now().time_since_epoch()) {
assert(_loop != nullptr);
switch (mode) {
case AsyncConnectionMode::SINGLE:
_state = State::NOT_CONNECTED;
break;
case AsyncConnectionMode::SENTINEL:
_state = State::WAIT_SENTINEL;
break;
default:
throw Error("not supporeted async connection mode");
break;
}
}
AsyncConnection::~AsyncConnection() {
_clean_up();
}
void AsyncConnection::send(AsyncEventUPtr event) {
{
std::lock_guard<std::mutex> lock(_mtx);
_events.push_back(std::move(event));
}
_loop->add(shared_from_this());
}
void AsyncConnection::event_callback() {
// NOTE: we should try our best not throw in these callbacks
switch (_state.load()) {
case State::WAIT_SENTINEL:
_connect_with_sentinel();
break;
case State::NOT_CONNECTED:
_connect();
break;
case State::READY:
_send();
break;
case State::BROKEN:
_clean_up();
break;
default:
break;
}
}
void AsyncConnection::connect_callback(std::exception_ptr err) {
if (err) {
// Failed to connect to Redis, fail all pending events.
_fail_events(err);
return;
}
// Connect OK.
try {
switch (_state.load()) {
case State::CONNECTING:
_connecting_callback();
break;
case State::AUTHING:
_authing_callback();
break;
case State::SELECTING_DB:
_select_db_callback();
break;
default:
assert(_state == State::ENABLE_READONLY);
_set_ready();
}
} catch (const Error &e) {
disconnect(std::make_exception_ptr(e));
}
}
void AsyncConnection::disconnect(std::exception_ptr err) {
if (_ctx != nullptr) {
_disable_disconnect_callback();
redisAsyncDisconnect(_ctx);
}
_fail_events(err);
}
void AsyncConnection::disconnect_callback(std::exception_ptr err) {
_fail_events(err);
}
ConnectionOptions AsyncConnection::options() {
std::lock_guard<std::mutex> lock(_mtx);
return _opts;
}
void AsyncConnection::update_node_info(const std::string &host, int port) {
std::lock_guard<std::mutex> lock(_mtx);
_opts.host = host;
_opts.port = port;
}
void AsyncConnection::_disable_disconnect_callback() {
assert(_ctx != nullptr);
auto *ctx = static_cast<AsyncContext *>(_ctx->data);
assert(ctx != nullptr);
ctx->run_disconnect_callback = false;
}
void AsyncConnection::_send() {
auto events = _get_events();
auto &ctx = _context();
for (auto idx = 0U; idx != events.size(); ++idx) {
auto &event = events[idx];
try {
if (event->handle(ctx)) {
// CommandEvent::_reply_callback will release the memory.
event.release();
}
} catch (...) {
// Failed to send command, fail subsequent events.
auto err = std::current_exception();
for (; idx != events.size(); ++idx) {
events[idx]->set_exception(err);
}
disconnect(err);
break;
}
}
}
std::vector<AsyncEventUPtr> AsyncConnection::_get_events() {
std::vector<AsyncEventUPtr> events;
{
std::lock_guard<std::mutex> lock(_mtx);
events.swap(_events);
}
return events;
}
void AsyncConnection::_clean_up() {
if (!_err) {
_err = std::make_exception_ptr(Error("connection is closing"));
}
auto events = _get_events();
for (auto &event : events) {
assert(event);
event->set_exception(_err);
}
}
void AsyncConnection::_fail_events(std::exception_ptr err) {
_ctx = nullptr;
_err = err;
_state = State::BROKEN;
// Must call _clean_up after `_err` has been set.
_clean_up();
}
void AsyncConnection::_connecting_callback() {
if (_need_auth()) {
_auth();
} else if (_need_select_db()) {
_select_db();
} else if (_need_enable_readonly()) {
_enable_readonly();
} else {
_set_ready();
}
}
void AsyncConnection::_authing_callback() {
if (_need_select_db()) {
_select_db();
} else if (_need_enable_readonly()) {
_enable_readonly();
} else {
_set_ready();
}
}
void AsyncConnection::_select_db_callback() {
if (_need_enable_readonly()) {
_enable_readonly();
} else {
_set_ready();
}
}
void AsyncConnection::_auth() {
assert(!broken());
if (_opts.user == "default") {
if (redisAsyncCommand(_ctx, set_options_callback, nullptr, "AUTH %b",
_opts.password.data(), _opts.password.size()) != REDIS_OK) {
throw Error("failed to send auth command");
}
} else {
// Redis 6.0 or latter
if (redisAsyncCommand(_ctx, set_options_callback, nullptr, "AUTH %b %b",
_opts.user.data(), _opts.user.size(),
_opts.password.data(), _opts.password.size()) != REDIS_OK) {
throw Error("failed to send auth command");
}
}
_state = State::AUTHING;
}
void AsyncConnection::_select_db() {
assert(!broken());
if (redisAsyncCommand(_ctx, set_options_callback, nullptr, "SELECT %d",
_opts.db) != REDIS_OK) {
throw Error("failed to send select command");
}
_state = State::SELECTING_DB;
}
void AsyncConnection::_enable_readonly() {
assert(!broken());
if (redisAsyncCommand(_ctx, set_options_callback, nullptr, "READONLY") != REDIS_OK) {
throw Error("failed to send readonly command");
}
_state = State::ENABLE_READONLY;
}
void AsyncConnection::_set_ready() {
_state = State::READY;
// Send pending commands.
_send();
}
void AsyncConnection::_connect_with_sentinel() {
try {
auto opts = options();
if (opts.host.empty()) {
// Still waiting for sentinel.
return;
}
// Already got node info from sentinel
_state = State::NOT_CONNECTED;
_connect();
} catch (const Error &err) {
_fail_events(std::current_exception());
}
}
void AsyncConnection::_connect() {
try {
auto opts = options();
auto ctx = _connect(opts);
assert(ctx && ctx->err == REDIS_OK);
const auto &tls_opts = opts.tls;
tls::TlsContextUPtr tls_ctx;
if (tls::enabled(tls_opts)) {
tls_ctx = tls::secure_connection(ctx->c, tls_opts);
}
_loop->watch(*ctx);
_tls_ctx = std::move(tls_ctx);
_ctx = ctx.release();
_state = State::CONNECTING;
} catch (const Error &err) {
_fail_events(std::current_exception());
}
}
bool AsyncConnection::_need_auth() const {
return !_opts.password.empty() || _opts.user != "default";
}
bool AsyncConnection::_need_select_db() const {
return _opts.db != 0;
}
bool AsyncConnection::_need_enable_readonly() const {
return _opts.readonly;
}
void AsyncConnection::_clean_async_context(void *data) {
auto *ctx = static_cast<AsyncContext *>(data);
assert(ctx != nullptr);
delete ctx;
}
AsyncConnection::AsyncContextUPtr AsyncConnection::_connect(const ConnectionOptions &opts) {
redisAsyncContext *context = nullptr;
switch (opts.type) {
case ConnectionType::TCP:
context = redisAsyncConnect(opts.host.c_str(), opts.port);
break;
case ConnectionType::UNIX:
context = redisAsyncConnectUnix(opts.path.c_str());
break;
default:
// Never goes here.
throw Error("Unknown connection type");
}
if (context == nullptr) {
throw Error("Failed to allocate memory for connection.");
}
auto ctx = AsyncContextUPtr(context);
if (ctx->err != REDIS_OK) {
throw_error(ctx->c, "failed to connect to server");
}
ctx->data = new AsyncContext(shared_from_this());
ctx->dataCleanup = _clean_async_context;
return ctx;
}
GuardedAsyncConnection::GuardedAsyncConnection(const AsyncConnectionPoolSPtr &pool) :
_pool(pool), _connection(_pool->fetch()) {
assert(!_connection->broken());
}
GuardedAsyncConnection::~GuardedAsyncConnection() {
// If `GuardedAsyncConnection` has been moved, `_pool` will be nullptr.
if (_pool) {
_pool->release(std::move(_connection));
}
}
AsyncConnection& GuardedAsyncConnection::connection() {
assert(_connection);
return *_connection;
}
}
}
<commit_msg>Add socket timeout and connect timeout support for async interface (#393)<commit_after>/**************************************************************************
Copyright (c) 2021 sewenew
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 "async_connection.h"
#include <hiredis/async.h>
#include "errors.h"
#include "async_shards_pool.h"
#include "cmd_formatter.h"
#ifdef _MSC_VER
#include <winsock2.h> // for `timeval` with MSVC compiler
#endif
namespace {
using namespace sw::redis;
void set_options_callback(redisAsyncContext *ctx, void *r, void *) {
assert(ctx != nullptr);
auto *context = static_cast<AsyncContext *>(ctx->data);
assert(context != nullptr);
auto &connection = context->connection;
assert(connection);
redisReply *reply = static_cast<redisReply *>(r);
if (reply == nullptr) {
// Connection has bee closed.
// TODO: not sure if we should set this to be State::BROKEN
return;
}
try {
if (reply::is_error(*reply)) {
throw_error(*reply);
}
reply::parse<void>(*reply);
} catch (const Error &e) {
// TODO: disconnect and connect_callback might throw
connection->disconnect(std::make_exception_ptr(e));
return;
}
connection->connect_callback();
}
timeval to_timeval(const std::chrono::milliseconds &dur) {
auto sec = std::chrono::duration_cast<std::chrono::seconds>(dur);
auto msec = std::chrono::duration_cast<std::chrono::microseconds>(dur - sec);
timeval t;
t.tv_sec = sec.count();
t.tv_usec = msec.count();
return t;
}
}
namespace sw {
namespace redis {
AsyncConnection::AsyncConnection(const ConnectionOptions &opts,
EventLoop *loop,
AsyncConnectionMode mode) :
_opts(opts),
_loop(loop),
_create_time(std::chrono::steady_clock::now()),
_last_active(std::chrono::steady_clock::now().time_since_epoch()) {
assert(_loop != nullptr);
switch (mode) {
case AsyncConnectionMode::SINGLE:
_state = State::NOT_CONNECTED;
break;
case AsyncConnectionMode::SENTINEL:
_state = State::WAIT_SENTINEL;
break;
default:
throw Error("not supporeted async connection mode");
break;
}
}
AsyncConnection::~AsyncConnection() {
_clean_up();
}
void AsyncConnection::send(AsyncEventUPtr event) {
{
std::lock_guard<std::mutex> lock(_mtx);
_events.push_back(std::move(event));
}
_loop->add(shared_from_this());
}
void AsyncConnection::event_callback() {
// NOTE: we should try our best not throw in these callbacks
switch (_state.load()) {
case State::WAIT_SENTINEL:
_connect_with_sentinel();
break;
case State::NOT_CONNECTED:
_connect();
break;
case State::READY:
_send();
break;
case State::BROKEN:
_clean_up();
break;
default:
break;
}
}
void AsyncConnection::connect_callback(std::exception_ptr err) {
if (err) {
// Failed to connect to Redis, fail all pending events.
_fail_events(err);
return;
}
// Connect OK.
try {
switch (_state.load()) {
case State::CONNECTING:
_connecting_callback();
break;
case State::AUTHING:
_authing_callback();
break;
case State::SELECTING_DB:
_select_db_callback();
break;
default:
assert(_state == State::ENABLE_READONLY);
_set_ready();
}
} catch (const Error &e) {
disconnect(std::make_exception_ptr(e));
}
}
void AsyncConnection::disconnect(std::exception_ptr err) {
if (_ctx != nullptr) {
_disable_disconnect_callback();
redisAsyncDisconnect(_ctx);
}
_fail_events(err);
}
void AsyncConnection::disconnect_callback(std::exception_ptr err) {
_fail_events(err);
}
ConnectionOptions AsyncConnection::options() {
std::lock_guard<std::mutex> lock(_mtx);
return _opts;
}
void AsyncConnection::update_node_info(const std::string &host, int port) {
std::lock_guard<std::mutex> lock(_mtx);
_opts.host = host;
_opts.port = port;
}
void AsyncConnection::_disable_disconnect_callback() {
assert(_ctx != nullptr);
auto *ctx = static_cast<AsyncContext *>(_ctx->data);
assert(ctx != nullptr);
ctx->run_disconnect_callback = false;
}
void AsyncConnection::_send() {
auto events = _get_events();
auto &ctx = _context();
for (auto idx = 0U; idx != events.size(); ++idx) {
auto &event = events[idx];
try {
if (event->handle(ctx)) {
// CommandEvent::_reply_callback will release the memory.
event.release();
}
} catch (...) {
// Failed to send command, fail subsequent events.
auto err = std::current_exception();
for (; idx != events.size(); ++idx) {
events[idx]->set_exception(err);
}
disconnect(err);
break;
}
}
}
std::vector<AsyncEventUPtr> AsyncConnection::_get_events() {
std::vector<AsyncEventUPtr> events;
{
std::lock_guard<std::mutex> lock(_mtx);
events.swap(_events);
}
return events;
}
void AsyncConnection::_clean_up() {
if (!_err) {
_err = std::make_exception_ptr(Error("connection is closing"));
}
auto events = _get_events();
for (auto &event : events) {
assert(event);
event->set_exception(_err);
}
}
void AsyncConnection::_fail_events(std::exception_ptr err) {
_ctx = nullptr;
_err = err;
_state = State::BROKEN;
// Must call _clean_up after `_err` has been set.
_clean_up();
}
void AsyncConnection::_connecting_callback() {
if (_need_auth()) {
_auth();
} else if (_need_select_db()) {
_select_db();
} else if (_need_enable_readonly()) {
_enable_readonly();
} else {
_set_ready();
}
}
void AsyncConnection::_authing_callback() {
if (_need_select_db()) {
_select_db();
} else if (_need_enable_readonly()) {
_enable_readonly();
} else {
_set_ready();
}
}
void AsyncConnection::_select_db_callback() {
if (_need_enable_readonly()) {
_enable_readonly();
} else {
_set_ready();
}
}
void AsyncConnection::_auth() {
assert(!broken());
if (_opts.user == "default") {
if (redisAsyncCommand(_ctx, set_options_callback, nullptr, "AUTH %b",
_opts.password.data(), _opts.password.size()) != REDIS_OK) {
throw Error("failed to send auth command");
}
} else {
// Redis 6.0 or latter
if (redisAsyncCommand(_ctx, set_options_callback, nullptr, "AUTH %b %b",
_opts.user.data(), _opts.user.size(),
_opts.password.data(), _opts.password.size()) != REDIS_OK) {
throw Error("failed to send auth command");
}
}
_state = State::AUTHING;
}
void AsyncConnection::_select_db() {
assert(!broken());
if (redisAsyncCommand(_ctx, set_options_callback, nullptr, "SELECT %d",
_opts.db) != REDIS_OK) {
throw Error("failed to send select command");
}
_state = State::SELECTING_DB;
}
void AsyncConnection::_enable_readonly() {
assert(!broken());
if (redisAsyncCommand(_ctx, set_options_callback, nullptr, "READONLY") != REDIS_OK) {
throw Error("failed to send readonly command");
}
_state = State::ENABLE_READONLY;
}
void AsyncConnection::_set_ready() {
_state = State::READY;
// Send pending commands.
_send();
}
void AsyncConnection::_connect_with_sentinel() {
try {
auto opts = options();
if (opts.host.empty()) {
// Still waiting for sentinel.
return;
}
// Already got node info from sentinel
_state = State::NOT_CONNECTED;
_connect();
} catch (const Error &err) {
_fail_events(std::current_exception());
}
}
void AsyncConnection::_connect() {
try {
auto opts = options();
auto ctx = _connect(opts);
assert(ctx && ctx->err == REDIS_OK);
const auto &tls_opts = opts.tls;
tls::TlsContextUPtr tls_ctx;
if (tls::enabled(tls_opts)) {
tls_ctx = tls::secure_connection(ctx->c, tls_opts);
}
_loop->watch(*ctx);
_tls_ctx = std::move(tls_ctx);
_ctx = ctx.release();
_state = State::CONNECTING;
} catch (const Error &err) {
_fail_events(std::current_exception());
}
}
bool AsyncConnection::_need_auth() const {
return !_opts.password.empty() || _opts.user != "default";
}
bool AsyncConnection::_need_select_db() const {
return _opts.db != 0;
}
bool AsyncConnection::_need_enable_readonly() const {
return _opts.readonly;
}
void AsyncConnection::_clean_async_context(void *data) {
auto *ctx = static_cast<AsyncContext *>(data);
assert(ctx != nullptr);
delete ctx;
}
AsyncConnection::AsyncContextUPtr AsyncConnection::_connect(const ConnectionOptions &opts) {
redisOptions redis_opts;
// GCC 4.8 doesn't support zero initializer for C struct. Damn it!
std::memset(&redis_opts, 0, sizeof(redis_opts));
timeval connect_timeout;
if (opts.connect_timeout > std::chrono::milliseconds(0)) {
connect_timeout = to_timeval(opts.connect_timeout);
redis_opts.connect_timeout = &connect_timeout;
}
timeval socket_timeout;
if (opts.socket_timeout > std::chrono::milliseconds(0)) {
socket_timeout = to_timeval(opts.socket_timeout);
redis_opts.command_timeout = &socket_timeout;
}
switch (opts.type) {
case ConnectionType::TCP:
redis_opts.type = REDIS_CONN_TCP;
redis_opts.endpoint.tcp.ip = opts.host.c_str();
redis_opts.endpoint.tcp.port = opts.port;
break;
case ConnectionType::UNIX:
redis_opts.type = REDIS_CONN_UNIX;
redis_opts.endpoint.unix_socket = opts.path.c_str();
break;
default:
// Never goes here.
throw Error("Unknown connection type");
}
auto *context = redisAsyncConnectWithOptions(&redis_opts);
if (context == nullptr) {
throw Error("Failed to allocate memory for connection.");
}
auto ctx = AsyncContextUPtr(context);
if (ctx->err != REDIS_OK) {
throw_error(ctx->c, "failed to connect to server");
}
ctx->data = new AsyncContext(shared_from_this());
ctx->dataCleanup = _clean_async_context;
return ctx;
}
GuardedAsyncConnection::GuardedAsyncConnection(const AsyncConnectionPoolSPtr &pool) :
_pool(pool), _connection(_pool->fetch()) {
assert(!_connection->broken());
}
GuardedAsyncConnection::~GuardedAsyncConnection() {
// If `GuardedAsyncConnection` has been moved, `_pool` will be nullptr.
if (_pool) {
_pool->release(std::move(_connection));
}
}
AsyncConnection& GuardedAsyncConnection::connection() {
assert(_connection);
return *_connection;
}
}
}
<|endoftext|> |
<commit_before>// Read an INI file into easy-to-access name/value pairs.
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include "../ini.h"
#include "INIReader.h"
using std::string;
INIReader::INIReader(string filename)
{
_error = ini_parse(filename.c_str(), ValueHandler, this);
}
int INIReader::ParseError()
{
return _error;
}
string INIReader::Get(string section, string name, string default_value)
{
string key = MakeKey(section, name);
return _values.count(key) ? _values[key] : default_value;
}
long INIReader::GetInteger(string section, string name, long default_value)
{
string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
// This parses "1234" (decimal) and also "0x4D2" (hex)
long n = strtol(value, &end, 0);
return end > value ? n : default_value;
}
bool INIReader::GetBoolean(string section, string name, bool default_value)
{
string valstr = Get(section, name, "");
// Convert to lower case to make string comparisons case-insensitive
std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower);
if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1")
return true;
else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0")
return false;
else
return default_value;
}
string INIReader::MakeKey(string section, string name)
{
string key = section + "." + name;
// Convert to lower case to make section/name lookups case-insensitive
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
return key;
}
int INIReader::ValueHandler(void* user, const char* section, const char* name,
const char* value)
{
INIReader* reader = (INIReader*)user;
reader->_values[MakeKey(section, name)] = value;
return 1;
}
<commit_msg>Issue 18: Fixed multi-line handling in C++ wrapper, per jeffhawke77.<commit_after>// Read an INI file into easy-to-access name/value pairs.
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include "../ini.h"
#include "INIReader.h"
using std::string;
INIReader::INIReader(string filename)
{
_error = ini_parse(filename.c_str(), ValueHandler, this);
}
int INIReader::ParseError()
{
return _error;
}
string INIReader::Get(string section, string name, string default_value)
{
string key = MakeKey(section, name);
return _values.count(key) ? _values[key] : default_value;
}
long INIReader::GetInteger(string section, string name, long default_value)
{
string valstr = Get(section, name, "");
const char* value = valstr.c_str();
char* end;
// This parses "1234" (decimal) and also "0x4D2" (hex)
long n = strtol(value, &end, 0);
return end > value ? n : default_value;
}
bool INIReader::GetBoolean(string section, string name, bool default_value)
{
string valstr = Get(section, name, "");
// Convert to lower case to make string comparisons case-insensitive
std::transform(valstr.begin(), valstr.end(), valstr.begin(), ::tolower);
if (valstr == "true" || valstr == "yes" || valstr == "on" || valstr == "1")
return true;
else if (valstr == "false" || valstr == "no" || valstr == "off" || valstr == "0")
return false;
else
return default_value;
}
string INIReader::MakeKey(string section, string name)
{
string key = section + "." + name;
// Convert to lower case to make section/name lookups case-insensitive
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
return key;
}
int INIReader::ValueHandler(void* user, const char* section, const char* name,
const char* value)
{
INIReader* reader = (INIReader*)user;
string key = MakeKey(section, name);
if (reader->_values[key].size() > 0)
reader->_values[key] += "\n";
reader->_values[key] += value;
return 1;
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow 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 "tensorflow/compiler/mlir/utils/name_utils.h"
#include <cctype>
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "mlir/IR/Identifier.h" // from @llvm-project
namespace mlir {
namespace {
// Checks if a character is legal for a TensorFlow node name, with special
// handling if a character is at the beginning.
bool IsLegalChar(char c, bool first_char) {
if (isalpha(c)) return true;
if (isdigit(c)) return true;
if (c == '.') return true;
if (c == '_') return true;
// First character of a node name can only be a letter, digit, dot or
// underscore.
if (first_char) return false;
if (c == '/') return true;
if (c == '-') return true;
return false;
}
} // anonymous namespace
void LegalizeNodeName(std::string& name) {
if (name.empty()) return;
if (!IsLegalChar(name[0], /*first_char=*/true)) name[0] = '.';
for (char& c : llvm::drop_begin(name, 1))
if (!IsLegalChar(c, /*first_char=*/false)) c = '.';
}
std::string GetNameFromLoc(Location loc) {
llvm::SmallVector<llvm::StringRef, 8> loc_names;
llvm::SmallVector<Location, 8> locs;
locs.push_back(loc);
bool names_is_nonempty = false;
while (!locs.empty()) {
Location curr_loc = locs.pop_back_val();
if (auto name_loc = curr_loc.dyn_cast<NameLoc>()) {
// Add name in NameLoc. For NameLoc we also account for names due to ops
// in functions where the op's name is first.
auto name = name_loc.getName().strref().split('@').first;
loc_names.push_back(name);
if (!name.empty()) names_is_nonempty = true;
continue;
} else if (auto call_loc = curr_loc.dyn_cast<CallSiteLoc>()) {
// Add name if CallSiteLoc's callee has a NameLoc (as should be the
// case if imported with DebugInfo).
if (auto name_loc = call_loc.getCallee().dyn_cast<NameLoc>()) {
auto name = name_loc.getName().strref().split('@').first;
loc_names.push_back(name);
if (!name.empty()) names_is_nonempty = true;
continue;
}
} else if (auto fused_loc = curr_loc.dyn_cast<FusedLoc>()) {
// Push all locations in FusedLoc in reverse order, so locations are
// visited based on order in FusedLoc.
auto reversed_fused_locs = llvm::reverse(fused_loc.getLocations());
locs.append(reversed_fused_locs.begin(), reversed_fused_locs.end());
continue;
}
// Location is not a supported, so an empty StringRef is added.
loc_names.push_back(llvm::StringRef());
}
if (names_is_nonempty)
return llvm::join(loc_names.begin(), loc_names.end(), ";");
return "";
}
} // namespace mlir
<commit_msg>Support nested CallSiteLoc's when generating names from Location.<commit_after>/* Copyright 2020 The TensorFlow 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 "tensorflow/compiler/mlir/utils/name_utils.h"
#include <cctype>
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "mlir/IR/Identifier.h" // from @llvm-project
namespace mlir {
namespace {
// Checks if a character is legal for a TensorFlow node name, with special
// handling if a character is at the beginning.
bool IsLegalChar(char c, bool first_char) {
if (isalpha(c)) return true;
if (isdigit(c)) return true;
if (c == '.') return true;
if (c == '_') return true;
// First character of a node name can only be a letter, digit, dot or
// underscore.
if (first_char) return false;
if (c == '/') return true;
if (c == '-') return true;
return false;
}
} // anonymous namespace
void LegalizeNodeName(std::string& name) {
if (name.empty()) return;
if (!IsLegalChar(name[0], /*first_char=*/true)) name[0] = '.';
for (char& c : llvm::drop_begin(name, 1))
if (!IsLegalChar(c, /*first_char=*/false)) c = '.';
}
std::string GetNameFromLoc(Location loc) {
llvm::SmallVector<llvm::StringRef, 8> loc_names;
llvm::SmallVector<Location, 8> locs;
locs.push_back(loc);
bool names_is_nonempty = false;
while (!locs.empty()) {
Location curr_loc = locs.pop_back_val();
if (auto name_loc = curr_loc.dyn_cast<NameLoc>()) {
// Add name in NameLoc. For NameLoc we also account for names due to ops
// in functions where the op's name is first.
auto name = name_loc.getName().strref().split('@').first;
loc_names.push_back(name);
if (!name.empty()) names_is_nonempty = true;
continue;
} else if (auto call_loc = curr_loc.dyn_cast<CallSiteLoc>()) {
// Use location of the Callee to generate the name.
locs.push_back(call_loc.getCallee());
continue;
} else if (auto fused_loc = curr_loc.dyn_cast<FusedLoc>()) {
// Push all locations in FusedLoc in reverse order, so locations are
// visited based on order in FusedLoc.
auto reversed_fused_locs = llvm::reverse(fused_loc.getLocations());
locs.append(reversed_fused_locs.begin(), reversed_fused_locs.end());
continue;
}
// Location is not a supported, so an empty StringRef is added.
loc_names.push_back(llvm::StringRef());
}
if (names_is_nonempty)
return llvm::join(loc_names.begin(), loc_names.end(), ";");
return "";
}
} // namespace mlir
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "../config/config.hpp"
#ifdef MFEM_USE_MPI
#ifdef MFEM_USE_PETSC
#ifdef MFEM_USE_SLEPC
#include "linalg.hpp"
#include "slepc.h"
#include "petscinternals.hpp"
static PetscErrorCode ierr;
namespace mfem
{
void MFEMInitializeSlepc()
{
MFEMInitializeSlepc(NULL,NULL,NULL,NULL);
}
void MFEMInitializeSlepc(int *argc,char*** argv)
{
MFEMInitializeSlepc(argc,argv,NULL,NULL);
}
void MFEMInitializeSlepc(int *argc,char ***argv,const char rc_file[],
const char help[])
{
ierr = SlepcInitialize(argc,argv,rc_file,help);
MFEM_VERIFY(!ierr,"Unable to initialize SLEPc");
}
void MFEMFinalizeSlepc()
{
ierr = SlepcFinalize();
MFEM_VERIFY(!ierr,"Unable to finalize SLEPc");
}
SlepcEigenSolver::SlepcEigenSolver(MPI_Comm comm, const std::string &prefix)
{
clcustom = false;
VR = NULL;
VC = NULL;
ierr = EPSCreate(comm,&eps); CCHKERRQ(comm,ierr);
ierr = EPSSetOptionsPrefix(eps, prefix.c_str()); PCHKERRQ(eps, ierr);
}
SlepcEigenSolver::~SlepcEigenSolver()
{
delete VR;
delete VC;
MPI_Comm comm;
ierr = PetscObjectGetComm((PetscObject)eps,&comm); PCHKERRQ(eps,ierr);
ierr = EPSDestroy(&eps); CCHKERRQ(comm,ierr);
}
void SlepcEigenSolver::SetOperator(const PetscParMatrix &op)
{
delete VR;
delete VC;
VR = VC = NULL;
ierr = EPSSetOperators(eps,op,NULL); PCHKERRQ(eps, ierr);
VR = new PetscParVector(op, true, false);
VC = new PetscParVector(op, true, false);
}
void SlepcEigenSolver::SetOperators(const PetscParMatrix &op,
const PetscParMatrix&opB)
{
delete VR;
delete VC;
VR = VC = NULL;
ierr = EPSSetOperators(eps,op,opB); PCHKERRQ(eps,ierr);
VR = new PetscParVector(op, true, false);
VC = new PetscParVector(op, true, false);
}
void SlepcEigenSolver::SetTol(double tol)
{
PetscInt max_its;
ierr = EPSGetTolerances(eps,NULL,&max_its); PCHKERRQ(eps,ierr);
// Work around uninitialized maximum iterations
if (max_its==0) { max_its = PETSC_DECIDE; }
ierr = EPSSetTolerances(eps,tol,max_its); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::SetMaxIter(int max_its)
{
double tol;
ierr = EPSGetTolerances(eps,&tol,NULL); PCHKERRQ(eps,ierr);
ierr = EPSSetTolerances(eps,tol,max_its); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::SetNumModes(int num_eigs)
{
ierr = EPSSetDimensions(eps,num_eigs,PETSC_DECIDE,PETSC_DECIDE);
PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::Solve()
{
Customize();
ierr = EPSSolve(eps); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::Customize(bool customize) const
{
if (!customize) {clcustom = true; }
if (!clcustom)
{
ierr = EPSSetFromOptions(eps); PCHKERRQ(eps,ierr);
}
clcustom = true;
}
void SlepcEigenSolver::GetEigenvalue(unsigned int i, double & lr) const
{
ierr = EPSGetEigenvalue(eps,i,&lr,NULL); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::GetEigenvalue(unsigned int i, double & lr,
double & lc) const
{
ierr = EPSGetEigenvalue(eps,i,&lr,&lc); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::GetEigenvector(unsigned int i, Vector & vr) const
{
MFEM_VERIFY(VR,"Missing real vector");
MFEM_ASSERT(vr.Size() == VR->Size(), "invalid vr.Size() = " << vr.Size()
<< ", expected size = " << VR->Size());
VR->PlaceMemory(vr.GetMemory());
ierr = EPSGetEigenvector(eps,i,*VR,NULL); PCHKERRQ(eps,ierr);
VR->ResetMemory();
}
void SlepcEigenSolver::GetEigenvector(unsigned int i, Vector & vr,
Vector & vc) const
{
MFEM_VERIFY(VR,"Missing real vector");
MFEM_VERIFY(VC,"Missing imaginary vector");
MFEM_ASSERT(vr.Size() == VR->Size(), "invalid vr.Size() = " << vr.Size()
<< ", expected size = " << VR->Size());
MFEM_ASSERT(vc.Size() == VC->Size(), "invalid vc.Size() = " << vc.Size()
<< ", expected size = " << VC->Size());
VR->PlaceArray(vr.GetMemory());
VC->PlaceArray(vc.GetMemory());
ierr = EPSGetEigenvector(eps,i,*VR,*VC); PCHKERRQ(eps,ierr);
VR->ResetMemory();
VC->ResetMemory();
}
int SlepcEigenSolver::GetNumConverged()
{
PetscInt num_conv;
ierr = EPSGetConverged(eps,&num_conv); PCHKERRQ(eps,ierr);
return static_cast<int>(num_conv);
}
void SlepcEigenSolver::SetWhichEigenpairs(SlepcEigenSolver::Which which)
{
switch (which)
{
case SlepcEigenSolver::LARGEST_MAGNITUDE:
ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_MAGNITUDE); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::SMALLEST_MAGNITUDE:
ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_MAGNITUDE); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::LARGEST_REAL:
ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_REAL); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::SMALLEST_REAL:
ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_REAL); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::LARGEST_IMAGINARY:
ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_IMAGINARY); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::SMALLEST_IMAGINARY:
ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_IMAGINARY); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::TARGET_MAGNITUDE:
ierr = EPSSetWhichEigenpairs(eps,EPS_TARGET_MAGNITUDE); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::TARGET_REAL:
ierr = EPSSetWhichEigenpairs(eps,EPS_TARGET_REAL); PCHKERRQ(eps,ierr);
break;
default:
MFEM_ABORT("Which eigenpair not implemented!");
break;
}
}
void SlepcEigenSolver::SetTarget(double target)
{
ierr = EPSSetTarget(eps,target); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::SetSpectralTransformation(
SlepcEigenSolver::SpectralTransformation transformation)
{
ST st;
ierr = EPSGetST(eps,&st); PCHKERRQ(eps,ierr);
switch (transformation)
{
case SlepcEigenSolver::SHIFT:
ierr = STSetType(st,STSHIFT); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::SHIFT_INVERT:
ierr = STSetType(st,STSINVERT); PCHKERRQ(eps,ierr);
break;
default:
MFEM_ABORT("Spectral transformation not implemented!");
break;
}
}
}
#endif // MFEM_USE_SLEPC
#endif // MFEM_USE_PETSC
#endif // MFEM_USE_MPI
<commit_msg>SLEPC: set device id from MFEM device manager<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "../config/config.hpp"
#ifdef MFEM_USE_MPI
#ifdef MFEM_USE_PETSC
#ifdef MFEM_USE_SLEPC
#include "linalg.hpp"
#include "petscinternals.hpp"
#include "slepc.h"
static PetscErrorCode ierr;
using namespace std;
namespace mfem
{
void MFEMInitializeSlepc()
{
MFEMInitializeSlepc(NULL,NULL,NULL,NULL);
}
void MFEMInitializeSlepc(int *argc,char*** argv)
{
MFEMInitializeSlepc(argc,argv,NULL,NULL);
}
void MFEMInitializeSlepc(int *argc,char ***argv,const char rc_file[],
const char help[])
{
if (mfem::Device::Allows(mfem::Backend::CUDA_MASK))
{
// Tell PETSc to use the same CUDA device as MFEM:
ierr = PetscOptionsSetValue(NULL,"-cuda_device",
to_string(mfem::Device::GetId()).c_str());
MFEM_VERIFY(!ierr,"Unable to set initial option value to PETSc");
}
ierr = SlepcInitialize(argc,argv,rc_file,help);
MFEM_VERIFY(!ierr,"Unable to initialize SLEPc");
}
void MFEMFinalizeSlepc()
{
ierr = SlepcFinalize();
MFEM_VERIFY(!ierr,"Unable to finalize SLEPc");
}
SlepcEigenSolver::SlepcEigenSolver(MPI_Comm comm, const std::string &prefix)
{
clcustom = false;
VR = NULL;
VC = NULL;
ierr = EPSCreate(comm,&eps); CCHKERRQ(comm,ierr);
ierr = EPSSetOptionsPrefix(eps, prefix.c_str()); PCHKERRQ(eps, ierr);
}
SlepcEigenSolver::~SlepcEigenSolver()
{
delete VR;
delete VC;
MPI_Comm comm;
ierr = PetscObjectGetComm((PetscObject)eps,&comm); PCHKERRQ(eps,ierr);
ierr = EPSDestroy(&eps); CCHKERRQ(comm,ierr);
}
void SlepcEigenSolver::SetOperator(const PetscParMatrix &op)
{
delete VR;
delete VC;
VR = VC = NULL;
ierr = EPSSetOperators(eps,op,NULL); PCHKERRQ(eps, ierr);
VR = new PetscParVector(op, true, false);
VC = new PetscParVector(op, true, false);
}
void SlepcEigenSolver::SetOperators(const PetscParMatrix &op,
const PetscParMatrix&opB)
{
delete VR;
delete VC;
VR = VC = NULL;
ierr = EPSSetOperators(eps,op,opB); PCHKERRQ(eps,ierr);
VR = new PetscParVector(op, true, false);
VC = new PetscParVector(op, true, false);
}
void SlepcEigenSolver::SetTol(double tol)
{
PetscInt max_its;
ierr = EPSGetTolerances(eps,NULL,&max_its); PCHKERRQ(eps,ierr);
// Work around uninitialized maximum iterations
if (max_its==0) { max_its = PETSC_DECIDE; }
ierr = EPSSetTolerances(eps,tol,max_its); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::SetMaxIter(int max_its)
{
double tol;
ierr = EPSGetTolerances(eps,&tol,NULL); PCHKERRQ(eps,ierr);
ierr = EPSSetTolerances(eps,tol,max_its); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::SetNumModes(int num_eigs)
{
ierr = EPSSetDimensions(eps,num_eigs,PETSC_DECIDE,PETSC_DECIDE);
PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::Solve()
{
Customize();
ierr = EPSSolve(eps); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::Customize(bool customize) const
{
if (!customize) {clcustom = true; }
if (!clcustom)
{
ierr = EPSSetFromOptions(eps); PCHKERRQ(eps,ierr);
}
clcustom = true;
}
void SlepcEigenSolver::GetEigenvalue(unsigned int i, double & lr) const
{
ierr = EPSGetEigenvalue(eps,i,&lr,NULL); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::GetEigenvalue(unsigned int i, double & lr,
double & lc) const
{
ierr = EPSGetEigenvalue(eps,i,&lr,&lc); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::GetEigenvector(unsigned int i, Vector & vr) const
{
MFEM_VERIFY(VR,"Missing real vector");
MFEM_ASSERT(vr.Size() == VR->Size(), "invalid vr.Size() = " << vr.Size()
<< ", expected size = " << VR->Size());
VR->PlaceMemory(vr.GetMemory());
ierr = EPSGetEigenvector(eps,i,*VR,NULL); PCHKERRQ(eps,ierr);
VR->ResetMemory();
}
void SlepcEigenSolver::GetEigenvector(unsigned int i, Vector & vr,
Vector & vc) const
{
MFEM_VERIFY(VR,"Missing real vector");
MFEM_VERIFY(VC,"Missing imaginary vector");
MFEM_ASSERT(vr.Size() == VR->Size(), "invalid vr.Size() = " << vr.Size()
<< ", expected size = " << VR->Size());
MFEM_ASSERT(vc.Size() == VC->Size(), "invalid vc.Size() = " << vc.Size()
<< ", expected size = " << VC->Size());
VR->PlaceArray(vr.GetMemory());
VC->PlaceArray(vc.GetMemory());
ierr = EPSGetEigenvector(eps,i,*VR,*VC); PCHKERRQ(eps,ierr);
VR->ResetMemory();
VC->ResetMemory();
}
int SlepcEigenSolver::GetNumConverged()
{
PetscInt num_conv;
ierr = EPSGetConverged(eps,&num_conv); PCHKERRQ(eps,ierr);
return static_cast<int>(num_conv);
}
void SlepcEigenSolver::SetWhichEigenpairs(SlepcEigenSolver::Which which)
{
switch (which)
{
case SlepcEigenSolver::LARGEST_MAGNITUDE:
ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_MAGNITUDE); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::SMALLEST_MAGNITUDE:
ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_MAGNITUDE); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::LARGEST_REAL:
ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_REAL); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::SMALLEST_REAL:
ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_REAL); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::LARGEST_IMAGINARY:
ierr = EPSSetWhichEigenpairs(eps,EPS_LARGEST_IMAGINARY); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::SMALLEST_IMAGINARY:
ierr = EPSSetWhichEigenpairs(eps,EPS_SMALLEST_IMAGINARY); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::TARGET_MAGNITUDE:
ierr = EPSSetWhichEigenpairs(eps,EPS_TARGET_MAGNITUDE); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::TARGET_REAL:
ierr = EPSSetWhichEigenpairs(eps,EPS_TARGET_REAL); PCHKERRQ(eps,ierr);
break;
default:
MFEM_ABORT("Which eigenpair not implemented!");
break;
}
}
void SlepcEigenSolver::SetTarget(double target)
{
ierr = EPSSetTarget(eps,target); PCHKERRQ(eps,ierr);
}
void SlepcEigenSolver::SetSpectralTransformation(
SlepcEigenSolver::SpectralTransformation transformation)
{
ST st;
ierr = EPSGetST(eps,&st); PCHKERRQ(eps,ierr);
switch (transformation)
{
case SlepcEigenSolver::SHIFT:
ierr = STSetType(st,STSHIFT); PCHKERRQ(eps,ierr);
break;
case SlepcEigenSolver::SHIFT_INVERT:
ierr = STSetType(st,STSINVERT); PCHKERRQ(eps,ierr);
break;
default:
MFEM_ABORT("Spectral transformation not implemented!");
break;
}
}
}
#endif // MFEM_USE_SLEPC
#endif // MFEM_USE_PETSC
#endif // MFEM_USE_MPI
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_MULTIPLY_HPP
#define STAN_MATH_PRIM_MAT_FUN_MULTIPLY_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/arr/err/check_matching_sizes.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#ifdef STAN_OPENCL
#include <stan/math/opencl/multiply.hpp>
#endif
#include <type_traits>
namespace stan {
namespace math {
/**
* Return specified matrix multiplied by specified scalar.
* @tparam R Row type for matrix.
* @tparam C Column type for matrix.
* @param m Matrix.
* @param c Scalar.
* @return Product of matrix and scalar.
*/
template <int R, int C, typename T>
inline typename std::enable_if<std::is_arithmetic<T>::value,
Eigen::Matrix<double, R, C> >::type
multiply(const Eigen::Matrix<double, R, C>& m, T c) {
return c * m;
}
/**
* Return specified scalar multiplied by specified matrix.
* @tparam R Row type for matrix.
* @tparam C Column type for matrix.
* @param c Scalar.
* @param m Matrix.
* @return Product of scalar and matrix.
*/
template <int R, int C, typename T>
inline typename std::enable_if<std::is_arithmetic<T>::value,
Eigen::Matrix<double, R, C> >::type
multiply(T c, const Eigen::Matrix<double, R, C>& m) {
return c * m;
}
/**
* Return the product of the specified matrices. The number of
* columns in the first matrix must be the same as the number of rows
* in the second matrix.
* @param m1 First matrix.
* @param m2 Second matrix.
* @return The product of the first and second matrices.
* @throw std::domain_error if the number of columns of m1 does not match
* the number of rows of m2.
*/
template <int R1, int C1, int R2, int C2>
inline Eigen::Matrix<double, R1, C2> multiply(
const Eigen::Matrix<double, R1, C1>& m1,
const Eigen::Matrix<double, R2, C2>& m2) {
check_multiplicable("multiply", "m1", m1, "m2", m2);
#ifdef STAN_OPENCL
if (m1.rows() * m1.cols() * m2.cols()
> opencl_context.tuning_opts().multiply_dim_prod_worth_transfer) {
matrix_cl m1_cl(m1);
matrix_cl m2_cl(m2);
matrix_cl m3_cl = m1_cl * m2_cl;
return from_matrix_cl(m3_cl);
} else {
#endif
return m1 * m2;
#ifdef STAN_OPENCL
}
#endif
}
/**
* Return the scalar product of the specified row vector and
* specified column vector. The return is the same as the dot
* product. The two vectors must be the same size.
* @param rv Row vector.
* @param v Column vector.
* @return Scalar result of multiplying row vector by column vector.
* @throw std::domain_error if rv and v are not the same size.
*/
template <int C1, int R2>
inline double multiply(const Eigen::Matrix<double, 1, C1>& rv,
const Eigen::Matrix<double, R2, 1>& v) {
check_matching_sizes("multiply", "rv", rv, "v", v);
return rv.dot(v);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>added the template parameter<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_MULTIPLY_HPP
#define STAN_MATH_PRIM_MAT_FUN_MULTIPLY_HPP
#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/arr/err/check_matching_sizes.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#ifdef STAN_OPENCL
#include <stan/math/opencl/multiply.hpp>
#endif
#include <type_traits>
namespace stan {
namespace math {
/**
* Return specified matrix multiplied by specified scalar.
* @tparam R Row type for matrix.
* @tparam C Column type for matrix.
* @param m Matrix.
* @param c Scalar.
* @return Product of matrix and scalar.
*/
template <int R, int C, typename T>
inline typename std::enable_if<std::is_arithmetic<T>::value,
Eigen::Matrix<double, R, C> >::type
multiply(const Eigen::Matrix<double, R, C>& m, T c) {
return c * m;
}
/**
* Return specified scalar multiplied by specified matrix.
* @tparam R Row type for matrix.
* @tparam C Column type for matrix.
* @param c Scalar.
* @param m Matrix.
* @return Product of scalar and matrix.
*/
template <int R, int C, typename T>
inline typename std::enable_if<std::is_arithmetic<T>::value,
Eigen::Matrix<double, R, C> >::type
multiply(T c, const Eigen::Matrix<double, R, C>& m) {
return c * m;
}
/**
* Return the product of the specified matrices. The number of
* columns in the first matrix must be the same as the number of rows
* in the second matrix.
* @param m1 First matrix.
* @param m2 Second matrix.
* @return The product of the first and second matrices.
* @throw std::domain_error if the number of columns of m1 does not match
* the number of rows of m2.
*/
template <int R1, int C1, int R2, int C2>
inline Eigen::Matrix<double, R1, C2> multiply(
const Eigen::Matrix<double, R1, C1>& m1,
const Eigen::Matrix<double, R2, C2>& m2) {
check_multiplicable("multiply", "m1", m1, "m2", m2);
#ifdef STAN_OPENCL
if (m1.rows() * m1.cols() * m2.cols()
> opencl_context.tuning_opts().multiply_dim_prod_worth_transfer) {
matrix_cl<double> m1_cl(m1);
matrix_cl<double> m2_cl(m2);
matrix_cl<double> m3_cl = m1_cl * m2_cl;
return from_matrix_cl(m3_cl);
} else {
#endif
return m1 * m2;
#ifdef STAN_OPENCL
}
#endif
}
/**
* Return the scalar product of the specified row vector and
* specified column vector. The return is the same as the dot
* product. The two vectors must be the same size.
* @param rv Row vector.
* @param v Column vector.
* @return Scalar result of multiplying row vector by column vector.
* @throw std::domain_error if rv and v are not the same size.
*/
template <int C1, int R2>
inline double multiply(const Eigen::Matrix<double, 1, C1>& rv,
const Eigen::Matrix<double, R2, 1>& v) {
check_matching_sizes("multiply", "rv", rv, "v", v);
return rv.dot(v);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*!
* \page DemandGenerationTestSuite_cpp Command-Line Test to Demonstrate How To Use TraDemGen elements
* \code
*/
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <map>
#include <cmath>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE DemandGenerationTest
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
// TraDemGen
#include <trademgen/TRADEMGEN_Service.hpp>
#include <trademgen/bom/DemandStreamKey.hpp>
#include <trademgen/config/trademgen-paths.hpp>
namespace boost_utf = boost::unit_test;
// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("DemandGenerationTestSuite_utfresults.xml");
/**
* Configuration for the Boost Unit Test Framework (UTF)
*/
struct UnitTestConfig {
/** Constructor. */
UnitTestConfig() {
boost_utf::unit_test_log.set_stream (utfReportStream);
boost_utf::unit_test_log.set_format (boost_utf::XML);
boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
//boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
}
/** Destructor. */
~UnitTestConfig() {
}
};
// Specific type definitions
typedef std::pair<stdair::Count_T, stdair::Count_T> NbOfEventsPair_T;
typedef std::map<const stdair::DemandStreamKeyStr_T,
NbOfEventsPair_T> NbOfEventsByDemandStreamMap_T;
// /////////////// Main: Unit Test Suite //////////////
// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);
// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)
/**
* Test a simple simulation
*/
BOOST_AUTO_TEST_CASE (trademgen_simple_simulation_test) {
// Input file name
const stdair::Filename_T lInputFilename (STDAIR_SAMPLE_DIR "/demand01.csv");
// Check that the file path given as input corresponds to an actual file
const bool doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lInputFilename
<< "' input file can not be open and read");
// Output log File
const stdair::Filename_T lLogFilename ("DemandGenerationTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the TraDemGen service object
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams, lInputFilename);
/**
Initialise the current number of generated events and the
expected total numbers of requests to be generated, depending on
the demand streams.
<br>The current number of generated events starts at one, for each demand
stream, because the initialisation step generates exactly one event
for each demand stream.
*/
NbOfEventsByDemandStreamMap_T lNbOfEventsMap;
lNbOfEventsMap.insert (NbOfEventsByDemandStreamMap_T::
value_type ("SIN-HND 2010-Feb-08 Y",
NbOfEventsPair_T (1, 10)));
lNbOfEventsMap.insert (NbOfEventsByDemandStreamMap_T::
value_type ("SIN-BKK 2010-Feb-08 Y",
NbOfEventsPair_T (1, 10)));
// Total number of events, for all the demand streams: 20 (10 + 10)
stdair::Count_T lRefExpectedNbOfEvents (20);
// Retrieve the expected (mean value of the) number of events to be
// generated
const stdair::Count_T& lExpectedNbOfEventsToBeGenerated =
trademgenService.getExpectedTotalNumberOfRequestsToBeGenerated();
BOOST_CHECK_EQUAL (lRefExpectedNbOfEvents,
std::floor (lExpectedNbOfEventsToBeGenerated));
BOOST_CHECK_MESSAGE (lRefExpectedNbOfEvents ==
std::floor (lExpectedNbOfEventsToBeGenerated),
"Expected total number of requests to be generated: "
<< lExpectedNbOfEventsToBeGenerated
<< " (=> "
<< std::floor (lExpectedNbOfEventsToBeGenerated)
<< "). Reference value: " << lRefExpectedNbOfEvents);
/**
* Initialisation step.
*
* Generate the first event for each demand stream.
*
* \note For that demand (CSV) file (i.e., demand01.csv), the
* expected and actual numbers of events to be generated are
* the same (and equal to 20).
*/
const stdair::Count_T& lActualNbOfEventsToBeGenerated =
trademgenService.generateFirstRequests();
// DEBUG
STDAIR_LOG_DEBUG ("Expected number of events: "
<< lExpectedNbOfEventsToBeGenerated << ", actual: "
<< lActualNbOfEventsToBeGenerated);
// Total number of events, for all the demand streams: 8 (2 + 6)
const stdair::Count_T lRefActualNbOfEvents (8);
BOOST_CHECK_EQUAL (lRefActualNbOfEvents, lActualNbOfEventsToBeGenerated);
BOOST_CHECK_MESSAGE (lRefActualNbOfEvents == lActualNbOfEventsToBeGenerated,
"Actual total number of requests to be generated: "
<< lExpectedNbOfEventsToBeGenerated
<< " (=> "
<< std::floor (lExpectedNbOfEventsToBeGenerated)
<< "). Reference value: " << lRefActualNbOfEvents);
/** Is the queue empty? */
const bool isQueueDone = trademgenService.isQueueDone();
BOOST_REQUIRE_MESSAGE (isQueueDone == false,
"The event queue should not be empty. You may check "
<< "the input file: '" << lInputFilename << "'");
/**
Main loop.
<ul>
<li>Pop a request and get its associated type/demand stream.</li>
<li>Generate the next request for the same type/demand stream.</li>
</ul>
*/
stdair::Count_T idx = 1;
while (trademgenService.isQueueDone() == false) {
// Get the next event from the event queue
const stdair::EventStruct& lEventStruct = trademgenService.popEvent();
// DEBUG
STDAIR_LOG_DEBUG ("Poped event: '" << lEventStruct.describe() << "'.");
// Extract the corresponding demand/booking request
const stdair::BookingRequestStruct& lPoppedRequest =
lEventStruct.getBookingRequest();
// DEBUG
STDAIR_LOG_DEBUG ("Poped booking request: '"
<< lPoppedRequest.describe() << "'.");
// Retrieve the corresponding demand stream
const stdair::EventContentKey_T& lDemandStreamKey =
lEventStruct.getEventContentKey();
// Check that the number of booking requests to be generated are correct
const NbOfEventsByDemandStreamMap_T::iterator itNbOfEventsMap =
lNbOfEventsMap.find (lDemandStreamKey);
BOOST_REQUIRE_MESSAGE (itNbOfEventsMap != lNbOfEventsMap.end(),
"The demand stream key '" << lDemandStreamKey
<< "' is not expected in that test");
/**
For that demand stream, retrieve:
<ul>
<li>The current number of events</li>
<li>The expected total number of events to be generated. That
number is just hard coded for that test (it does not correspond
to an automatically generated number)</li>
</ul>
*/
const NbOfEventsPair_T& lNbOfEventsPair = itNbOfEventsMap->second;
stdair::Count_T lCurrentNbOfEvents = lNbOfEventsPair.first;
const stdair::Count_T& lExpectedTotalNbOfEvents = lNbOfEventsPair.second;
/**
The first time an event is popped from the queue for that demand stream,
check that the actual total number of requests to be generated (as
calculated by the demand stream itself during the initialisation
step), is equal to the expected number.
*/
if (lCurrentNbOfEvents == 1) {
/**
Retrieve, from the demand stream, the total number of events
to be generated, so that that number can be compared to the
expected one.
*/
const stdair::Count_T& lNbOfRequests =
lEventStruct.getKeySpecificExpectedTotalNbOfEvents();
BOOST_CHECK_EQUAL (lNbOfRequests, lExpectedTotalNbOfEvents);
BOOST_CHECK_MESSAGE (lNbOfRequests == lExpectedTotalNbOfEvents,
"[" << lDemandStreamKey
<< "] Total number of requests to be generated: "
<< lNbOfRequests << "). Expected value: "
<< lExpectedTotalNbOfEvents);
}
// Assess whether more events should be generated for that demand stream
const bool stillHavingRequestsToBeGenerated =
trademgenService.stillHavingRequestsToBeGenerated (lDemandStreamKey);
// DEBUG
STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "][" << lCurrentNbOfEvents
<< "/" << lExpectedTotalNbOfEvents
<< "] is now processed. "
<< "Still generate events for that demand stream? "
<< stillHavingRequestsToBeGenerated);
// If there are still events to be generated for that demand stream,
// generate and add them to the event queue
if (stillHavingRequestsToBeGenerated == true) {
const stdair::BookingRequestPtr_T lNextRequest_ptr =
trademgenService.generateNextRequest (lDemandStreamKey);
assert (lNextRequest_ptr != NULL);
/**
Sanity check
<br>The date-time of the next event must be greater than
the date-time of the current event.
*/
const stdair::Duration_T lDuration =
lNextRequest_ptr->getRequestDateTime()
- lPoppedRequest.getRequestDateTime();
BOOST_REQUIRE_GT (lDuration.total_milliseconds(), 0);
BOOST_REQUIRE_MESSAGE (lDuration.total_milliseconds() > 0,
"[" << lDemandStreamKey
<< "] The date-time of the generated event ("
<< lNextRequest_ptr->getRequestDateTime()
<< ") is lower than the date-time "
<< "of the current event ("
<< lPoppedRequest.getRequestDateTime() << ")");
// DEBUG
STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "][" << lCurrentNbOfEvents
<< "/" << lExpectedTotalNbOfEvents
<< "] Added request: '" << lNextRequest_ptr->describe()
<< "'. Is queue done? "
<< trademgenService.isQueueDone());
// Keep, within the dedicated map, the current counters of events updated.
++lCurrentNbOfEvents;
itNbOfEventsMap->second = NbOfEventsPair_T (lCurrentNbOfEvents,
lExpectedTotalNbOfEvents);
}
// Iterate
++idx;
}
// Compensate for the last iteration
--idx;
//
BOOST_CHECK_EQUAL (idx, lRefActualNbOfEvents);
BOOST_CHECK_MESSAGE (idx == lRefActualNbOfEvents,
"The total actual number of events is "
<< lRefActualNbOfEvents << ", but " << idx
<< " events have been generated");
/** Reset the context of the demand streams for another demand generation
without having to reparse the demand input file. */
trademgenService.reset();
// DEBUG
STDAIR_LOG_DEBUG ("End of the simulation");
// Close the log file
logOutputFile.close();
}
// End the test suite
BOOST_AUTO_TEST_SUITE_END()
/*!
* \endcode
*/
<commit_msg>[test] Fixed a bug.<commit_after>/*!
* \page DemandGenerationTestSuite_cpp Command-Line Test to Demonstrate How To Use TraDemGen elements
* \code
*/
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <map>
#include <cmath>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE DemandGenerationTest
#include <boost/test/unit_test.hpp>
// StdAir
#include <stdair/stdair_basic_types.hpp>
#include <stdair/basic/BasLogParams.hpp>
#include <stdair/basic/BasDBParams.hpp>
#include <stdair/basic/BasFileMgr.hpp>
#include <stdair/basic/ProgressStatusSet.hpp>
#include <stdair/bom/EventStruct.hpp>
#include <stdair/bom/EventQueue.hpp>
#include <stdair/bom/BookingRequestStruct.hpp>
#include <stdair/service/Logger.hpp>
// TraDemGen
#include <trademgen/TRADEMGEN_Service.hpp>
#include <trademgen/bom/DemandStreamKey.hpp>
#include <trademgen/config/trademgen-paths.hpp>
namespace boost_utf = boost::unit_test;
// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("DemandGenerationTestSuite_utfresults.xml");
/**
* Configuration for the Boost Unit Test Framework (UTF)
*/
struct UnitTestConfig {
/** Constructor. */
UnitTestConfig() {
boost_utf::unit_test_log.set_stream (utfReportStream);
boost_utf::unit_test_log.set_format (boost_utf::XML);
boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
//boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
}
/** Destructor. */
~UnitTestConfig() {
}
};
// Specific type definitions
typedef std::pair<stdair::Count_T, stdair::Count_T> NbOfEventsPair_T;
typedef std::map<const stdair::DemandStreamKeyStr_T,
NbOfEventsPair_T> NbOfEventsByDemandStreamMap_T;
// /////////////// Main: Unit Test Suite //////////////
// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);
// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)
/**
* Test a simple simulation
*/
BOOST_AUTO_TEST_CASE (trademgen_simple_simulation_test) {
// Input file name
const stdair::Filename_T lInputFilename (STDAIR_SAMPLE_DIR "/demand01.csv");
// Check that the file path given as input corresponds to an actual file
const bool doesExistAndIsReadable =
stdair::BasFileMgr::doesExistAndIsReadable (lInputFilename);
BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true,
"The '" << lInputFilename
<< "' input file can not be open and read");
// Output log File
const stdair::Filename_T lLogFilename ("DemandGenerationTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the TraDemGen service object
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
TRADEMGEN::TRADEMGEN_Service trademgenService (lLogParams, lInputFilename);
/**
Initialise the current number of generated events and the
expected total numbers of requests to be generated, depending on
the demand streams.
<br>The current number of generated events starts at one, for each demand
stream, because the initialisation step generates exactly one event
for each demand stream.
*/
NbOfEventsByDemandStreamMap_T lNbOfEventsMap;
lNbOfEventsMap.insert (NbOfEventsByDemandStreamMap_T::
value_type ("SIN-HND 2010-Feb-08 Y",
NbOfEventsPair_T (1, 10)));
lNbOfEventsMap.insert (NbOfEventsByDemandStreamMap_T::
value_type ("SIN-BKK 2010-Feb-08 Y",
NbOfEventsPair_T (1, 10)));
// Total number of events, for all the demand streams: 20 (10 + 10)
stdair::Count_T lRefExpectedNbOfEvents (20);
// Retrieve the expected (mean value of the) number of events to be
// generated
const stdair::Count_T& lExpectedNbOfEventsToBeGenerated =
trademgenService.getExpectedTotalNumberOfRequestsToBeGenerated();
BOOST_CHECK_EQUAL (lRefExpectedNbOfEvents,
std::floor (lExpectedNbOfEventsToBeGenerated));
BOOST_CHECK_MESSAGE (lRefExpectedNbOfEvents ==
std::floor (lExpectedNbOfEventsToBeGenerated),
"Expected total number of requests to be generated: "
<< lExpectedNbOfEventsToBeGenerated
<< " (=> "
<< std::floor (lExpectedNbOfEventsToBeGenerated)
<< "). Reference value: " << lRefExpectedNbOfEvents);
/**
* Initialisation step.
*
* Generate the first event for each demand stream.
*
* \note For that demand (CSV) file (i.e., demand01.csv), the
* expected and actual numbers of events to be generated are
* the same (and equal to 20).
*/
const stdair::Count_T& lActualNbOfEventsToBeGenerated =
trademgenService.generateFirstRequests();
// DEBUG
STDAIR_LOG_DEBUG ("Expected number of events: "
<< lExpectedNbOfEventsToBeGenerated << ", actual: "
<< lActualNbOfEventsToBeGenerated);
// Total number of events, for all the demand streams: 8 (2 + 6)
const stdair::Count_T lRefActualNbOfEvents (8);
BOOST_CHECK_EQUAL (lRefActualNbOfEvents, lActualNbOfEventsToBeGenerated);
BOOST_CHECK_MESSAGE (lRefActualNbOfEvents == lActualNbOfEventsToBeGenerated,
"Actual total number of requests to be generated: "
<< lExpectedNbOfEventsToBeGenerated
<< " (=> "
<< std::floor (lExpectedNbOfEventsToBeGenerated)
<< "). Reference value: " << lRefActualNbOfEvents);
/** Is the queue empty? */
const bool isQueueDone = trademgenService.isQueueDone();
BOOST_REQUIRE_MESSAGE (isQueueDone == false,
"The event queue should not be empty. You may check "
<< "the input file: '" << lInputFilename << "'");
/**
Main loop.
<ul>
<li>Pop a request and get its associated type/demand stream.</li>
<li>Generate the next request for the same type/demand stream.</li>
</ul>
*/
stdair::Count_T idx = 1;
while (trademgenService.isQueueDone() == false) {
// Get the next event from the event queue
stdair::EventStruct lEventStruct;
stdair::ProgressStatusSet lPPS = trademgenService.popEvent (lEventStruct);
// DEBUG
STDAIR_LOG_DEBUG ("Poped event: '" << lEventStruct.describe() << "'.");
// Extract the corresponding demand/booking request
const stdair::BookingRequestStruct& lPoppedRequest =
lEventStruct.getBookingRequest();
// DEBUG
STDAIR_LOG_DEBUG ("Poped booking request: '"
<< lPoppedRequest.describe() << "'.");
// Retrieve the corresponding demand stream
const stdair::DemandGeneratorKey_T& lDemandStreamKey =
lPoppedRequest.getDemandGeneratorKey();
// Check that the number of booking requests to be generated are correct
const NbOfEventsByDemandStreamMap_T::iterator itNbOfEventsMap =
lNbOfEventsMap.find (lDemandStreamKey);
BOOST_REQUIRE_MESSAGE (itNbOfEventsMap != lNbOfEventsMap.end(),
"The demand stream key '" << lDemandStreamKey
<< "' is not expected in that test");
/**
For that demand stream, retrieve:
<ul>
<li>The current number of events</li>
<li>The expected total number of events to be generated. That
number is just hard coded for that test (it does not correspond
to an automatically generated number)</li>
</ul>
*/
const NbOfEventsPair_T& lNbOfEventsPair = itNbOfEventsMap->second;
stdair::Count_T lCurrentNbOfEvents = lNbOfEventsPair.first;
const stdair::Count_T& lExpectedTotalNbOfEvents = lNbOfEventsPair.second;
// Assess whether more events should be generated for that demand stream
const bool stillHavingRequestsToBeGenerated =
trademgenService.stillHavingRequestsToBeGenerated (lDemandStreamKey, lPPS);
/**
The first time an event is popped from the queue for that demand stream,
check that the actual total number of requests to be generated (as
calculated by the demand stream itself during the initialisation
step), is equal to the expected number.
*/
if (lCurrentNbOfEvents == 1) {
/**
Retrieve, from the demand stream, the total number of events
to be generated, so that that number can be compared to the
expected one.
*/
const stdair::ProgressStatus& lDemandStreamProgressStatus =
lPPS.getSpecificGeneratorStatus();
const stdair::Count_T& lNbOfRequests =
lDemandStreamProgressStatus.getExpectedNb();
BOOST_CHECK_EQUAL (lNbOfRequests, lExpectedTotalNbOfEvents);
BOOST_CHECK_MESSAGE (lNbOfRequests == lExpectedTotalNbOfEvents,
"[" << lDemandStreamKey
<< "] Total number of requests to be generated: "
<< lNbOfRequests << "). Expected value: "
<< lExpectedTotalNbOfEvents);
}
// DEBUG
STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "][" << lCurrentNbOfEvents
<< "/" << lExpectedTotalNbOfEvents
<< "] is now processed. "
<< "Still generate events for that demand stream? "
<< stillHavingRequestsToBeGenerated);
// If there are still events to be generated for that demand stream,
// generate and add them to the event queue
if (stillHavingRequestsToBeGenerated == true) {
const stdair::BookingRequestPtr_T lNextRequest_ptr =
trademgenService.generateNextRequest (lDemandStreamKey);
assert (lNextRequest_ptr != NULL);
/**
Sanity check
<br>The date-time of the next event must be greater than
the date-time of the current event.
*/
const stdair::Duration_T lDuration =
lNextRequest_ptr->getRequestDateTime()
- lPoppedRequest.getRequestDateTime();
BOOST_REQUIRE_GT (lDuration.total_milliseconds(), 0);
BOOST_REQUIRE_MESSAGE (lDuration.total_milliseconds() > 0,
"[" << lDemandStreamKey
<< "] The date-time of the generated event ("
<< lNextRequest_ptr->getRequestDateTime()
<< ") is lower than the date-time "
<< "of the current event ("
<< lPoppedRequest.getRequestDateTime() << ")");
// DEBUG
STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "][" << lCurrentNbOfEvents
<< "/" << lExpectedTotalNbOfEvents
<< "] Added request: '" << lNextRequest_ptr->describe()
<< "'. Is queue done? "
<< trademgenService.isQueueDone());
// Keep, within the dedicated map, the current counters of events updated.
++lCurrentNbOfEvents;
itNbOfEventsMap->second = NbOfEventsPair_T (lCurrentNbOfEvents,
lExpectedTotalNbOfEvents);
}
// Iterate
++idx;
}
// Compensate for the last iteration
--idx;
//
BOOST_CHECK_EQUAL (idx, lRefActualNbOfEvents);
BOOST_CHECK_MESSAGE (idx == lRefActualNbOfEvents,
"The total actual number of events is "
<< lRefActualNbOfEvents << ", but " << idx
<< " events have been generated");
/** Reset the context of the demand streams for another demand generation
without having to reparse the demand input file. */
trademgenService.reset();
// DEBUG
STDAIR_LOG_DEBUG ("End of the simulation");
// Close the log file
logOutputFile.close();
}
// End the test suite
BOOST_AUTO_TEST_SUITE_END()
/*!
* \endcode
*/
<|endoftext|> |
<commit_before>#include <zmq.hpp>
#include <map>
#include <string>
#include <iostream>
// #include <quidpp.h>
//#include <ups/upscaledb.hpp>
//#include <leveldb/db.h>
#include "common/sdbm_hash.h"
#include "common/crc32.h"
#include "common/hdb.h"
#include "protoc/storagequery.pb.h"
#include "consistent_hash.h"
#include "server_node.h"
#include "node_config.h"
#include "engine.h"
#define SHARDING_SPREAD 10
static Consistent::HashRing<std::string, quidpp::Quid, Crc32> nodeRing(SHARDING_SPREAD, Crc32());
static std::map<std::string, ServerNode> servers;
static NodeConfig nc;
void initMaster() {
std::cout << "Master" << std::endl;
/* Setup node ring */
nc.foreachSlaveNode([](const std::string & key, const std::string & value) -> void {
std::cout << "Adding '" << value << ":" << nodeRing.addNode(value) << "' to nodering" << std::endl;
});
/* Prepare our context and socket */
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REQ);
int id = 17;
{
StorageQuery query;
query.set_name("woei");
query.set_id(id++);
query.set_quid("{8ca9e93a-59ad-4564-b677-5dc59c2f0250}");
query.set_content("haha bier");
query.set_queryaction(StorageQuery::INSERT);
// Perform query
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
}
{
StorageQuery query;
query.set_name("kaas");
query.set_id(id++);
query.set_quid("{42ec500a-c0af-40b6-a1f0-37121d6777f7}");
query.set_content("woef");
query.set_queryaction(StorageQuery::INSERT);
// Perform query
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
}
{
StorageQuery query;
query.set_name("blub");
query.set_id(id++);
query.set_quid("{a24521f5-2cb8-4c41-aa98-1366a439024e}");
query.set_content("is ook erg grappig enzo");
query.set_queryaction(StorageQuery::INSERT);
// Perform query
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
}
{
StorageQuery query;
query.set_name("worst");
query.set_id(id++);
query.set_quid("{5a875b54-b167-4b28-8cfd-7b994598a455}");
query.set_content("hoort er ook bij");
query.set_queryaction(StorageQuery::INSERT);
// Perform query
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
}
{
StorageQuery query;
query.set_name("woei");
query.set_id(id++);
query.set_quid("{8ca9e93a-59ad-4564-b677-5dc59c2f0250}");
query.set_queryaction(StorageQuery::SELECT);
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "SELECT result " << query.content() << std::endl;
}
exit(0); /* Should never reach */
}
void initSlave() {
std::cout << "Slave" << std::endl;
Engine coredb(EngineType::DB_ABI);
Engine metadb(EngineType::DB_ADI);
/* Prepare our context and socket */
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REP);
int opt = 1;
socket.setsockopt(ZMQ_IPV6, &opt, sizeof(int));
socket.bind("tcp://*:5522");
std::cout << "Waiting for connections " << std::endl;
while (true) {
zmq::message_t request;
// Wait for next request from client
socket.recv(&request);
StorageQuery query;
query.ParseFromArray(request.data(), request.size());
switch (query.queryaction()) {
case StorageQuery::SELECT:
std::cout << "Request " << query.id() << " [SELECT] " << query.quid() << " & " << query.name() << std::endl;
query.set_content(coredb.get(query.quid()));
break;
case StorageQuery::INSERT:
std::cout << "Request " << query.id() << " [INSERT] " << query.quid() << " & " << query.name() << std::endl;
coredb.put(query.quid(), query.name(), query.content());
// insert into meta [ADI]
break;
case StorageQuery::UPDATE:
std::cout << "Request " << query.id() << " [UPDATE] " << query.quid() << " & " << query.name() << std::endl;
coredb.put(query.quid(), query.name(), query.content(), true);
break;
case StorageQuery::DELETE:
std::cout << "Request " << query.id() << " [DELETE] " << query.quid() << " & " << query.name() << std::endl;
coredb.remove(query.quid(), query.name());
break;
}
// Send back query structure
std::string serialized;
query.SerializeToString(&serialized);
zmq::message_t reply(serialized.size());
memcpy(reinterpret_cast<void *>(reply.data()), serialized.c_str(), serialized.size());
socket.send(reply);
}
}
int main(int argc, char *argv[]) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
if (argc > 2 && !strcmp(argv[1], "-a")) {
nc.addSlaveNode(argv[2]);
return 0;
}
if (argc > 1 && !strcmp(argv[1], "-m")) {
nc.setMaster();
}
if (nc.isMaster())
initMaster();
/* Only initialize if we're not master */
initSlave();
return 0;
}
<commit_msg>Test query operations<commit_after>#include <zmq.hpp>
#include <map>
#include <string>
#include <iostream>
// #include <quidpp.h>
//#include <ups/upscaledb.hpp>
//#include <leveldb/db.h>
#include "common/sdbm_hash.h"
#include "common/crc32.h"
#include "common/hdb.h"
#include "protoc/storagequery.pb.h"
#include "consistent_hash.h"
#include "server_node.h"
#include "node_config.h"
#include "engine.h"
#define SHARDING_SPREAD 10
static Consistent::HashRing<std::string, quidpp::Quid, Crc32> nodeRing(SHARDING_SPREAD, Crc32());
static std::map<std::string, ServerNode> servers;
static NodeConfig nc;
void initMaster() {
std::cout << "Master" << std::endl;
/* Setup node ring */
nc.foreachSlaveNode([](const std::string & key, const std::string & value) -> void {
std::cout << "Adding '" << value << ":" << nodeRing.addNode(value) << "' to nodering" << std::endl;
});
/* Prepare our context and socket */
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REQ);
int id = 17;
{
StorageQuery query;
query.set_name("woei");
query.set_id(id++);
query.set_quid("{8ca9e93a-59ad-4564-b677-5dc59c2f0250}");
query.set_content("haha bier");
query.set_queryaction(StorageQuery::INSERT);
query.set_queryresult(StorageQuery::SUCCESS);
// Perform query
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "RS: " << query.queryresult() << std::endl;
}
{
StorageQuery query;
query.set_name("kaas");
query.set_id(id++);
query.set_quid("{42ec500a-c0af-40b6-a1f0-37121d6777f7}");
query.set_content("woef");
query.set_queryaction(StorageQuery::INSERT);
query.set_queryresult(StorageQuery::SUCCESS);
// Perform query
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "RS: " << query.queryresult() << std::endl;
}
{
StorageQuery query;
query.set_name("blub");
query.set_id(id++);
query.set_quid("{a24521f5-2cb8-4c41-aa98-1366a439024e}");
query.set_content("is ook erg grappig enzo");
query.set_queryaction(StorageQuery::INSERT);
query.set_queryresult(StorageQuery::SUCCESS);
// Perform query
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "RS: " << query.queryresult() << std::endl;
}
{
StorageQuery query;
query.set_name("worst");
query.set_id(id++);
query.set_quid("{5a875b54-b167-4b28-8cfd-7b994598a455}");
query.set_content("hoort er ook bij");
query.set_queryaction(StorageQuery::INSERT);
query.set_queryresult(StorageQuery::SUCCESS);
// Perform query
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "RS: " << query.queryresult() << std::endl;
}
{
StorageQuery query;
query.set_name("woei");
query.set_id(id++);
query.set_quid("{8ca9e93a-59ad-4564-b677-5dc59c2f0250}");
query.set_content("haha bier, en nog meer");
query.set_queryaction(StorageQuery::UPDATE);
query.set_queryresult(StorageQuery::SUCCESS);
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "SELECT result " << query.content() << std::endl;
std::cout << "RS: " << query.queryresult() << std::endl;
}
{
StorageQuery query;
query.set_name("woei");
query.set_id(id++);
query.set_quid("{8ca9e93a-59ad-4564-b677-5dc59c2f0250}");
query.set_queryaction(StorageQuery::SELECT);
query.set_queryresult(StorageQuery::SUCCESS);
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "SELECT result " << query.content() << std::endl;
std::cout << "RS: " << query.queryresult() << std::endl;
}
{
StorageQuery query;
query.set_name("woei");
query.set_id(id);
query.set_quid("{8ca9e93a-59ad-4564-b677-5dc59c2f0250}");
query.set_queryaction(StorageQuery::DELETE);
query.set_queryresult(StorageQuery::SUCCESS);
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "RS: " << query.queryresult() << std::endl;
}
{
StorageQuery query;
query.set_name("woei");
query.set_id(id++);
query.set_quid("{8ca9e93a-59ad-4564-b677-5dc59c2f0250}");
query.set_queryaction(StorageQuery::SELECT);
query.set_queryresult(StorageQuery::SUCCESS);
std::string serialized;
query.SerializeToString(&serialized);
std::string host = nodeRing.getNode(query.quid());
socket.connect(("tcp://" + host + ":5522").c_str());
std::cout << "Connect to server " << host << " for record " << query.quid() << std::endl;
zmq::message_t request(serialized.size());
memcpy(reinterpret_cast<void *>(request.data()), serialized.c_str(), serialized.size());
socket.send(request);
// Get the reply
zmq::message_t reply;
socket.recv(&reply);
socket.disconnect(("tcp://" + host + ":5522").c_str());
query.ParseFromArray(reply.data(), reply.size());
std::cout << "RS: " << query.queryresult() << std::endl;
}
exit(0); /* Should never reach */
}
void initSlave() {
std::cout << "Slave" << std::endl;
Engine coredb(EngineType::DB_ABI);
Engine metadb(EngineType::DB_ADI);
/* Prepare our context and socket */
zmq::context_t context(1);
zmq::socket_t socket(context, ZMQ_REP);
int opt = 1;
socket.setsockopt(ZMQ_IPV6, &opt, sizeof(int));
socket.bind("tcp://*:5522");
std::cout << "Waiting for connections " << std::endl;
while (true) {
zmq::message_t request;
// Wait for next request from client
socket.recv(&request);
StorageQuery query;
query.ParseFromArray(request.data(), request.size());
query.set_queryresult(StorageQuery::SUCCESS);
try {
switch (query.queryaction()) {
case StorageQuery::SELECT:
std::cout << "Request " << query.id() << " [SELECT] " << query.quid() << " named '" << query.name() << "'" << std::endl;
query.set_content(coredb.get(query.quid()));
break;
case StorageQuery::INSERT:
std::cout << "Request " << query.id() << " [INSERT] " << query.quid() << " named '" << query.name() << "'" << std::endl;
coredb.put(query.quid(), query.name(), query.content());
// insert into meta [ADI]
break;
case StorageQuery::UPDATE:
std::cout << "Request " << query.id() << " [UPDATE] " << query.quid() << " named '" << query.name() << "'" << std::endl;
coredb.put(query.quid(), query.name(), query.content(), true);
break;
case StorageQuery::DELETE:
std::cout << "Request " << query.id() << " [DELETE] " << query.quid() << " named '" << query.name() << "'" << std::endl;
coredb.remove(query.quid(), query.name());
break;
}
} catch (upscaledb::error &e) {
switch (e.get_errno()) {
case UPS_KEY_NOT_FOUND:
query.set_queryresult(StorageQuery::NOTFOUND);
break;
case UPS_DUPLICATE_KEY:
query.set_queryresult(StorageQuery::DUPLICATE);
break;
default:
std::cerr << "Operation failed: " << e.get_string() << " :: " << e.get_errno() << std::endl;
break;
}
}
// Send back query structure
std::string serialized;
query.SerializeToString(&serialized);
zmq::message_t reply(serialized.size());
memcpy(reinterpret_cast<void *>(reply.data()), serialized.c_str(), serialized.size());
socket.send(reply);
}
}
int main(int argc, char *argv[]) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
if (argc > 2 && !strcmp(argv[1], "-a")) {
nc.addSlaveNode(argv[2]);
return 0;
}
if (argc > 1 && !strcmp(argv[1], "-m")) {
nc.setMaster();
}
if (nc.isMaster())
initMaster();
/* Only initialize if we're not master */
initSlave();
return 0;
}
<|endoftext|> |
<commit_before>#ifdef _DEBUG
#include "testdatapath.h"
#endif
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <qdir.h>
#include <qstringlist.h>
#include "cvutils.h"
#include "ImageScrap.h"
using namespace std;
int main(int argc, char** argv)
{
#ifdef _DEBUG
//コマンドライン引数の解析。デバッグの時は使わない
string commandArgs =
"@input | | processing one image or image named serial number"
;
cv::CommandLineParser parser(argc, argv, commandArgs);
string src = parser.get<string>(0);
#else
//string src = TEST_DATA_0;
string src = "C:\\Users\\kyokushin\\Pictures\\testData\\";
#endif
QDir dir(src.c_str());
if (!dir.exists()) {
cerr << "failed to find files" << endl;
return 1;
}
QFileInfoList fileList = dir.entryInfoList(QDir::Files);
fileList.size();
cout << "input file:" << src << endl;
int waitTime = 10;
vector<int> imageHeights;
vector<cv::Mat> pageNumbers;
cv::Mat rowImage(1, 1, CV_8UC1);
cv::Mat image;
for (int i = 0; i < fileList.size(); i++){
string fname = fileList[i].absoluteFilePath().toStdString();
cout << fname << endl;
cv::Mat colorImage = cv::imread(fname);
//画像の読み込み。グレースケール画像として読み込む
cv::cvtColor(colorImage, image, CV_BGR2GRAY);
ImageScrap scrapImage(image, ImageScrap::RANGE_ALL);
//scrapImage.show();
scrapImage.getRow(0).copyTo(rowImage);
imageHeights.push_back(rowImage.rows);//ページ番号と思われる領域を保存
pageNumbers.push_back(rowImage);
cout << "height:" << rowImage.rows << endl;
showImage(rowImage, waitTime);
}
vector<int> sortedImageHeights;
copy(imageHeights.begin(), imageHeights.end(), back_inserter(sortedImageHeights));
sort(sortedImageHeights.begin(), sortedImageHeights.end());
int start;
int acceptHeight = 10;
for (start = 0; sortedImageHeights[start] < acceptHeight; start++) {
}
int heightMed = sortedImageHeights[start + (sortedImageHeights.size() - start)/2];
int minHeight = heightMed * 0.5;
int maxHeight = heightMed * 2.0;
cout << "height median:" << heightMed << endl;
vector<int> isPageNumber;
for (int i = 0; i < imageHeights.size(); i++){
cout << "height:" << imageHeights[i] << endl;
isPageNumber.push_back(minHeight <= imageHeights[i] && imageHeights[i] <= maxHeight);
}
for (int i = 0; i < isPageNumber.size(); i++){
if (isPageNumber[i]){
showImage(pageNumbers[i]);
}
else{
continue;
cv::Mat colorImage = cv::imread(fileList[i].absoluteFilePath().toStdString());
showImage(colorImage);
}
}
return 0;
}
void showNoneCharacterRange(const cv::Mat& image){
CV_Assert(image.channels() == 1 && image.type() == CV_8UC1);
showImage(image);
//二値化
cv::Mat binary;
int binaryMax = 1;//二値化時の最大値は1に。積分するときに白だったところか黒だったところかがわかればいい。
int binaryThreshold = 128;
cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV);
CV_Assert(binary.channels() == 1 && binary.type() == CV_8UC1);
showImage(binary);
cv::imwrite("binary.jpg", binary);
//積分画像の生成
cv::Mat integral;
cv::integral(binary, integral);
CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1);
showImage(integral);
cv::imwrite("integral.jpg", integral);
//積分画像を見やすくする処理
cv::Mat integralVisible;
double max;
double min;
cv::minMaxLoc(integral, &min, &max);//最大値だけほしいので第3引数まで。最小値は0のはずだが本当に0か確認するために使う
CV_Assert(min == 0.0);//本当に最小値が0になっているか確認
integral.convertTo(integralVisible, CV_8UC1, 255.0 / max); //betaは使わない。0-255の値をとるようにalphaを与える。
showImage(integralVisible);
cv::imwrite("integralVisible.jpg", integralVisible);
//横方向
//文字のない範囲を受け取る変数
vector<Range> horizontalRanges;
findSameValueHorizontal(integral, horizontalRanges);
//1チャンネルの原画像から3チャンネルの画像を作る
cv::Mat srcArray[] = {image, image, image};
cv::Mat srcColor;
cv::merge(srcArray, 3, srcColor);
const cv::Scalar colorVertical(0, 0, 255);
const cv::Scalar colorHorizontal(240, 176, 0);
//文字のない範囲を書き込む画像
cv::Mat horizontalRangeDst;
drawRange(srcColor, horizontalRanges, ImageScrap::RANGE_COLS, horizontalRangeDst, colorHorizontal);
showImage(horizontalRangeDst);
cv::imwrite("horizontalDst.jpg", horizontalRangeDst);
//縦方向
//文字のない範囲を受け取る変数
vector<Range> verticalRanges;
findSameValueVertical(integral, verticalRanges);
//文字のない範囲を書き込む画像
cv::Mat verticalRangeDst;
drawRange(srcColor, verticalRanges, ImageScrap::RANGE_ROWS, verticalRangeDst, colorVertical);
showImage(verticalRangeDst);
//縦横で文字のない範囲を書き込む
cv::imwrite("verticalDst.jpg", verticalRangeDst);
drawRange(horizontalRangeDst, verticalRanges, ImageScrap::RANGE_ROWS, horizontalRangeDst, colorVertical);
showImage(horizontalRangeDst);
cv::imwrite("horizontalVerticalDst.jpg", horizontalRangeDst);
}<commit_msg>ページ番号の部分だけど切り抜くようにした<commit_after>#ifdef _DEBUG
#include "testdatapath.h"
#endif
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <qdir.h>
#include <qstringlist.h>
#include "cvutils.h"
#include "ImageScrap.h"
using namespace std;
int main(int argc, char** argv)
{
#ifdef _DEBUG
//コマンドライン引数の解析。デバッグの時は使わない
string commandArgs =
"@input | | processing one image or image named serial number"
;
cv::CommandLineParser parser(argc, argv, commandArgs);
string src = parser.get<string>(0);
#else
//string src = TEST_DATA_0;
string src = "C:\\Users\\kyokushin\\Pictures\\testData\\";
#endif
QDir dir(src.c_str());
if (!dir.exists()) {
cerr << "failed to find files" << endl;
return 1;
}
QFileInfoList fileList = dir.entryInfoList(QDir::Files);
fileList.size();
cout << "input file:" << src << endl;
int waitTime = 10;
vector<int> imageHeights;
vector<cv::Mat> pageNumbers;
cv::Mat rowImage(1, 1, CV_8UC1);
cv::Mat image;
for (int i = 0; i < fileList.size(); i++){
string fname = fileList[i].absoluteFilePath().toStdString();
cout << fname << endl;
cv::Mat colorImage = cv::imread(fname);
//画像の読み込み。グレースケール画像として読み込む
cv::cvtColor(colorImage, image, CV_BGR2GRAY);
ImageScrap scrapImage(image, ImageScrap::RANGE_ALL);
//scrapImage.show();
scrapImage.getRow(0).copyTo(rowImage);
imageHeights.push_back(rowImage.rows);//ページ番号と思われる領域を保存
pageNumbers.push_back(rowImage);
cout << "height:" << rowImage.rows << endl;
showImage(rowImage, waitTime);
}
vector<int> sortedImageHeights;
copy(imageHeights.begin(), imageHeights.end(), back_inserter(sortedImageHeights));
sort(sortedImageHeights.begin(), sortedImageHeights.end());
int start;
int acceptHeight = 10;
for (start = 0; sortedImageHeights[start] < acceptHeight; start++) {
}
int heightMed = sortedImageHeights[start + (sortedImageHeights.size() - start)/2];
int minHeight = heightMed * 0.5;
int maxHeight = heightMed * 1.5;
cout << "height median:" << heightMed << endl;
vector<int> isPageNumber;
int totalHeight = 0;
int maxWidth = 0;
int acceptedNum = 0;
for (int i = 0; i < imageHeights.size(); i++){
cout << "height:" << imageHeights[i] << endl;
bool accept = minHeight <= imageHeights[i] && imageHeights[i] <= maxHeight;
isPageNumber.push_back(accept);
if(accept){
totalHeight += imageHeights[i];
acceptedNum++;
maxWidth = max(maxWidth, pageNumbers[i].cols);
}
}
cout << "total height:" << totalHeight << endl;
const int indexWidth = 100;
cv::Mat allPageNumImage(totalHeight + acceptedNum, indexWidth + maxWidth, CV_8UC1);
allPageNumImage.setTo(255);
int currentTop = 0;
stringstream sstr;
for (int i = 0; i < isPageNumber.size(); i++){
if (isPageNumber[i]){
cv::Mat &page = pageNumbers[i];
ImageScrap scrap(page, ImageScrap::RANGE_COLS);
int numOfWords = scrap.getCols();
vector<cv::Mat> wordImages;
int pageImageWidth = 0;
for (int h = 0; h < numOfWords; h++) {
cv::Mat wordImage = scrap.getCol(h);
wordImages.push_back(wordImage);
pageImageWidth += wordImage.cols;
}
cv::Mat wordImage(page.rows, pageImageWidth + 2 * numOfWords, CV_8UC1);
wordImage.setTo(255);
int currentWidth = 0;
for (int h = 0; h < wordImages.size(); h++) {
cv::Mat& word = wordImages[h];
word.copyTo(cv::Mat(wordImage, cv::Rect(currentWidth, 0, word.cols, word.rows)));
currentWidth += word.cols + 2;
}
//showImage(wordImage);
//showImage(page, waitTime);
//cv::Mat tmpImage(allPageNumImage, cv::Rect(indexWidth, currentTop, page.cols, page.rows));
//page.copyTo(tmpImage);
cv::Mat tmpImage(allPageNumImage, cv::Rect(indexWidth, currentTop, wordImage.cols, wordImage.rows));
wordImage.copyTo(tmpImage);
sstr.str("");
sstr << i << flush;
cv::putText(allPageNumImage, sstr.str(), cv::Point(0, currentTop + page.rows),
CV_FONT_HERSHEY_COMPLEX, 0.5,
cv::Scalar(0, 0, 0), 1);
currentTop += page.rows;
cv::Mat(allPageNumImage, cv::Rect(0, currentTop, allPageNumImage.cols, 1)).setTo(0);
currentTop++;
showImage(tmpImage, waitTime);
}
else{
continue;
cv::Mat colorImage = cv::imread(fileList[i].absoluteFilePath().toStdString());
showImage(colorImage);
}
}
cout << "total" << endl;
showImage(allPageNumImage);
cv::imwrite("pagenumbers.png", allPageNumImage);
return 0;
}
void showNoneCharacterRange(const cv::Mat& image){
CV_Assert(image.channels() == 1 && image.type() == CV_8UC1);
showImage(image);
//二値化
cv::Mat binary;
int binaryMax = 1;//二値化時の最大値は1に。積分するときに白だったところか黒だったところかがわかればいい。
int binaryThreshold = 128;
cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV);
CV_Assert(binary.channels() == 1 && binary.type() == CV_8UC1);
showImage(binary);
cv::imwrite("binary.jpg", binary);
//積分画像の生成
cv::Mat integral;
cv::integral(binary, integral);
CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1);
showImage(integral);
cv::imwrite("integral.jpg", integral);
//積分画像を見やすくする処理
cv::Mat integralVisible;
double max;
double min;
cv::minMaxLoc(integral, &min, &max);//最大値だけほしいので第3引数まで。最小値は0のはずだが本当に0か確認するために使う
CV_Assert(min == 0.0);//本当に最小値が0になっているか確認
integral.convertTo(integralVisible, CV_8UC1, 255.0 / max); //betaは使わない。0-255の値をとるようにalphaを与える。
showImage(integralVisible);
cv::imwrite("integralVisible.jpg", integralVisible);
//横方向
//文字のない範囲を受け取る変数
vector<Range> horizontalRanges;
findSameValueHorizontal(integral, horizontalRanges);
//1チャンネルの原画像から3チャンネルの画像を作る
cv::Mat srcArray[] = {image, image, image};
cv::Mat srcColor;
cv::merge(srcArray, 3, srcColor);
const cv::Scalar colorVertical(0, 0, 255);
const cv::Scalar colorHorizontal(240, 176, 0);
//文字のない範囲を書き込む画像
cv::Mat horizontalRangeDst;
drawRange(srcColor, horizontalRanges, ImageScrap::RANGE_COLS, horizontalRangeDst, colorHorizontal);
showImage(horizontalRangeDst);
cv::imwrite("horizontalDst.jpg", horizontalRangeDst);
//縦方向
//文字のない範囲を受け取る変数
vector<Range> verticalRanges;
findSameValueVertical(integral, verticalRanges);
//文字のない範囲を書き込む画像
cv::Mat verticalRangeDst;
drawRange(srcColor, verticalRanges, ImageScrap::RANGE_ROWS, verticalRangeDst, colorVertical);
showImage(verticalRangeDst);
//縦横で文字のない範囲を書き込む
cv::imwrite("verticalDst.jpg", verticalRangeDst);
drawRange(horizontalRangeDst, verticalRanges, ImageScrap::RANGE_ROWS, horizontalRangeDst, colorVertical);
showImage(horizontalRangeDst);
cv::imwrite("horizontalVerticalDst.jpg", horizontalRangeDst);
}<|endoftext|> |
<commit_before>// Copyright 2015 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 "components/message_port/web_message_port_channel_impl.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/strings/string16.h"
#include "third_party/WebKit/public/platform/WebMessagePortChannelClient.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/mojo/src/mojo/public/cpp/system/message_pipe.h"
using blink::WebMessagePortChannel;
using blink::WebMessagePortChannelArray;
using blink::WebMessagePortChannelClient;
using blink::WebString;
namespace message_port {
void WebMessagePortChannelImpl::CreatePair(
blink::WebMessagePortChannel** channel1,
blink::WebMessagePortChannel** channel2) {
mojo::ScopedMessagePipeHandle pipe1;
mojo::ScopedMessagePipeHandle pipe2;
MojoResult result = mojo::CreateMessagePipe(nullptr, &pipe1, &pipe2);
if (result != MOJO_RESULT_OK) {
NOTREACHED();
return;
}
*channel1 = new WebMessagePortChannelImpl(pipe1.Pass());;
*channel2 = new WebMessagePortChannelImpl(pipe2.Pass());
}
WebMessagePortChannelImpl::WebMessagePortChannelImpl(
mojo::ScopedMessagePipeHandle pipe)
: client_(nullptr), pipe_(pipe.Pass()) {
WaitForNextMessage();
}
WebMessagePortChannelImpl::~WebMessagePortChannelImpl() {
}
void WebMessagePortChannelImpl::setClient(WebMessagePortChannelClient* client) {
client_ = client;
}
void WebMessagePortChannelImpl::destroy() {
setClient(nullptr);
delete this;
}
void WebMessagePortChannelImpl::postMessage(
const WebString& message_as_string,
WebMessagePortChannelArray* channels) {
base::string16 string = message_as_string;
std::vector<MojoHandle> handles;
if (channels) {
for (size_t i = 0; i < channels->size(); ++i) {
WebMessagePortChannelImpl* channel =
static_cast<WebMessagePortChannelImpl*>((*channels)[i]);
handles.push_back(channel->pipe_.release().value());
channel->handle_watcher_.Stop();
}
delete channels;
}
uint32_t num_handles = static_cast<uint32_t>(handles.size());
MojoHandle* handles_ptr = handles.empty() ? nullptr : &handles[0];
MojoResult result = MojoWriteMessage(
pipe_.get().value(), string.c_str(),
static_cast<uint32_t>(string.length() * sizeof(base::char16)),
handles_ptr, num_handles, MOJO_WRITE_MESSAGE_FLAG_NONE);
DCHECK_EQ(MOJO_RESULT_OK, result);
}
bool WebMessagePortChannelImpl::tryGetMessage(
WebString* message,
WebMessagePortChannelArray& channels) {
uint32_t num_bytes = 0;
uint32_t num_handles = 0;
MojoResult result = MojoReadMessage(
pipe_.get().value(), nullptr, &num_bytes, nullptr, &num_handles,
MOJO_READ_MESSAGE_FLAG_NONE);
if (result != MOJO_RESULT_RESOURCE_EXHAUSTED)
return false;
base::string16 message16;
CHECK(num_bytes % sizeof(base::char16) == 0);
message16.resize(num_bytes / sizeof(base::char16));
std::vector<MojoHandle> handles;
handles.resize(num_handles);
MojoHandle* handles_ptr = handles.empty() ? nullptr : &handles[0];
result = MojoReadMessage(
pipe_.get().value(), &message16[0], &num_bytes, handles_ptr, &num_handles,
MOJO_READ_MESSAGE_FLAG_NONE);
if (result != MOJO_RESULT_OK) {
NOTREACHED();
return false;
}
*message = message16;
WebMessagePortChannelArray ports(handles.size());
for (size_t i = 0; i < handles.size(); ++i) {
mojo::MessagePipeHandle mph(handles[i]);
mojo::ScopedMessagePipeHandle handle(mph);
ports[i] = new WebMessagePortChannelImpl(handle.Pass());
}
channels = ports;
return true;
}
void WebMessagePortChannelImpl::WaitForNextMessage() {
handle_watcher_.Start(
pipe_.get(),
MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE,
base::Bind(&WebMessagePortChannelImpl::OnMessageAvailable,
base::Unretained(this)));
}
void WebMessagePortChannelImpl::OnMessageAvailable(MojoResult result) {
DCHECK_EQ(MOJO_RESULT_OK, result);
client_->messageAvailable();
WaitForNextMessage();
}
} // namespace message_port
<commit_msg>Fix nullptr dereference in WebMessagePortChannelImpl<commit_after>// Copyright 2015 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 "components/message_port/web_message_port_channel_impl.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/strings/string16.h"
#include "third_party/WebKit/public/platform/WebMessagePortChannelClient.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/mojo/src/mojo/public/cpp/system/message_pipe.h"
using blink::WebMessagePortChannel;
using blink::WebMessagePortChannelArray;
using blink::WebMessagePortChannelClient;
using blink::WebString;
namespace message_port {
void WebMessagePortChannelImpl::CreatePair(
blink::WebMessagePortChannel** channel1,
blink::WebMessagePortChannel** channel2) {
mojo::ScopedMessagePipeHandle pipe1;
mojo::ScopedMessagePipeHandle pipe2;
MojoResult result = mojo::CreateMessagePipe(nullptr, &pipe1, &pipe2);
if (result != MOJO_RESULT_OK) {
NOTREACHED();
return;
}
*channel1 = new WebMessagePortChannelImpl(pipe1.Pass());;
*channel2 = new WebMessagePortChannelImpl(pipe2.Pass());
}
WebMessagePortChannelImpl::WebMessagePortChannelImpl(
mojo::ScopedMessagePipeHandle pipe)
: client_(nullptr), pipe_(pipe.Pass()) {
WaitForNextMessage();
}
WebMessagePortChannelImpl::~WebMessagePortChannelImpl() {
}
void WebMessagePortChannelImpl::setClient(WebMessagePortChannelClient* client) {
client_ = client;
}
void WebMessagePortChannelImpl::destroy() {
setClient(nullptr);
delete this;
}
void WebMessagePortChannelImpl::postMessage(
const WebString& message_as_string,
WebMessagePortChannelArray* channels) {
base::string16 string = message_as_string;
std::vector<MojoHandle> handles;
if (channels) {
for (size_t i = 0; i < channels->size(); ++i) {
WebMessagePortChannelImpl* channel =
static_cast<WebMessagePortChannelImpl*>((*channels)[i]);
handles.push_back(channel->pipe_.release().value());
channel->handle_watcher_.Stop();
}
delete channels;
}
uint32_t num_handles = static_cast<uint32_t>(handles.size());
MojoHandle* handles_ptr = handles.empty() ? nullptr : &handles[0];
MojoResult result = MojoWriteMessage(
pipe_.get().value(), string.c_str(),
static_cast<uint32_t>(string.length() * sizeof(base::char16)),
handles_ptr, num_handles, MOJO_WRITE_MESSAGE_FLAG_NONE);
DCHECK_EQ(MOJO_RESULT_OK, result);
}
bool WebMessagePortChannelImpl::tryGetMessage(
WebString* message,
WebMessagePortChannelArray& channels) {
uint32_t num_bytes = 0;
uint32_t num_handles = 0;
MojoResult result = MojoReadMessage(
pipe_.get().value(), nullptr, &num_bytes, nullptr, &num_handles,
MOJO_READ_MESSAGE_FLAG_NONE);
if (result != MOJO_RESULT_RESOURCE_EXHAUSTED)
return false;
base::string16 message16;
CHECK(num_bytes % sizeof(base::char16) == 0);
message16.resize(num_bytes / sizeof(base::char16));
std::vector<MojoHandle> handles;
handles.resize(num_handles);
MojoHandle* handles_ptr = handles.empty() ? nullptr : &handles[0];
result = MojoReadMessage(
pipe_.get().value(), &message16[0], &num_bytes, handles_ptr, &num_handles,
MOJO_READ_MESSAGE_FLAG_NONE);
if (result != MOJO_RESULT_OK) {
NOTREACHED();
return false;
}
*message = message16;
WebMessagePortChannelArray ports(handles.size());
for (size_t i = 0; i < handles.size(); ++i) {
mojo::MessagePipeHandle mph(handles[i]);
mojo::ScopedMessagePipeHandle handle(mph);
ports[i] = new WebMessagePortChannelImpl(handle.Pass());
}
channels = ports;
return true;
}
void WebMessagePortChannelImpl::WaitForNextMessage() {
handle_watcher_.Start(
pipe_.get(),
MOJO_HANDLE_SIGNAL_READABLE,
MOJO_DEADLINE_INDEFINITE,
base::Bind(&WebMessagePortChannelImpl::OnMessageAvailable,
base::Unretained(this)));
}
void WebMessagePortChannelImpl::OnMessageAvailable(MojoResult result) {
DCHECK_EQ(MOJO_RESULT_OK, result);
if (!client_)
return;
client_->messageAvailable();
WaitForNextMessage();
}
} // namespace message_port
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct MirroredClock {
string whatTimeIsIt(string time) {
stst ss;
ss << time;
int h, m;
char c;
ss >> h >> c >> m;
h = (12 - h) % 12;
m = (60 - m) % 60;
stst tt;
tt << h << c << m;
string sime;
getline(tt, sime);
return sime;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, string p0, bool hasAnswer, string p1) {
cout << "Test " << testNum << ": [" << "\"" << p0 << "\"";
cout << "]" << endl;
MirroredClock *obj;
string answer;
obj = new MirroredClock();
clock_t startTime = clock();
answer = obj->whatTimeIsIt(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "\"" << p1 << "\"" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "\"" << answer << "\"" << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
string p0;
string p1;
// ----- test 0 -----
disabled = false;
p0 = "10:00";
p1 = "02:00";
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = "01:15";
p1 = "10:45";
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = "03:40";
p1 = "08:20";
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = "00:00";
p1 = "00:00";
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 4 -----
disabled = false;
p0 = "11:53";
p1 = "00:07";
all_right = (disabled || KawigiEdit_RunTest(4, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>MirroredClock<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;
struct MirroredClock {
string whatTimeIsIt(string time) {
stst ss;
ss << time;
int h, m;
char c;
ss >> h >> c >> m;
h = (12 - h) % 12;
m = (60 - m) % 60;
stst tt;
if (h < 10) tt << '0';
tt << h;
tt << c;
if (m < 10) tt << '0';
tt << m;
string sime;
getline(tt, sime);
return sime;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, string p0, bool hasAnswer, string p1) {
cout << "Test " << testNum << ": [" << "\"" << p0 << "\"";
cout << "]" << endl;
MirroredClock *obj;
string answer;
obj = new MirroredClock();
clock_t startTime = clock();
answer = obj->whatTimeIsIt(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "\"" << p1 << "\"" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "\"" << answer << "\"" << endl;
if (hasAnswer) {
res = answer == p1;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
bool disabled;
bool tests_disabled;
all_right = true;
tests_disabled = false;
string p0;
string p1;
// ----- test 0 -----
disabled = false;
p0 = "10:00";
p1 = "02:00";
all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 1 -----
disabled = false;
p0 = "01:15";
p1 = "10:45";
all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 2 -----
disabled = false;
p0 = "03:40";
p1 = "08:20";
all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 3 -----
disabled = false;
p0 = "00:00";
p1 = "00:00";
all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
// ----- test 4 -----
disabled = false;
p0 = "11:53";
p1 = "00:07";
all_right = (disabled || KawigiEdit_RunTest(4, p0, true, p1) ) && all_right;
tests_disabled = tests_disabled || disabled;
// ------------------
if (all_right) {
if (tests_disabled) {
cout << "You're a stud (but some test cases were disabled)!" << endl;
} else {
cout << "You're a stud (at least on given cases)!" << endl;
}
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|> |
<commit_before>#include <math.h>
#include <assert.h>
#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
double make_kernel2D( double sigma, double* kernel, int width )
{
int W = width;
double mean = W/2;
double sum = 0.0; // For accumulating the kernel values
for (int x = 0; x < W; ++x)
for (int y = 0; y < W; ++y) {
/*
kernel[y*width+x] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) + pow((y-mean)/sigma,2.0)) )
/ (2 * M_PI * sigma * sigma);
*/
kernel[y*width+x] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) + pow((y-mean)/sigma,2.0)) );
// Accumulate the kernel values
sum += kernel[y*width+x];
}
// Normalize the kernel
for (int x = 0; x < W; ++x)
for (int y = 0; y < W; ++y)
kernel[y*width+x] /= sum;
return sum;
}
double make_kernel1D( double sigma, double* kernel, int width )
{
int W = width;
double mean = W/2;
double sum = 0.0; // For accumulating the kernel values
for (int x = 0; x < W; ++x) {
/*
kernel[x] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) ) )
/ sqrt(2 * M_PI * sigma * sigma);
*/
kernel[x] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) ) );
// Accumulate the kernel values
sum += kernel[x];
}
// Normalize the kernel
for (int x = 0; x < W; ++x)
kernel[x] /= sum;
return sum;
}
void apply2D( const double* kernel, int kwidth, double* dst, const double* src, int iwidth )
{
for( int y=0; y<iwidth; y++ ) {
for( int x=0; x<iwidth; x++ ) {
// cout << "Dest is (" << y << "," << x << ")" << endl;
dst[y*iwidth+x] = 0;
assert( 2*(kwidth/2) < kwidth );
for( int h=-kwidth/2; h<=kwidth/2; h++ ) {
for( int w=-kwidth/2; w<=kwidth/2; w++ ) {
int xw = std::min<int>( std::max<int>(x+w,0), iwidth-1 );
int yh = std::min<int>( std::max<int>(y+h,0), iwidth-1 );
const double srcval = src[ yh*iwidth + xw ];
// cout << "(" << y+h << "," << x+w << "): " << setprecision(3) << srcval << " ";
const double kerval = kernel[ (h+kwidth/2)*kwidth + (w+kwidth/2) ];
dst[y*iwidth+x] += ( srcval * kerval );
}
// cout << endl;
}
}
}
cout << endl;
}
void apply1D_row( const double* kernel, int kwidth, double* dst, const double* src, int iwidth )
{
for( int y=0; y<iwidth; y++ ) {
for( int x=0; x<iwidth; x++ ) {
dst[y*iwidth+x] = 0;
assert( 2*(kwidth/2) < kwidth );
for( int w=-kwidth/2; w<=kwidth/2; w++ ) {
int xw = std::min<int>( std::max<int>(x+w,0), iwidth-1 );
const double srcval = src[ y*iwidth + xw ];
const double kerval = kernel[ w+kwidth/2 ];
dst[y*iwidth+x] += ( srcval * kerval );
}
}
}
cout << endl;
}
void apply1D_col( const double* kernel, int kwidth, double* dst, const double* src, int iwidth )
{
for( int y=0; y<iwidth; y++ ) {
for( int x=0; x<iwidth; x++ ) {
dst[y*iwidth+x] = 0;
assert( 2*(kwidth/2) < kwidth );
for( int h=-kwidth/2; h<=kwidth/2; h++ ) {
int yh = std::min<int>( std::max<int>(y+h,0), iwidth-1 );
const double srcval = src[ yh*iwidth + x ];
const double kerval = kernel[ h+kwidth/2 ];
dst[y*iwidth+x] += ( srcval * kerval );
}
}
}
cout << endl;
}
void printit( double* image, int width )
{
for( int h=0; h<width; h++ ) {
for( int w=0; w<width; w++ ) {
cout << setprecision(3) << image[h*width+w] << " ";
}
cout << endl;
}
}
int main( )
{
const double sigma=2.0;
const int width=7; // width should be ceil(6*sigma)^2
int w1D_1 = ceil(sigma)*6+1;
double* k = new double[width*width];
cout << sigma << " -> " << w1D_1 << endl;
make_kernel2D( sigma, k, width );
// printit( k, width );
// cout << "Sum: " << sum << endl;
double* k1D = new double[width];
make_kernel1D( sigma, k1D, width );
double sigma2 = sqrt(2.0) * sigma;
int w1D_2 = ceil(sigma2)*6+1;
cout << sigma2 << " -> " << w1D_2 << endl;
double* k1D_2 = new double[w1D_2];
make_kernel1D( sigma2, k1D_2, w1D_2 );
double sigma3 = sqrt(3.0) * sigma;
int w1D_3 = ceil(sigma3)*6+1;
cout << sigma3 << " -> " << w1D_3 << endl;
double* k1D_3 = new double[w1D_3];
make_kernel1D( sigma3, k1D_3, w1D_3 );
double sigma4 = sqrt(4.0) * sigma;
int w1D_4 = ceil(sigma4)*6+1;
cout << sigma4 << " -> " << w1D_4 << endl;
double* k1D_4 = new double[w1D_4];
make_kernel1D( sigma4, k1D_4, w1D_4 );
cout << endl
<< "Applying kernel to a dummy image of 1s" << endl;
const int imagewidth = 3 * width;
double* image = new double[imagewidth*imagewidth];
for( int h=0; h<imagewidth; h++ ) {
for( int w=0; w<imagewidth; w++ ) {
image[h*imagewidth+w] = 1.0;
}
}
image[10*imagewidth+10] = 255;
double* out_i2D_1 = new double[imagewidth*imagewidth];
double* out_i2D_2 = new double[imagewidth*imagewidth];
double* out_i2D_3 = new double[imagewidth*imagewidth];
double* out_i2D_4 = new double[imagewidth*imagewidth];
double* out_i1D_1 = new double[imagewidth*imagewidth];
double* out_i1D_2 = new double[imagewidth*imagewidth];
double* out_i1D_3 = new double[imagewidth*imagewidth];
double* out_i1D_4 = new double[imagewidth*imagewidth];
double* out_i1D_5 = new double[imagewidth*imagewidth];
double* out_i1D_6 = new double[imagewidth*imagewidth];
double* out_i1D_7 = new double[imagewidth*imagewidth];
double* out_i1D_8 = new double[imagewidth*imagewidth];
apply2D( k, width, out_i2D_1, image, imagewidth );
apply2D( k, width, out_i2D_2, out_i2D_1, imagewidth );
apply2D( k, width, out_i2D_3, out_i2D_2, imagewidth );
// apply2D( k, width, out_i2D_4, out_i2D_3, imagewidth );
printit( out_i2D_3, imagewidth );
// apply1D_row( k1D, width, out_i1D_1, image, imagewidth );
// apply1D_row( k1D, width, out_i1D_2, out_i1D_1, imagewidth );
// apply1D_col( k1D, width, out_i1D_3, out_i1D_2, imagewidth );
// apply1D_col( k1D, width, out_i1D_4, out_i1D_3, imagewidth );
// printit( out_i1D_4, imagewidth );
// apply1D_row( k1D, width, out_i1D_1, image, imagewidth );
// apply1D_row( k1D, width, out_i1D_2, out_i1D_1, imagewidth );
// apply1D_row( k1D, width, out_i1D_3, out_i1D_2, imagewidth );
// apply1D_col( k1D, width, out_i1D_4, out_i1D_3, imagewidth );
// apply1D_col( k1D, width, out_i1D_5, out_i1D_4, imagewidth );
// apply1D_col( k1D, width, out_i1D_6, out_i1D_5, imagewidth );
// printit( out_i1D_6, imagewidth );
apply1D_row( k1D_3, w1D_3, out_i1D_7, image, imagewidth );
apply1D_col( k1D_3, w1D_3, out_i1D_8, out_i1D_7, imagewidth );
printit( out_i1D_8, imagewidth );
#if 0
apply2D( k, width, out_image2, out_image, imagewidth );
printit( out_image2, imagewidth );
double* k2 = new double[width*width];
apply2D( k, width, k2, k, width );
apply2D( k2, width, out_image3, image, imagewidth );
cout << "First kernel" << endl;
printit( k, width );
cout << "Second kernel" << endl;
printit( k2, width );
cout << "Final image kernel" << endl;
printit( out_image3, imagewidth );
#endif
}
<commit_msg>some more Gauss experiments<commit_after>#include <math.h>
#include <assert.h>
#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
double make_kernel2D( double sigma, double* kernel, int width )
{
int W = width;
double mean = W/2;
double sum = 0.0; // For accumulating the kernel values
for (int x = 0; x < W; ++x)
for (int y = 0; y < W; ++y) {
/*
kernel[y*width+x] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) + pow((y-mean)/sigma,2.0)) )
/ (2 * M_PI * sigma * sigma);
*/
kernel[y*width+x] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) + pow((y-mean)/sigma,2.0)) );
// Accumulate the kernel values
sum += kernel[y*width+x];
}
// Normalize the kernel
for (int x = 0; x < W; ++x)
for (int y = 0; y < W; ++y)
kernel[y*width+x] /= sum;
return sum;
}
double make_kernel1D( double sigma, double* kernel, int width )
{
int W = width;
double mean = W/2;
double sum = 0.0; // For accumulating the kernel values
for (int x = 0; x < W; ++x) {
/*
kernel[x] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) ) )
/ sqrt(2 * M_PI * sigma * sigma);
*/
kernel[x] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) ) );
// Accumulate the kernel values
sum += kernel[x];
}
// Normalize the kernel
for (int x = 0; x < W; ++x)
kernel[x] /= sum;
return sum;
}
void apply2D( const double* kernel, int kwidth, double* dst, const double* src, int iwidth )
{
for( int y=0; y<iwidth; y++ ) {
for( int x=0; x<iwidth; x++ ) {
// cout << "Dest is (" << y << "," << x << ")" << endl;
dst[y*iwidth+x] = 0;
assert( 2*(kwidth/2) < kwidth );
for( int h=-kwidth/2; h<=kwidth/2; h++ ) {
for( int w=-kwidth/2; w<=kwidth/2; w++ ) {
int xw = std::min<int>( std::max<int>(x+w,0), iwidth-1 );
int yh = std::min<int>( std::max<int>(y+h,0), iwidth-1 );
const double srcval = src[ yh*iwidth + xw ];
// cout << "(" << y+h << "," << x+w << "): " << setprecision(3) << srcval << " ";
const double kerval = kernel[ (h+kwidth/2)*kwidth + (w+kwidth/2) ];
dst[y*iwidth+x] += ( srcval * kerval );
}
// cout << endl;
}
}
}
cout << endl;
}
void apply1D_row( const double* kernel, int kwidth, double* dst, const double* src, int iwidth )
{
for( int y=0; y<iwidth; y++ ) {
for( int x=0; x<iwidth; x++ ) {
dst[y*iwidth+x] = 0;
assert( 2*(kwidth/2) < kwidth );
for( int w=-kwidth/2; w<=kwidth/2; w++ ) {
int xw = std::min<int>( std::max<int>(x+w,0), iwidth-1 );
const double srcval = src[ y*iwidth + xw ];
const double kerval = kernel[ w+kwidth/2 ];
dst[y*iwidth+x] += ( srcval * kerval );
}
}
}
cout << endl;
}
void apply1D_col( const double* kernel, int kwidth, double* dst, const double* src, int iwidth )
{
for( int y=0; y<iwidth; y++ ) {
for( int x=0; x<iwidth; x++ ) {
dst[y*iwidth+x] = 0;
assert( 2*(kwidth/2) < kwidth );
for( int h=-kwidth/2; h<=kwidth/2; h++ ) {
int yh = std::min<int>( std::max<int>(y+h,0), iwidth-1 );
const double srcval = src[ yh*iwidth + x ];
const double kerval = kernel[ h+kwidth/2 ];
dst[y*iwidth+x] += ( srcval * kerval );
}
}
}
cout << endl;
}
void printit( double* image, int width )
{
for( int h=0; h<width; h++ ) {
for( int w=0; w<width; w++ ) {
cout << setw(4) << setprecision(3) << image[h*width+w] << " ";
}
cout << endl;
}
}
int main( )
{
const double sigma=1.0;
const int width=9; // width should be ceil(6*sigma)^2
int w1D_1 = ceil(sigma)*6+1;
double* k = new double[width*width];
cout << sigma << " -> " << w1D_1 << endl;
make_kernel2D( sigma, k, width );
// printit( k, width );
// cout << "Sum: " << sum << endl;
double* k1D = new double[width];
make_kernel1D( sigma, k1D, width );
double sigma2 = sqrt(2.0) * sigma;
int w1D_2 = ceil(sigma2)*6+1;
cout << sigma2 << " -> " << w1D_2 << endl;
double* k1D_2 = new double[w1D_2];
make_kernel1D( sigma2, k1D_2, w1D_2 );
double sigma3 = sqrt(3.0) * sigma;
int w1D_3 = ceil(sigma3)*6+1;
cout << sigma3 << " -> " << w1D_3 << endl;
double* k1D_3 = new double[w1D_3];
make_kernel1D( sigma3, k1D_3, w1D_3 );
double sigma4 = sqrt(4.0) * sigma;
int w1D_4 = ceil(sigma4)*6+1;
cout << sigma4 << " -> " << w1D_4 << endl;
double* k1D_4 = new double[w1D_4];
make_kernel1D( sigma4, k1D_4, w1D_4 );
double sigma6 = sqrt(6.0) * sigma;
int w1D_6 = ceil(sigma6)*6+1;
cout << sigma6 << " -> " << w1D_6 << endl;
double* k1D_6 = new double[w1D_6];
make_kernel1D( sigma6, k1D_6, w1D_6 );
cout << endl
<< "Applying kernel to a dummy image of 1s" << endl;
const int imagewidth = 3 * width;
double* image = new double[imagewidth*imagewidth];
for( int h=0; h<imagewidth; h++ ) {
for( int w=0; w<imagewidth; w++ ) {
image[h*imagewidth+w] = 1.0;
}
}
image[10*imagewidth+10] = 255;
double* out_i2D_1 = new double[imagewidth*imagewidth];
double* out_i2D_2 = new double[imagewidth*imagewidth];
double* out_i2D_3 = new double[imagewidth*imagewidth];
double* out_i2D_4 = new double[imagewidth*imagewidth];
double* out_i2D_5 = new double[imagewidth*imagewidth];
double* out_i2D_6 = new double[imagewidth*imagewidth];
double* out_i1D_1 = new double[imagewidth*imagewidth];
double* out_i1D_2 = new double[imagewidth*imagewidth];
double* out_i1D_3 = new double[imagewidth*imagewidth];
double* out_i1D_4 = new double[imagewidth*imagewidth];
double* out_i1D_5 = new double[imagewidth*imagewidth];
double* out_i1D_6 = new double[imagewidth*imagewidth];
double* out_i1D_7 = new double[imagewidth*imagewidth];
double* out_i1D_8 = new double[imagewidth*imagewidth];
apply2D( k, width, out_i2D_1, image, imagewidth );
apply2D( k, width, out_i2D_2, out_i2D_1, imagewidth );
apply2D( k, width, out_i2D_3, out_i2D_2, imagewidth );
apply2D( k, width, out_i2D_4, out_i2D_3, imagewidth );
apply2D( k, width, out_i2D_5, out_i2D_4, imagewidth );
apply2D( k, width, out_i2D_6, out_i2D_5, imagewidth );
cout << "Applying 2D kernel with sigma " << sigma << " 6 times (kernel size " << width << "x" << width << ")" << endl;
printit( out_i2D_6, imagewidth );
// apply1D_row( k1D, width, out_i1D_1, image, imagewidth );
// apply1D_row( k1D, width, out_i1D_2, out_i1D_1, imagewidth );
// apply1D_col( k1D, width, out_i1D_3, out_i1D_2, imagewidth );
// apply1D_col( k1D, width, out_i1D_4, out_i1D_3, imagewidth );
// printit( out_i1D_4, imagewidth );
// apply1D_row( k1D, width, out_i1D_1, image, imagewidth );
// apply1D_row( k1D, width, out_i1D_2, out_i1D_1, imagewidth );
// apply1D_row( k1D, width, out_i1D_3, out_i1D_2, imagewidth );
// apply1D_col( k1D, width, out_i1D_4, out_i1D_3, imagewidth );
// apply1D_col( k1D, width, out_i1D_5, out_i1D_4, imagewidth );
// apply1D_col( k1D, width, out_i1D_6, out_i1D_5, imagewidth );
// printit( out_i1D_6, imagewidth );
// apply1D_row( k1D_3, w1D_3, out_i1D_7, image, imagewidth );
// apply1D_col( k1D_3, w1D_3, out_i1D_8, out_i1D_7, imagewidth );
// cout << "Applying 1D kernel with sigma " << sigma3 << " once horiz, once vert (kernel size " << w1D_3 << ")" << endl;
// printit( out_i1D_8, imagewidth );
apply1D_row( k1D_6, w1D_6, out_i1D_7, image, imagewidth );
apply1D_col( k1D_6, w1D_6, out_i1D_8, out_i1D_7, imagewidth );
cout << "Applying 1D kernel with sigma " << sigma3 << " once horiz, once vert (kernel size " << w1D_3 << ")" << endl;
printit( out_i1D_8, imagewidth );
#if 0
apply2D( k, width, out_image2, out_image, imagewidth );
printit( out_image2, imagewidth );
double* k2 = new double[width*width];
apply2D( k, width, k2, k, width );
apply2D( k2, width, out_image3, image, imagewidth );
cout << "First kernel" << endl;
printit( k, width );
cout << "Second kernel" << endl;
printit( k2, width );
cout << "Final image kernel" << endl;
printit( out_image3, imagewidth );
#endif
}
<|endoftext|> |
<commit_before>//
// debugger.cpp
// MusicPlayer
//
// Created by Albert Zeyer on 03.08.13.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
//
#include "debugger.h"
<commit_msg>some initial python module init code<commit_after>//
// debugger.cpp
// MusicPlayer
//
// Created by Albert Zeyer on 03.08.13.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.
//
#include <Python.h>
#include "debugger.h"
PyDoc_STRVAR(module_doc,
"debugger module.");
static PyMethodDef module_methods[] = {
{NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
#if PY_MAJOR_VERSION >= 3
PyInit_debugger(void)
#else
initdebugger(void)
#endif
{
PyObject *m;
#if PY_MAJOR_VERSION >= 3
m = PyModule_Create(&module_def);
#else
m = Py_InitModule3("debugger", module_methods, module_doc);
#endif
if (m == NULL) {
#if PY_MAJOR_VERSION >= 3
return NULL;
#else
return;
#endif
}
#if PY_MAJOR_VERSION >= 3
return m;
#else
return;
#endif
error:
#if PY_MAJOR_VERSION >= 3
Py_DECREF(m);
return NULL;
#else
return;
#endif
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) <2015> <Stephan Gatzka>
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE websocket_peer
#include <boost/test/unit_test.hpp>
#include "buffered_reader.h"
#include "generated/os_config.h"
#include "http_connection.h"
#include "peer.h"
#include "socket.h"
#include "websocket_peer.h"
static const uint8_t WS_HEADER_FIN = 0x80;
static const uint8_t WS_HEADER_MASK = 0x80;
static const uint8_t WS_OPCODE_CLOSE = 0x08;
static unsigned int num_close_called = 0;
static uint8_t write_buffer[70000];
static uint8_t *write_buffer_ptr;
static error_handler br_error_handler = NULL;
static void *br_error_context = NULL;
extern "C" {
ssize_t socket_read(socket_type sock, void *buf, size_t count)
{
(void)sock;
(void)count;
uint64_t number_of_timeouts = 1;
::memcpy(buf, &number_of_timeouts, sizeof(number_of_timeouts));
return 8;
}
int socket_close(socket_type sock)
{
(void)sock;
return 0;
}
static int br_read_exactly(void *this_ptr, size_t num, read_handler handler, void *handler_context) {
(void)this_ptr;
(void)num;
(void)handler;
(void)handler_context;
return 0;
}
static int br_read_until(void *this_ptr, const char *delim, read_handler handler, void *handler_context) {
(void)this_ptr;
(void)delim;
(void)handler;
(void)handler_context;
return 0;
}
static int br_writev(void *this_ptr, struct socket_io_vector *io_vec, unsigned int count)
{
(void)this_ptr;
size_t complete_length = 0;
for (unsigned int i = 0; i < count; i++) {
::memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len);
write_buffer_ptr += io_vec[i].iov_len;
complete_length += io_vec[i].iov_len;
}
return complete_length;
}
static int br_close(void *this_ptr) {
(void)this_ptr;
num_close_called++;
return 0;
}
static void br_set_error_handler(void *this_ptr, error_handler handler, void *error_context) {
(void)this_ptr;
br_error_handler = handler;
br_error_context = error_context;
return;
}
}
struct F {
F()
{
num_close_called = 0;
write_buffer_ptr = write_buffer;
}
~F()
{
}
};
static bool is_close_frame(enum ws_status_code code)
{
const uint8_t *ptr = write_buffer;
uint8_t header;
::memcpy(&header, ptr, sizeof(header));
if ((header & WS_HEADER_FIN) != WS_HEADER_FIN) {
return false;
}
if ((header & WS_OPCODE_CLOSE) != WS_OPCODE_CLOSE) {
return false;
}
ptr += sizeof(header);
uint8_t length;
::memcpy(&length, ptr, sizeof(length));
if ((length & WS_HEADER_MASK) == WS_HEADER_MASK) {
return false;
}
if (length != 2) {
return false;
}
ptr += sizeof(length);
uint16_t status_code;
::memcpy(&status_code, ptr, sizeof(status_code));
status_code = be16toh(status_code);
if (status_code != code) {
return false;
}
return true;
}
BOOST_AUTO_TEST_CASE(test_connection_closed_when_destryoing_peers)
{
F f;
struct buffered_reader br;
br.this_ptr = NULL;
br.close = br_close;
br.read_exactly = br_read_exactly;
br.read_until = br_read_until;
br.set_error_handler = br_set_error_handler;
br.writev = br_writev;
struct http_server server;
server.ev.loop = NULL;
struct http_connection *connection = alloc_http_connection();
init_http_connection(connection, &server, &br, false);
int ret = alloc_websocket_peer(connection);
BOOST_REQUIRE_MESSAGE(ret == 0, "alloc_websocket_peer did not return 0");
struct websocket *socket = (struct websocket *)connection->parser.data;
socket->upgrade_complete = true;
destroy_all_peers();
BOOST_CHECK_MESSAGE(num_close_called == 1, "Close of buffered_reader was not called when destryoing all peers!");
BOOST_CHECK_MESSAGE(is_close_frame(WS_CLOSE_GOING_AWAY), "No close frame sent when destryoing all peers!");
}
BOOST_AUTO_TEST_CASE(test_connection_closed_when_buffered_reader_gots_error)
{
F f;
struct buffered_reader br;
br.this_ptr = NULL;
br.close = br_close;
br.read_exactly = br_read_exactly;
br.read_until = br_read_until;
br.set_error_handler = br_set_error_handler;
br.writev = br_writev;
struct http_server server;
server.ev.loop = NULL;
struct http_connection *connection = alloc_http_connection();
init_http_connection(connection, &server, &br, false);
int ret = alloc_websocket_peer(connection);
BOOST_REQUIRE_MESSAGE(ret == 0, "alloc_websocket_peer did not return 0");
struct websocket *socket = (struct websocket *)connection->parser.data;
socket->upgrade_complete = true;
br_error_handler(br_error_context);
BOOST_CHECK_MESSAGE(num_close_called == 1, "Close of buffered_reader was not called when buffered_reader has an error!");
BOOST_CHECK_MESSAGE(is_close_frame(WS_CLOSE_GOING_AWAY), "No close frame sent when bufferd_reader has an error!");
}
<commit_msg>Test that connection is closed when receiving a close frame.<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) <2015> <Stephan Gatzka>
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE websocket_peer
#include <boost/test/unit_test.hpp>
#include "buffered_reader.h"
#include "generated/os_config.h"
#include "http_connection.h"
#include "peer.h"
#include "socket.h"
#include "websocket_peer.h"
static const uint8_t WS_HEADER_FIN = 0x80;
static const uint8_t WS_HEADER_MASK = 0x80;
static const uint8_t WS_OPCODE_CLOSE = 0x08;
static unsigned int num_close_called = 0;
static uint8_t read_buffer[5000];
static size_t read_buffer_length;
static uint8_t *read_buffer_ptr;
static uint8_t write_buffer[70000];
static uint8_t *write_buffer_ptr;
static error_handler br_error_handler = NULL;
static void *br_error_context = NULL;
extern "C" {
ssize_t socket_read(socket_type sock, void *buf, size_t count)
{
(void)sock;
(void)count;
uint64_t number_of_timeouts = 1;
::memcpy(buf, &number_of_timeouts, sizeof(number_of_timeouts));
return 8;
}
int socket_close(socket_type sock)
{
(void)sock;
return 0;
}
static int br_read_exactly(void *this_ptr, size_t num, read_handler handler, void *handler_context) {
(void)this_ptr;
uint8_t *ptr = read_buffer_ptr;
read_buffer_ptr += num;
if ((ptr - read_buffer) < (ssize_t)read_buffer_length) {
handler(handler_context, ptr, num);
}
return 0;
}
static int br_read_until(void *this_ptr, const char *delim, read_handler handler, void *handler_context) {
(void)this_ptr;
(void)delim;
(void)handler;
(void)handler_context;
return 0;
}
static int br_writev(void *this_ptr, struct socket_io_vector *io_vec, unsigned int count)
{
(void)this_ptr;
size_t complete_length = 0;
for (unsigned int i = 0; i < count; i++) {
::memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len);
write_buffer_ptr += io_vec[i].iov_len;
complete_length += io_vec[i].iov_len;
}
return complete_length;
}
static int br_close(void *this_ptr) {
(void)this_ptr;
num_close_called++;
return 0;
}
static void br_set_error_handler(void *this_ptr, error_handler handler, void *error_context) {
(void)this_ptr;
br_error_handler = handler;
br_error_context = error_context;
return;
}
}
struct F {
F()
{
num_close_called = 0;
write_buffer_ptr = write_buffer;
read_buffer_ptr = read_buffer;
br.this_ptr = NULL;
br.close = br_close;
br.read_exactly = br_read_exactly;
br.read_until = br_read_until;
br.set_error_handler = br_set_error_handler;
br.writev = br_writev;
}
~F()
{
}
struct buffered_reader br;
};
static void mask_payload(uint8_t *ptr, size_t length, uint8_t mask[4])
{
for (unsigned int i = 0; i < length; i++) {
uint8_t byte = ptr[i] ^ mask[i % 4];
ptr[i] = byte;
}
}
static void fill_payload(uint8_t *ptr, const uint8_t *payload, uint64_t length, bool shall_mask, uint8_t mask[4])
{
::memcpy(ptr, payload, length);
if (shall_mask) {
mask_payload(ptr, length, mask);
}
}
static void prepare_message(uint8_t type, uint8_t *buffer, uint64_t length, bool shall_mask, uint8_t mask[4])
{
uint8_t *ptr = read_buffer;
read_buffer_length = 0;
uint8_t header = 0x00;
header |= WS_HEADER_FIN;
header |= type;
::memcpy(ptr, &header, sizeof(header));
ptr += sizeof(header);
read_buffer_length += sizeof(header);
uint8_t first_length = 0x00;
if (shall_mask) {
first_length |= WS_HEADER_MASK;
}
if (length < 126) {
first_length = first_length | (uint8_t)length;
::memcpy(ptr, &first_length, sizeof(first_length));
ptr += sizeof(first_length);
read_buffer_length += sizeof(first_length);
} else if (length <= 65535) {
first_length = first_length | 126;
::memcpy(ptr, &first_length, sizeof(first_length));
ptr += sizeof(first_length);
read_buffer_length += sizeof(first_length);
uint16_t len = (uint16_t)length;
len = htobe16(len);
::memcpy(ptr, &len, sizeof(len));
ptr += sizeof(len);
read_buffer_length += sizeof(len);
} else {
first_length = first_length | 127;
::memcpy(ptr, &first_length, sizeof(first_length));
ptr += sizeof(first_length);
read_buffer_length += sizeof(first_length);
uint64_t len = htobe64(length);
::memcpy(ptr, &len, sizeof(length));
ptr += sizeof(len);
read_buffer_length += sizeof(len);
}
if (shall_mask) {
::memcpy(ptr, mask, 4);
ptr += 4;
read_buffer_length += 4;
}
fill_payload(ptr, buffer, length, shall_mask, mask);
read_buffer_length += length;
}
static bool is_close_frame(enum ws_status_code code)
{
const uint8_t *ptr = write_buffer;
uint8_t header;
::memcpy(&header, ptr, sizeof(header));
if ((header & WS_HEADER_FIN) != WS_HEADER_FIN) {
return false;
}
if ((header & WS_OPCODE_CLOSE) != WS_OPCODE_CLOSE) {
return false;
}
ptr += sizeof(header);
uint8_t length;
::memcpy(&length, ptr, sizeof(length));
if ((length & WS_HEADER_MASK) == WS_HEADER_MASK) {
return false;
}
if (length != 2) {
return false;
}
ptr += sizeof(length);
uint16_t status_code;
::memcpy(&status_code, ptr, sizeof(status_code));
status_code = be16toh(status_code);
if (status_code != code) {
return false;
}
return true;
}
BOOST_AUTO_TEST_CASE(test_connection_closed_when_destryoing_peers)
{
F f;
struct http_server server;
server.ev.loop = NULL;
struct http_connection *connection = alloc_http_connection();
init_http_connection(connection, &server, &f.br, false);
int ret = alloc_websocket_peer(connection);
BOOST_REQUIRE_MESSAGE(ret == 0, "alloc_websocket_peer did not return 0");
struct websocket *socket = (struct websocket *)connection->parser.data;
socket->upgrade_complete = true;
destroy_all_peers();
BOOST_CHECK_MESSAGE(num_close_called == 1, "Close of buffered_reader was not called when destryoing all peers!");
BOOST_CHECK_MESSAGE(is_close_frame(WS_CLOSE_GOING_AWAY), "No close frame sent when destryoing all peers!");
}
BOOST_AUTO_TEST_CASE(test_connection_closed_when_buffered_reader_gots_error)
{
F f;
struct http_server server;
server.ev.loop = NULL;
struct http_connection *connection = alloc_http_connection();
init_http_connection(connection, &server, &f.br, false);
int ret = alloc_websocket_peer(connection);
BOOST_REQUIRE_MESSAGE(ret == 0, "alloc_websocket_peer did not return 0");
struct websocket *socket = (struct websocket *)connection->parser.data;
socket->upgrade_complete = true;
br_error_handler(br_error_context);
BOOST_CHECK_MESSAGE(num_close_called == 1, "Close of buffered_reader was not called when buffered_reader has an error!");
BOOST_CHECK_MESSAGE(is_close_frame(WS_CLOSE_GOING_AWAY), "No close frame sent when bufferd_reader has an error!");
}
BOOST_AUTO_TEST_CASE(test_connection_closed_when_receiving_fin)
{
F f;
struct http_server server;
server.ev.loop = NULL;
struct http_connection *connection = alloc_http_connection();
init_http_connection(connection, &server, &f.br, false);
int ret = alloc_websocket_peer(connection);
BOOST_REQUIRE_MESSAGE(ret == 0, "alloc_websocket_peer did not return 0");
struct websocket *socket = (struct websocket *)connection->parser.data;
socket->upgrade_complete = true;
uint8_t mask[4] = {0xaa, 0x55, 0xcc, 0x11};
prepare_message(WS_OPCODE_CLOSE, NULL, 0, true, mask);
ws_get_header(socket, read_buffer_ptr++, read_buffer_length);
BOOST_CHECK_MESSAGE(num_close_called == 1, "Close of buffered_reader was not called when receiving a close frame!");
BOOST_CHECK_MESSAGE(is_close_frame(WS_CLOSE_GOING_AWAY), "No close frame sent when receiving a close frame!");
}
<|endoftext|> |
<commit_before>/*
Copyright 2012 Ulrik Mikaelsson <[email protected]>
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 "server.hpp"
#include <boost/asio/placeholders.hpp>
#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include "buildconf.hpp"
#include "client.hpp"
#include "config.hpp"
#include "../lib/loopfilter.hpp"
using namespace std;
namespace asio = boost::asio;
namespace fs = boost::filesystem;
using namespace bithorded;
namespace bithorded {
log4cplus::Logger serverLog = log4cplus::Logger::getInstance("server");
}
BindError::BindError(bithorde::Status status):
runtime_error("findAsset failed with " + bithorde::Status_Name(status)),
status(status)
{
}
void ConnectionList::inspect(management::InfoList& target) const
{
for (auto iter=begin(); iter != end(); iter++) {
if (auto conn = iter->second.lock()) {
target.append(iter->first, *conn);
}
}
}
void ConnectionList::describe(management::Info& target) const
{
target << size() << " connections";
}
bithorded::Config::Client null_client;
Server::Server(asio::io_service& ioSvc, Config& cfg) :
_cfg(cfg),
_ioSvc(ioSvc),
_timerSvc(new TimerService(ioSvc)),
_tcpListener(ioSvc),
_localListener(ioSvc),
_router(*this),
_cache(ioSvc, _router, cfg.cacheDir, static_cast<intmax_t>(cfg.cacheSizeMB)*1024*1024)
{
for (auto iter=_cfg.sources.begin(); iter != _cfg.sources.end(); iter++)
_assetStores.push_back( unique_ptr<source::Store>(new source::Store(ioSvc, iter->name, iter->root)) );
for (auto iter=_cfg.friends.begin(); iter != _cfg.friends.end(); iter++)
_router.addFriend(*iter);
if (_cfg.tcpPort) {
auto tcpPort = asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), _cfg.tcpPort);
_tcpListener.open(tcpPort.protocol());
_tcpListener.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
_tcpListener.bind(tcpPort);
_tcpListener.listen();
LOG4CPLUS_INFO(serverLog, "Listening on tcp port " << _cfg.tcpPort);
waitForTCPConnection();
}
if (!_cfg.unixSocket.empty()) {
if (fs::exists(_cfg.unixSocket))
fs::remove(_cfg.unixSocket);
long permissions = strtol(_cfg.unixPerms.c_str(), NULL, 0);
if (!permissions)
throw std::runtime_error("Failed to parse permissions for UNIX-socket");
auto localPort = asio::local::stream_protocol::endpoint(_cfg.unixSocket);
_localListener.open(localPort.protocol());
_localListener.set_option(boost::asio::local::stream_protocol::acceptor::reuse_address(true));
_localListener.bind(localPort);
_localListener.listen(4);
fs::permissions(localPort.path(), (fs::perms)permissions);
LOG4CPLUS_INFO(serverLog, "Listening on local socket " << localPort);
waitForLocalConnection();
}
if (_cfg.inspectPort) {
_httpInterface.reset(new http::server::server(_ioSvc, "127.0.0.1", _cfg.inspectPort, *this));
LOG4CPLUS_INFO(serverLog, "Inspection interface listening on port " << _cfg.inspectPort);
}
LOG4CPLUS_INFO(serverLog, "Server started, version " << bithorde::build_version);
}
asio::io_service& Server::ioService()
{
return _ioSvc;
}
void Server::waitForTCPConnection()
{
boost::shared_ptr<asio::ip::tcp::socket> sock = boost::make_shared<asio::ip::tcp::socket>(_ioSvc);
_tcpListener.async_accept(*sock, boost::bind(&Server::onTCPConnected, this, sock, asio::placeholders::error));
}
void Server::onTCPConnected(boost::shared_ptr< asio::ip::tcp::socket >& socket, const boost::system::error_code& ec)
{
if (!ec) {
hookup(socket, null_client);
waitForTCPConnection();
}
}
void Server::hookup ( boost::shared_ptr< asio::ip::tcp::socket >& socket, const Config::Client& client)
{
bithorded::Client::Ptr c = bithorded::Client::create(*this);
auto conn = bithorde::Connection::create(_ioSvc, boost::make_shared<bithorde::ConnectionStats>(_timerSvc), socket);
c->setSecurity(client.key, (bithorde::CipherType)client.cipher);
if (client.name.empty())
c->hookup(conn);
else
c->connect(conn, client.name);
clientConnected(c);
}
void Server::waitForLocalConnection()
{
boost::shared_ptr<asio::local::stream_protocol::socket> sock = boost::make_shared<asio::local::stream_protocol::socket>(_ioSvc);
_localListener.async_accept(*sock, boost::bind(&Server::onLocalConnected, this, sock, asio::placeholders::error));
}
void Server::onLocalConnected(boost::shared_ptr< boost::asio::local::stream_protocol::socket >& socket, const boost::system::error_code& ec)
{
if (!ec) {
bithorded::Client::Ptr c = bithorded::Client::create(*this);
c->hookup(bithorde::Connection::create(_ioSvc, boost::make_shared<bithorde::ConnectionStats>(_timerSvc), socket));
clientConnected(c);
waitForLocalConnection();
}
}
void Server::inspect(management::InfoList& target) const
{
target.append("router", _router);
target.append("connections", _connections);
if (_cache.enabled())
target.append("cache", _cache);
for (auto iter=_assetStores.begin(); iter!=_assetStores.end(); iter++) {
const auto& store = **iter;
target.append("source."+store.label(), store);
}
}
void Server::clientConnected(const bithorded::Client::Ptr& client)
{
// When storing a client-copy in the bound reference, we make sure the Client isn't
// destroyed until the disconnected signal calls clientDisconnected, which releases
// the reference
client->disconnected.connect(boost::bind(&Server::clientDisconnected, this, client));
client->authenticated.connect(boost::bind(&Server::clientAuthenticated, this, Client::WeakPtr(client)));
}
void Server::clientAuthenticated(const bithorded::Client::WeakPtr& client_) {
if (Client::Ptr client = client_.lock()) {
_connections.set(client->peerName(), client);
_router.onConnected(client);
}
}
void Server::clientDisconnected(bithorded::Client::Ptr& client)
{
LOG4CPLUS_INFO(serverLog, "Disconnected: " << client->peerName());
_router.onDisconnected(client);
// Will destroy the client, unless others are holding references.
client.reset();
}
const bithorded::Config::Client& Server::getClientConfig(const string& name)
{
for (auto iter = _cfg.friends.begin(); iter != _cfg.friends.end(); iter++) {
if (name == iter->name)
return *iter;
}
for (auto iter = _cfg.clients.begin(); iter != _cfg.clients.end(); iter++) {
if (name == iter->name)
return *iter;
}
return null_client;
}
IAsset::Ptr Server::async_linkAsset(const boost::filesystem::path& filePath)
{
for (auto iter=_assetStores.begin(); iter != _assetStores.end(); iter++) {
if (auto res = (*iter)->addAsset(filePath))
return res;
}
return ASSET_NONE;
}
IAsset::Ptr Server::async_findAsset(const bithorde::BindRead& req)
{
if (!_loopFilter.test_and_set(req.uuid())) {
LOG4CPLUS_INFO(serverLog, "Looped on uuid " << req.uuid());
throw BindError(bithorde::WOULD_LOOP);
}
for (auto iter=_assetStores.begin(); iter != _assetStores.end(); iter++) {
if (auto asset = (*iter)->findAsset(req))
return asset;
}
if (auto asset = _cache.findAsset(req))
return asset;
else
return _router.findAsset(req);
}
IAsset::Ptr Server::prepareUpload(uint64_t size)
{
return _cache.prepareUpload(size);
}
<commit_msg>[bithorded/server/server]Change socket-permission-code to use plain POSIX since older boost::fs doesn't have permissions-manipulation.<commit_after>/*
Copyright 2012 Ulrik Mikaelsson <[email protected]>
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 "server.hpp"
#include <boost/asio/placeholders.hpp>
#include <boost/filesystem.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
#include <system_error>
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include "buildconf.hpp"
#include "client.hpp"
#include "config.hpp"
#include "../lib/loopfilter.hpp"
using namespace std;
namespace asio = boost::asio;
namespace fs = boost::filesystem;
using namespace bithorded;
namespace bithorded {
log4cplus::Logger serverLog = log4cplus::Logger::getInstance("server");
}
BindError::BindError(bithorde::Status status):
runtime_error("findAsset failed with " + bithorde::Status_Name(status)),
status(status)
{
}
void ConnectionList::inspect(management::InfoList& target) const
{
for (auto iter=begin(); iter != end(); iter++) {
if (auto conn = iter->second.lock()) {
target.append(iter->first, *conn);
}
}
}
void ConnectionList::describe(management::Info& target) const
{
target << size() << " connections";
}
bithorded::Config::Client null_client;
Server::Server(asio::io_service& ioSvc, Config& cfg) :
_cfg(cfg),
_ioSvc(ioSvc),
_timerSvc(new TimerService(ioSvc)),
_tcpListener(ioSvc),
_localListener(ioSvc),
_router(*this),
_cache(ioSvc, _router, cfg.cacheDir, static_cast<intmax_t>(cfg.cacheSizeMB)*1024*1024)
{
for (auto iter=_cfg.sources.begin(); iter != _cfg.sources.end(); iter++)
_assetStores.push_back( unique_ptr<source::Store>(new source::Store(ioSvc, iter->name, iter->root)) );
for (auto iter=_cfg.friends.begin(); iter != _cfg.friends.end(); iter++)
_router.addFriend(*iter);
if (_cfg.tcpPort) {
auto tcpPort = asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), _cfg.tcpPort);
_tcpListener.open(tcpPort.protocol());
_tcpListener.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
_tcpListener.bind(tcpPort);
_tcpListener.listen();
LOG4CPLUS_INFO(serverLog, "Listening on tcp port " << _cfg.tcpPort);
waitForTCPConnection();
}
if (!_cfg.unixSocket.empty()) {
if (fs::exists(_cfg.unixSocket))
fs::remove(_cfg.unixSocket);
mode_t permissions = strtol(_cfg.unixPerms.c_str(), NULL, 0);
if (!permissions)
throw std::runtime_error("Failed to parse permissions for UNIX-socket");
auto localPort = asio::local::stream_protocol::endpoint(_cfg.unixSocket);
_localListener.open(localPort.protocol());
_localListener.set_option(boost::asio::local::stream_protocol::acceptor::reuse_address(true));
_localListener.bind(localPort);
_localListener.listen(4);
if (chmod(localPort.path().c_str(), permissions) == -1)
throw std::system_error(errno, std::system_category());
LOG4CPLUS_INFO(serverLog, "Listening on local socket " << localPort);
waitForLocalConnection();
}
if (_cfg.inspectPort) {
_httpInterface.reset(new http::server::server(_ioSvc, "127.0.0.1", _cfg.inspectPort, *this));
LOG4CPLUS_INFO(serverLog, "Inspection interface listening on port " << _cfg.inspectPort);
}
LOG4CPLUS_INFO(serverLog, "Server started, version " << bithorde::build_version);
}
asio::io_service& Server::ioService()
{
return _ioSvc;
}
void Server::waitForTCPConnection()
{
boost::shared_ptr<asio::ip::tcp::socket> sock = boost::make_shared<asio::ip::tcp::socket>(_ioSvc);
_tcpListener.async_accept(*sock, boost::bind(&Server::onTCPConnected, this, sock, asio::placeholders::error));
}
void Server::onTCPConnected(boost::shared_ptr< asio::ip::tcp::socket >& socket, const boost::system::error_code& ec)
{
if (!ec) {
hookup(socket, null_client);
waitForTCPConnection();
}
}
void Server::hookup ( boost::shared_ptr< asio::ip::tcp::socket >& socket, const Config::Client& client)
{
bithorded::Client::Ptr c = bithorded::Client::create(*this);
auto conn = bithorde::Connection::create(_ioSvc, boost::make_shared<bithorde::ConnectionStats>(_timerSvc), socket);
c->setSecurity(client.key, (bithorde::CipherType)client.cipher);
if (client.name.empty())
c->hookup(conn);
else
c->connect(conn, client.name);
clientConnected(c);
}
void Server::waitForLocalConnection()
{
boost::shared_ptr<asio::local::stream_protocol::socket> sock = boost::make_shared<asio::local::stream_protocol::socket>(_ioSvc);
_localListener.async_accept(*sock, boost::bind(&Server::onLocalConnected, this, sock, asio::placeholders::error));
}
void Server::onLocalConnected(boost::shared_ptr< boost::asio::local::stream_protocol::socket >& socket, const boost::system::error_code& ec)
{
if (!ec) {
bithorded::Client::Ptr c = bithorded::Client::create(*this);
c->hookup(bithorde::Connection::create(_ioSvc, boost::make_shared<bithorde::ConnectionStats>(_timerSvc), socket));
clientConnected(c);
waitForLocalConnection();
}
}
void Server::inspect(management::InfoList& target) const
{
target.append("router", _router);
target.append("connections", _connections);
if (_cache.enabled())
target.append("cache", _cache);
for (auto iter=_assetStores.begin(); iter!=_assetStores.end(); iter++) {
const auto& store = **iter;
target.append("source."+store.label(), store);
}
}
void Server::clientConnected(const bithorded::Client::Ptr& client)
{
// When storing a client-copy in the bound reference, we make sure the Client isn't
// destroyed until the disconnected signal calls clientDisconnected, which releases
// the reference
client->disconnected.connect(boost::bind(&Server::clientDisconnected, this, client));
client->authenticated.connect(boost::bind(&Server::clientAuthenticated, this, Client::WeakPtr(client)));
}
void Server::clientAuthenticated(const bithorded::Client::WeakPtr& client_) {
if (Client::Ptr client = client_.lock()) {
_connections.set(client->peerName(), client);
_router.onConnected(client);
}
}
void Server::clientDisconnected(bithorded::Client::Ptr& client)
{
LOG4CPLUS_INFO(serverLog, "Disconnected: " << client->peerName());
_router.onDisconnected(client);
// Will destroy the client, unless others are holding references.
client.reset();
}
const bithorded::Config::Client& Server::getClientConfig(const string& name)
{
for (auto iter = _cfg.friends.begin(); iter != _cfg.friends.end(); iter++) {
if (name == iter->name)
return *iter;
}
for (auto iter = _cfg.clients.begin(); iter != _cfg.clients.end(); iter++) {
if (name == iter->name)
return *iter;
}
return null_client;
}
IAsset::Ptr Server::async_linkAsset(const boost::filesystem::path& filePath)
{
for (auto iter=_assetStores.begin(); iter != _assetStores.end(); iter++) {
if (auto res = (*iter)->addAsset(filePath))
return res;
}
return ASSET_NONE;
}
IAsset::Ptr Server::async_findAsset(const bithorde::BindRead& req)
{
if (!_loopFilter.test_and_set(req.uuid())) {
LOG4CPLUS_INFO(serverLog, "Looped on uuid " << req.uuid());
throw BindError(bithorde::WOULD_LOOP);
}
for (auto iter=_assetStores.begin(); iter != _assetStores.end(); iter++) {
if (auto asset = (*iter)->findAsset(req))
return asset;
}
if (auto asset = _cache.findAsset(req))
return asset;
else
return _router.findAsset(req);
}
IAsset::Ptr Server::prepareUpload(uint64_t size)
{
return _cache.prepareUpload(size);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/trace_storage.h"
#include <string.h>
#include <algorithm>
#include <limits>
#include "perfetto/ext/base/no_destructor.h"
namespace perfetto {
namespace trace_processor {
namespace {
template <typename T>
void MaybeUpdateMinMax(T begin_it,
T end_it,
int64_t* min_value,
int64_t* max_value) {
if (begin_it == end_it) {
return;
}
std::pair<T, T> minmax = std::minmax_element(begin_it, end_it);
*min_value = std::min(*min_value, *minmax.first);
*max_value = std::max(*max_value, *minmax.second);
}
std::vector<const char*> CreateRefTypeStringMap() {
std::vector<const char*> map(RefType::kRefMax);
map[RefType::kRefNoRef] = nullptr;
map[RefType::kRefUtid] = "utid";
map[RefType::kRefCpuId] = "cpu";
map[RefType::kRefGpuId] = "gpu";
map[RefType::kRefIrq] = "irq";
map[RefType::kRefSoftIrq] = "softirq";
map[RefType::kRefUpid] = "upid";
return map;
}
} // namespace
const std::vector<const char*>& GetRefTypeStringMap() {
static const base::NoDestructor<std::vector<const char*>> map(
CreateRefTypeStringMap());
return map.ref();
}
TraceStorage::TraceStorage() {
// Upid/utid 0 is reserved for idle processes/threads.
unique_processes_.emplace_back(0);
unique_threads_.emplace_back(0);
}
TraceStorage::~TraceStorage() {}
void TraceStorage::ResetStorage() {
*this = TraceStorage();
}
uint32_t TraceStorage::SqlStats::RecordQueryBegin(const std::string& query,
int64_t time_queued,
int64_t time_started) {
if (queries_.size() >= kMaxLogEntries) {
queries_.pop_front();
times_queued_.pop_front();
times_started_.pop_front();
times_first_next_.pop_front();
times_ended_.pop_front();
popped_queries_++;
}
queries_.push_back(query);
times_queued_.push_back(time_queued);
times_started_.push_back(time_started);
times_first_next_.push_back(0);
times_ended_.push_back(0);
return static_cast<uint32_t>(popped_queries_ + queries_.size() - 1);
}
void TraceStorage::SqlStats::RecordQueryFirstNext(uint32_t row,
int64_t time_first_next) {
// This means we've popped this query off the queue of queries before it had
// a chance to finish. Just silently drop this number.
if (popped_queries_ > row)
return;
uint32_t queue_row = row - popped_queries_;
PERFETTO_DCHECK(queue_row < queries_.size());
times_first_next_[queue_row] = time_first_next;
}
void TraceStorage::SqlStats::RecordQueryEnd(uint32_t row, int64_t time_ended) {
// This means we've popped this query off the queue of queries before it had
// a chance to finish. Just silently drop this number.
if (popped_queries_ > row)
return;
uint32_t queue_row = row - popped_queries_;
PERFETTO_DCHECK(queue_row < queries_.size());
times_ended_[queue_row] = time_ended;
}
std::pair<int64_t, int64_t> TraceStorage::GetTraceTimestampBoundsNs() const {
int64_t start_ns = std::numeric_limits<int64_t>::max();
int64_t end_ns = std::numeric_limits<int64_t>::min();
MaybeUpdateMinMax(slices_.start_ns().begin(), slices_.start_ns().end(),
&start_ns, &end_ns);
MaybeUpdateMinMax(counter_values_.timestamps().begin(),
counter_values_.timestamps().end(), &start_ns, &end_ns);
MaybeUpdateMinMax(instants_.timestamps().begin(),
instants_.timestamps().end(), &start_ns, &end_ns);
MaybeUpdateMinMax(nestable_slices_.start_ns().begin(),
nestable_slices_.start_ns().end(), &start_ns, &end_ns);
MaybeUpdateMinMax(android_log_.timestamps().begin(),
android_log_.timestamps().end(), &start_ns, &end_ns);
MaybeUpdateMinMax(raw_events_.timestamps().begin(),
raw_events_.timestamps().end(), &start_ns, &end_ns);
if (start_ns == std::numeric_limits<int64_t>::max()) {
return std::make_pair(0, 0);
}
return std::make_pair(start_ns, end_ns);
}
} // namespace trace_processor
} // namespace perfetto
<commit_msg>[processor] Add string names for async ref types<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/trace_processor/trace_storage.h"
#include <string.h>
#include <algorithm>
#include <limits>
#include "perfetto/ext/base/no_destructor.h"
namespace perfetto {
namespace trace_processor {
namespace {
template <typename T>
void MaybeUpdateMinMax(T begin_it,
T end_it,
int64_t* min_value,
int64_t* max_value) {
if (begin_it == end_it) {
return;
}
std::pair<T, T> minmax = std::minmax_element(begin_it, end_it);
*min_value = std::min(*min_value, *minmax.first);
*max_value = std::max(*max_value, *minmax.second);
}
std::vector<const char*> CreateRefTypeStringMap() {
std::vector<const char*> map(RefType::kRefMax);
map[RefType::kRefNoRef] = nullptr;
map[RefType::kRefUtid] = "utid";
map[RefType::kRefCpuId] = "cpu";
map[RefType::kRefGpuId] = "gpu";
map[RefType::kRefIrq] = "irq";
map[RefType::kRefSoftIrq] = "softirq";
map[RefType::kRefUpid] = "upid";
map[RefType::kRefGlobalAsyncTrack] = "global_async_track";
map[RefType::kRefProcessAsyncTrack] = "process_async_track";
return map;
}
} // namespace
const std::vector<const char*>& GetRefTypeStringMap() {
static const base::NoDestructor<std::vector<const char*>> map(
CreateRefTypeStringMap());
return map.ref();
}
TraceStorage::TraceStorage() {
// Upid/utid 0 is reserved for idle processes/threads.
unique_processes_.emplace_back(0);
unique_threads_.emplace_back(0);
}
TraceStorage::~TraceStorage() {}
void TraceStorage::ResetStorage() {
*this = TraceStorage();
}
uint32_t TraceStorage::SqlStats::RecordQueryBegin(const std::string& query,
int64_t time_queued,
int64_t time_started) {
if (queries_.size() >= kMaxLogEntries) {
queries_.pop_front();
times_queued_.pop_front();
times_started_.pop_front();
times_first_next_.pop_front();
times_ended_.pop_front();
popped_queries_++;
}
queries_.push_back(query);
times_queued_.push_back(time_queued);
times_started_.push_back(time_started);
times_first_next_.push_back(0);
times_ended_.push_back(0);
return static_cast<uint32_t>(popped_queries_ + queries_.size() - 1);
}
void TraceStorage::SqlStats::RecordQueryFirstNext(uint32_t row,
int64_t time_first_next) {
// This means we've popped this query off the queue of queries before it had
// a chance to finish. Just silently drop this number.
if (popped_queries_ > row)
return;
uint32_t queue_row = row - popped_queries_;
PERFETTO_DCHECK(queue_row < queries_.size());
times_first_next_[queue_row] = time_first_next;
}
void TraceStorage::SqlStats::RecordQueryEnd(uint32_t row, int64_t time_ended) {
// This means we've popped this query off the queue of queries before it had
// a chance to finish. Just silently drop this number.
if (popped_queries_ > row)
return;
uint32_t queue_row = row - popped_queries_;
PERFETTO_DCHECK(queue_row < queries_.size());
times_ended_[queue_row] = time_ended;
}
std::pair<int64_t, int64_t> TraceStorage::GetTraceTimestampBoundsNs() const {
int64_t start_ns = std::numeric_limits<int64_t>::max();
int64_t end_ns = std::numeric_limits<int64_t>::min();
MaybeUpdateMinMax(slices_.start_ns().begin(), slices_.start_ns().end(),
&start_ns, &end_ns);
MaybeUpdateMinMax(counter_values_.timestamps().begin(),
counter_values_.timestamps().end(), &start_ns, &end_ns);
MaybeUpdateMinMax(instants_.timestamps().begin(),
instants_.timestamps().end(), &start_ns, &end_ns);
MaybeUpdateMinMax(nestable_slices_.start_ns().begin(),
nestable_slices_.start_ns().end(), &start_ns, &end_ns);
MaybeUpdateMinMax(android_log_.timestamps().begin(),
android_log_.timestamps().end(), &start_ns, &end_ns);
MaybeUpdateMinMax(raw_events_.timestamps().begin(),
raw_events_.timestamps().end(), &start_ns, &end_ns);
if (start_ns == std::numeric_limits<int64_t>::max()) {
return std::make_pair(0, 0);
}
return std::make_pair(start_ns, end_ns);
}
} // namespace trace_processor
} // namespace perfetto
<|endoftext|> |
<commit_before>//
// Copyright (c) 2009, Markus Rickert
// 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.
//
// 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 "Joint.h"
#include "Metric.h"
namespace rl
{
namespace mdl
{
Metric::Metric() :
Model()
{
}
Metric::~Metric()
{
}
void
Metric::clip(::rl::math::Vector& q) const
{
assert(q.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
::rl::math::Vector qi = q.segment(j, this->joints[i]->getDofPosition()); // TODO
this->joints[i]->clip(qi);
q.segment(j, this->joints[i]->getDofPosition()) = qi; // TODO
}
}
Model*
Metric::clone() const
{
return new Metric(*this);
}
::rl::math::Real
Metric::distance(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2) const
{
assert(q1.size() == this->getDofPosition());
assert(q2.size() == this->getDofPosition());
::rl::math::Real d = 0;
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
d += this->joints[i]->distance(
q1.segment(j, this->joints[i]->getDofPosition()),
q2.segment(j, this->joints[i]->getDofPosition())
);
}
return d;
}
void
Metric::interpolate(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2, const ::rl::math::Real& alpha, ::rl::math::Vector& q) const
{
assert(q1.size() == this->getDofPosition());
assert(q2.size() == this->getDofPosition());
assert(alpha >= 0.0f);
assert(alpha <= 1.0f);
assert(q.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
::rl::math::Vector qi = q.segment(j, this->joints[i]->getDofPosition()); // TODO
this->joints[i]->interpolate(
q1.segment(j, this->joints[i]->getDofPosition()),
q2.segment(j, this->joints[i]->getDofPosition()),
alpha,
qi
);
q.segment(j, this->joints[i]->getDofPosition()) = qi; // TODO
}
}
::rl::math::Real
Metric::inverseOfTransformedDistance(const ::rl::math::Real& d) const
{
return ::std::sqrt(d);
}
bool
Metric::isValid(const ::rl::math::Vector& q) const
{
assert(q.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
if (!this->joints[i]->isValid(q.segment(j, this->joints[i]->getDofPosition())))
{
return false;
}
}
return true;
}
::rl::math::Real
Metric::maxDistanceToRectangle(const ::rl::math::Vector& q, const ::rl::math::Vector& min, const ::rl::math::Vector& max) const
{
::rl::math::Real d = 0;
::std::size_t k = 0;
for (::std::size_t i = 0; i < this->joints.size(); ++i)
{
for (::std::size_t j = 0; j < this->joints[i]->getDofPosition(); ++j)
{
::rl::math::Real delta = ::std::max(::std::abs(q(k) - min(k)), ::std::abs(q(k) - max(k)));
if (this->joints[i]->wraparound(j))
{
::rl::math::Real range = ::std::abs(this->joints[i]->max(j) - this->joints[i]->min(j));
d += this->transformedDistance(::std::max(delta, ::std::abs(range - delta)));
}
else
{
d += this->transformedDistance(delta);
}
++k;
}
}
return d;
}
::rl::math::Real
Metric::minDistanceToRectangle(const ::rl::math::Vector& q, const ::rl::math::Vector& min, const ::rl::math::Vector& max) const
{
::rl::math::Real d = 0;
for (::std::size_t i = 0; i < this->getDofPosition(); ++i)
{
d += this->transformedDistance(this->minDistanceToRectangle(q(i), min(i), max(i), i));
}
return d;
}
::rl::math::Real
Metric::minDistanceToRectangle(const ::rl::math::Real& q, const ::rl::math::Real& min, const ::rl::math::Real& max, const ::std::size_t& cuttingDimension) const
{
::rl::math::Real d = 0;
#if 0 // TODO
if (q < min || q > max)
{
::rl::math::Real delta = ::std::min(::std::abs(q - min), ::std::abs(q - max));
if (this->joints[cuttingDimension]->wraparound)
{
::rl::math::Real range = ::std::abs(this->joints[cuttingDimension]->max - this->joints[cuttingDimension]->min);
::rl::math::Real size = ::std::abs(max - min);
d += ::std::min(delta, ::std::abs(range - size - delta));
}
else
{
d += delta;
}
}
#endif
return d;
}
::rl::math::Real
Metric::newDistance(const ::rl::math::Real& dist, const ::rl::math::Real& oldOff, const ::rl::math::Real& newOff, const int& cuttingDimension) const
{
return dist - this->transformedDistance(oldOff) + this->transformedDistance(newOff);
}
void
Metric::normalize(::rl::math::Vector& q) const
{
assert(q.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
::rl::math::Vector qi = q.segment(j, this->joints[i]->getDofPosition()); // TODO
this->joints[i]->normalize(qi);
q.segment(j, this->joints[i]->getDofPosition()) = qi; // TODO
}
}
void
Metric::step(const ::rl::math::Vector& q1, const ::rl::math::Vector& qdot, ::rl::math::Vector& q2) const
{
assert(q1.size() == this->getDofPosition());
assert(qdot.size() == this->getDof());
assert(q2.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0, k = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), k += this->joints[i]->getDof(), ++i)
{
::rl::math::Vector q2i = q2.segment(j, this->joints[i]->getDofPosition()); // TODO
this->joints[i]->step(
q1.segment(j, this->joints[i]->getDofPosition()),
qdot.segment(k, this->joints[i]->getDof()),
q2i
);
q2.segment(j, this->joints[i]->getDofPosition()) = q2i; // TODO
}
}
::rl::math::Real
Metric::transformedDistance(const ::rl::math::Real& d) const
{
return ::std::pow(d, 2);
}
::rl::math::Real
Metric::transformedDistance(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2) const
{
assert(q1.size() == this->getDofPosition());
assert(q2.size() == this->getDofPosition());
::rl::math::Real d = 0;
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
d += this->joints[i]->transformedDistance(
q1.segment(j, this->joints[i]->getDofPosition()),
q2.segment(j, this->joints[i]->getDofPosition())
);
}
return d;
}
::rl::math::Real
Metric::transformedDistance(const ::rl::math::Real& q1, const ::rl::math::Real& q2, const ::std::size_t& i) const
{
::rl::math::Real delta = ::std::abs(q1 - q2);
if (this->joints[i]->wraparound(0))
{
::rl::math::Real range = ::std::abs(this->joints[i]->max(0) - this->joints[i]->min(0));
return this->transformedDistance(::std::max(delta, ::std::abs(range - delta)));
}
else
{
return this->transformedDistance(delta);
}
}
}
}
<commit_msg>Fix distance in rl::mdl::Metric<commit_after>//
// Copyright (c) 2009, Markus Rickert
// 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.
//
// 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 "Joint.h"
#include "Metric.h"
namespace rl
{
namespace mdl
{
Metric::Metric() :
Model()
{
}
Metric::~Metric()
{
}
void
Metric::clip(::rl::math::Vector& q) const
{
assert(q.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
::rl::math::Vector qi = q.segment(j, this->joints[i]->getDofPosition()); // TODO
this->joints[i]->clip(qi);
q.segment(j, this->joints[i]->getDofPosition()) = qi; // TODO
}
}
Model*
Metric::clone() const
{
return new Metric(*this);
}
::rl::math::Real
Metric::distance(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2) const
{
assert(q1.size() == this->getDofPosition());
assert(q2.size() == this->getDofPosition());
::rl::math::Real d = 0;
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
d += this->joints[i]->transformedDistance(
q1.segment(j, this->joints[i]->getDofPosition()),
q2.segment(j, this->joints[i]->getDofPosition())
);
}
return this->inverseOfTransformedDistance(d);
}
void
Metric::interpolate(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2, const ::rl::math::Real& alpha, ::rl::math::Vector& q) const
{
assert(q1.size() == this->getDofPosition());
assert(q2.size() == this->getDofPosition());
assert(alpha >= 0.0f);
assert(alpha <= 1.0f);
assert(q.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
::rl::math::Vector qi = q.segment(j, this->joints[i]->getDofPosition()); // TODO
this->joints[i]->interpolate(
q1.segment(j, this->joints[i]->getDofPosition()),
q2.segment(j, this->joints[i]->getDofPosition()),
alpha,
qi
);
q.segment(j, this->joints[i]->getDofPosition()) = qi; // TODO
}
}
::rl::math::Real
Metric::inverseOfTransformedDistance(const ::rl::math::Real& d) const
{
return ::std::sqrt(d);
}
bool
Metric::isValid(const ::rl::math::Vector& q) const
{
assert(q.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
if (!this->joints[i]->isValid(q.segment(j, this->joints[i]->getDofPosition())))
{
return false;
}
}
return true;
}
::rl::math::Real
Metric::maxDistanceToRectangle(const ::rl::math::Vector& q, const ::rl::math::Vector& min, const ::rl::math::Vector& max) const
{
::rl::math::Real d = 0;
::std::size_t k = 0;
for (::std::size_t i = 0; i < this->joints.size(); ++i)
{
for (::std::size_t j = 0; j < this->joints[i]->getDofPosition(); ++j)
{
::rl::math::Real delta = ::std::max(::std::abs(q(k) - min(k)), ::std::abs(q(k) - max(k)));
if (this->joints[i]->wraparound(j))
{
::rl::math::Real range = ::std::abs(this->joints[i]->max(j) - this->joints[i]->min(j));
d += this->transformedDistance(::std::max(delta, ::std::abs(range - delta)));
}
else
{
d += this->transformedDistance(delta);
}
++k;
}
}
return d;
}
::rl::math::Real
Metric::minDistanceToRectangle(const ::rl::math::Vector& q, const ::rl::math::Vector& min, const ::rl::math::Vector& max) const
{
::rl::math::Real d = 0;
for (::std::size_t i = 0; i < this->getDofPosition(); ++i)
{
d += this->transformedDistance(this->minDistanceToRectangle(q(i), min(i), max(i), i));
}
return d;
}
::rl::math::Real
Metric::minDistanceToRectangle(const ::rl::math::Real& q, const ::rl::math::Real& min, const ::rl::math::Real& max, const ::std::size_t& cuttingDimension) const
{
::rl::math::Real d = 0;
#if 0 // TODO
if (q < min || q > max)
{
::rl::math::Real delta = ::std::min(::std::abs(q - min), ::std::abs(q - max));
if (this->joints[cuttingDimension]->wraparound)
{
::rl::math::Real range = ::std::abs(this->joints[cuttingDimension]->max - this->joints[cuttingDimension]->min);
::rl::math::Real size = ::std::abs(max - min);
d += ::std::min(delta, ::std::abs(range - size - delta));
}
else
{
d += delta;
}
}
#endif
return d;
}
::rl::math::Real
Metric::newDistance(const ::rl::math::Real& dist, const ::rl::math::Real& oldOff, const ::rl::math::Real& newOff, const int& cuttingDimension) const
{
return dist - this->transformedDistance(oldOff) + this->transformedDistance(newOff);
}
void
Metric::normalize(::rl::math::Vector& q) const
{
assert(q.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
::rl::math::Vector qi = q.segment(j, this->joints[i]->getDofPosition()); // TODO
this->joints[i]->normalize(qi);
q.segment(j, this->joints[i]->getDofPosition()) = qi; // TODO
}
}
void
Metric::step(const ::rl::math::Vector& q1, const ::rl::math::Vector& qdot, ::rl::math::Vector& q2) const
{
assert(q1.size() == this->getDofPosition());
assert(qdot.size() == this->getDof());
assert(q2.size() == this->getDofPosition());
for (::std::size_t i = 0, j = 0, k = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), k += this->joints[i]->getDof(), ++i)
{
::rl::math::Vector q2i = q2.segment(j, this->joints[i]->getDofPosition()); // TODO
this->joints[i]->step(
q1.segment(j, this->joints[i]->getDofPosition()),
qdot.segment(k, this->joints[i]->getDof()),
q2i
);
q2.segment(j, this->joints[i]->getDofPosition()) = q2i; // TODO
}
}
::rl::math::Real
Metric::transformedDistance(const ::rl::math::Real& d) const
{
return ::std::pow(d, 2);
}
::rl::math::Real
Metric::transformedDistance(const ::rl::math::Vector& q1, const ::rl::math::Vector& q2) const
{
assert(q1.size() == this->getDofPosition());
assert(q2.size() == this->getDofPosition());
::rl::math::Real d = 0;
for (::std::size_t i = 0, j = 0; i < this->joints.size(); j += this->joints[i]->getDofPosition(), ++i)
{
d += this->joints[i]->transformedDistance(
q1.segment(j, this->joints[i]->getDofPosition()),
q2.segment(j, this->joints[i]->getDofPosition())
);
}
return d;
}
::rl::math::Real
Metric::transformedDistance(const ::rl::math::Real& q1, const ::rl::math::Real& q2, const ::std::size_t& i) const
{
::rl::math::Real delta = ::std::abs(q1 - q2);
if (this->joints[i]->wraparound(0))
{
::rl::math::Real range = ::std::abs(this->joints[i]->max(0) - this->joints[i]->min(0));
return this->transformedDistance(::std::max(delta, ::std::abs(range - delta)));
}
else
{
return this->transformedDistance(delta);
}
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: zforscan.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: er $ $Date: 2002-10-29 18:20:14 $
*
* 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 _ZFORSCAN_HXX
#define _ZFORSCAN_HXX
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _DATE_HXX //autogen
#include <tools/date.hxx>
#endif
#ifndef _LANG_HXX //autogen
#include <tools/lang.hxx>
#endif
#ifndef _COLOR_HXX //autogen
#include <vcl/color.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_NFKEYTAB_HXX
#include "nfkeytab.hxx"
#endif
class SvNumberFormatter;
struct ImpSvNumberformatInfo;
#define SC_MAX_ANZ_FORMAT_STRINGS 100
#define SC_MAX_ANZ_STANDARD_FARBEN 10
#define FLAG_STANDARD_IN_FORMAT 1000
// Hack: nThousand=1000
// => Standard kommt im
// Format vor
enum Sc_SymbolType
{
SYMBOLTYPE_STRING = -1, // literal string in output
SYMBOLTYPE_DEL = -2, // special character
SYMBOLTYPE_BLANK = -3, // blank for '_'
SYMBOLTYPE_STAR = -4, // *-character
SYMBOLTYPE_DIGIT = -5, // digit place holder
SYMBOLTYPE_DECSEP = -6, // decimal separator
SYMBOLTYPE_THSEP = -7, // group AKA thousand separator
SYMBOLTYPE_EXP = -8, // exponent E
SYMBOLTYPE_FRAC = -9, // fraction /
SYMBOLTYPE_EMPTY = -10, // deleted symbols
SYMBOLTYPE_FRACBLANK = -11, // delimiter between integer and fraction
SYMBOLTYPE_COMMENT = -12, // comment is following
SYMBOLTYPE_CURRENCY = -13, // currency symbol
SYMBOLTYPE_CURRDEL = -14, // currency symbol delimiter [$]
SYMBOLTYPE_CURREXT = -15, // currency symbol extension -xxx
SYMBOLTYPE_CALENDAR = -16, // calendar ID
SYMBOLTYPE_CALDEL = -17 // calendar delimiter [~]
};
class ImpSvNumberformatScan
{
public:
ImpSvNumberformatScan( SvNumberFormatter* pFormatter );
~ImpSvNumberformatScan();
void ChangeIntl(); // tauscht Keywords aus
void ChangeNullDate(USHORT nDay, USHORT nMonth, USHORT nYear);
// tauscht Referenzdatum aus
void ChangeStandardPrec(short nPrec); // tauscht Standardprecision aus
xub_StrLen ScanFormat( String& rString, String& rComment ); // Aufruf der Scan-Analyse
void CopyInfo(ImpSvNumberformatInfo* pInfo,
USHORT nAnz); // Kopiert die FormatInfo
USHORT GetAnzResStrings() const { return nAnzResStrings; }
const CharClass& GetChrCls() const { return *pFormatter->GetCharClass(); }
const LocaleDataWrapper& GetLoc() const { return *pFormatter->GetLocaleData(); }
CalendarWrapper& GetCal() const { return *pFormatter->GetCalendar(); }
const String* GetKeywords() const
{
if ( bKeywordsNeedInit )
InitKeywords();
return sKeyword;
}
// Keywords used in output like TRUE and FALSE
const String& GetSpecialKeyword( NfKeywordIndex eIdx ) const
{
if ( !sKeyword[eIdx].Len() )
InitSpecialKeyword( eIdx );
return sKeyword[eIdx];
}
const String& GetTrueString() const { return GetSpecialKeyword( NF_KEY_TRUE ); }
const String& GetFalseString() const { return GetSpecialKeyword( NF_KEY_FALSE ); }
const String& GetColorString() const { return GetKeywords()[NF_KEY_COLOR]; }
const String& GetRedString() const { return GetKeywords()[NF_KEY_RED]; }
const String& GetBooleanString() const { return GetKeywords()[NF_KEY_BOOLEAN]; }
const String& GetErrorString() const { return sErrStr; }
Date* GetNullDate() const { return pNullDate; }
const String& GetStandardName() const
{
if ( bKeywordsNeedInit )
InitKeywords();
return sNameStandardFormat;
}
short GetStandardPrec() const { return nStandardPrec; }
const Color& GetRedColor() const { return StandardColor[4]; }
Color* GetColor(String& sStr); // Setzt Hauptfarben oder
// definierte Farben
// the compatibility currency symbol for old automatic currency formats
const String& GetCurSymbol() const
{
if ( bCompatCurNeedInit )
InitCompatCur();
return sCurSymbol;
}
// the compatibility currency abbreviation for CCC format code
const String& GetCurAbbrev() const
{
if ( bCompatCurNeedInit )
InitCompatCur();
return sCurAbbrev;
}
// the compatibility currency symbol upper case for old automatic currency formats
const String& GetCurString() const
{
if ( bCompatCurNeedInit )
InitCompatCur();
return sCurString;
}
void SetConvertMode(LanguageType eTmpLge, LanguageType eNewLge,
BOOL bSystemToSystem = FALSE )
{
bConvertMode = TRUE;
eNewLnge = eNewLge;
eTmpLnge = eTmpLge;
bConvertSystemToSystem = bSystemToSystem;
}
void SetConvertMode(BOOL bMode) { bConvertMode = bMode; }
// Veraendert nur die Bool-Variable
// (zum temporaeren Unterbrechen des
// Convert-Modus)
const BOOL GetConvertMode() { return bConvertMode; }
const LanguageType GetNewLnge() { return eNewLnge; }
// Lesezugriff auf ConvertMode
// und Konvertierungsland/Spr.
const LanguageType GetTmpLnge() { return eTmpLnge; }
// Lesezugriff auf
// und Ausgangsland/Spr.
SvNumberFormatter* GetNumberformatter() { return pFormatter; }
// Zugriff auf Formatierer
// (fuer zformat.cxx)
private: // ---- privater Teil
static String theEnglishColors[SC_MAX_ANZ_STANDARD_FARBEN];
NfKeywordTable sKeyword; // Schluesselworte der Syntax
Color StandardColor[SC_MAX_ANZ_STANDARD_FARBEN];
// Array der Standardfarben
Date* pNullDate; // 30Dec1899
String sNameStandardFormat; // "Standard"
short nStandardPrec; // default Precision fuer Standardformat (2)
SvNumberFormatter* pFormatter; // Pointer auf die Formatliste
String sStrArray[SC_MAX_ANZ_FORMAT_STRINGS];// Array der Symbole
short nTypeArray[SC_MAX_ANZ_FORMAT_STRINGS];// Array der Infos
// externe Infos:
USHORT nAnzResStrings; // Anzahl der Ergebnissymbole
#if !(defined SOLARIS && defined X86)
short eScannedType; // Typ gemaess Scan
#else
int eScannedType; // wg. Optimierung
#endif
BOOL bThousand; // Mit Tausenderpunkt
USHORT nThousand; // Zaehlt ....-Folgen
USHORT nCntPre; // Zaehlt Vorkommastellen
USHORT nCntPost; // Zaehlt Nachkommastellen
USHORT nCntExp; // Zaehlt Exp.Stellen, AM/PM
// interne Infos:
USHORT nAnzStrings; // Anzahl der Symbole
USHORT nRepPos; // Position eines '*'
USHORT nExpPos; // interne Position des E
USHORT nBlankPos; // interne Position des Blank
short nDecPos; // interne Pos. des ,
BOOL bExp; // wird bei Lesen des E gesetzt
BOOL bFrac; // wird bei Lesen des / gesetzt
BOOL bBlank; // wird bei ' '(Fraction) ges.
BOOL bDecSep; // Wird beim ersten , gesetzt
mutable BOOL bKeywordsNeedInit; // Locale dependent keywords need to be initialized
mutable BOOL bCompatCurNeedInit; // Locale dependent compatibility currency need to be initialized
String sCurSymbol; // Currency symbol for compatibility format codes
String sCurString; // Currency symbol in upper case
String sCurAbbrev; // Currency abbreviation
String sErrStr; // String fuer Fehlerausgaben
BOOL bConvertMode; // Wird im Convert-Mode gesetzt
// Land/Sprache, in die der
LanguageType eNewLnge; // gescannte String konvertiert
// wird (fuer Excel Filter)
// Land/Sprache, aus der der
LanguageType eTmpLnge; // gescannte String konvertiert
// wird (fuer Excel Filter)
BOOL bConvertSystemToSystem; // Whether the conversion is
// from one system locale to
// another system locale (in
// this case the automatic
// currency symbol is converted
// too).
xub_StrLen nCurrPos; // Position des Waehrungssymbols
void InitKeywords() const;
void InitSpecialKeyword( NfKeywordIndex eIdx ) const;
void InitCompatCur() const;
#ifdef _ZFORSCAN_CXX // ----- private Methoden -----
void SetDependentKeywords();
// Setzt die Sprachabh. Keyw.
void SkipStrings(USHORT& i,xub_StrLen& nPos);// Ueberspringt StringSymbole
USHORT PreviousKeyword(USHORT i); // Gibt Index des vorangeh.
// Schluesselworts oder 0
USHORT NextKeyword(USHORT i); // Gibt Index des naechsten
// Schluesselworts oder 0
sal_Unicode PreviousChar(USHORT i); // Gibt letzten Buchstaben
// vor der Position,
// skipt EMPTY, STRING, STAR, BLANK
sal_Unicode NextChar(USHORT i); // Gibt ersten Buchst. danach
short PreviousType( USHORT i ); // Gibt Typ vor Position,
// skipt EMPTY
BOOL IsLastBlankBeforeFrac(USHORT i); // True <=> es kommt kein ' '
// mehr bis zum '/'
void Reset(); // Reset aller Variablen
// vor Analysestart
short GetKeyWord( const String& sSymbol, // determine keyword at nPos
xub_StrLen nPos ); // return 0 <=> not found
inline BOOL IsAmbiguousE( short nKey ) // whether nKey is ambiguous E of NF_KEY_E/NF_KEY_EC
{
return (nKey == NF_KEY_EC || nKey == NF_KEY_E) &&
(GetKeywords()[NF_KEY_EC] == GetKeywords()[NF_KEY_E]);
}
// if 0 at strArray[i] is of S,00 or SS,00 or SS"any"00 in ScanType() or FinalScan()
BOOL Is100SecZero( USHORT i, BOOL bHadDecSep );
short Next_Symbol(const String& rStr,
xub_StrLen& nPos,
String& sSymbol); // Naechstes Symbol
xub_StrLen Symbol_Division(const String& rString);// lexikalische Voranalyse
xub_StrLen ScanType(const String& rString); // Analyse des Formattyps
xub_StrLen FinalScan( String& rString, String& rComment ); // Endanalyse mit Vorgabe
// des Typs
// -1:= error, return nPos in FinalScan; 0:= no calendar, 1:= calendar found
int FinalScanGetCalendar( xub_StrLen& nPos, USHORT& i, USHORT& nAnzResStrings );
static inline BOOL StringEqualsChar( const String& rStr, sal_Unicode ch )
{ return rStr.GetChar(0) == ch && rStr.Len() == 1; }
// Yes, for efficiency get the character first and then compare length
// because in most places where this is used the string is one char.
// remove "..." and \... quotes from rStr, return how many chars removed
static xub_StrLen RemoveQuotes( String& rStr );
#endif //_ZFORSCAN_CXX
};
#endif // _ZFORSCAN_HXX
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.15.384); FILE MERGED 2003/12/11 09:07:27 mt 1.15.384.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/*************************************************************************
*
* $RCSfile: zforscan.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: vg $ $Date: 2004-01-06 19:33:27 $
*
* 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 _ZFORSCAN_HXX
#define _ZFORSCAN_HXX
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _DATE_HXX //autogen
#include <tools/date.hxx>
#endif
#ifndef _LANG_HXX //autogen
#include <tools/lang.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_NFKEYTAB_HXX
#include "nfkeytab.hxx"
#endif
class SvNumberFormatter;
struct ImpSvNumberformatInfo;
#define SC_MAX_ANZ_FORMAT_STRINGS 100
#define SC_MAX_ANZ_STANDARD_FARBEN 10
#define FLAG_STANDARD_IN_FORMAT 1000
// Hack: nThousand=1000
// => Standard kommt im
// Format vor
enum Sc_SymbolType
{
SYMBOLTYPE_STRING = -1, // literal string in output
SYMBOLTYPE_DEL = -2, // special character
SYMBOLTYPE_BLANK = -3, // blank for '_'
SYMBOLTYPE_STAR = -4, // *-character
SYMBOLTYPE_DIGIT = -5, // digit place holder
SYMBOLTYPE_DECSEP = -6, // decimal separator
SYMBOLTYPE_THSEP = -7, // group AKA thousand separator
SYMBOLTYPE_EXP = -8, // exponent E
SYMBOLTYPE_FRAC = -9, // fraction /
SYMBOLTYPE_EMPTY = -10, // deleted symbols
SYMBOLTYPE_FRACBLANK = -11, // delimiter between integer and fraction
SYMBOLTYPE_COMMENT = -12, // comment is following
SYMBOLTYPE_CURRENCY = -13, // currency symbol
SYMBOLTYPE_CURRDEL = -14, // currency symbol delimiter [$]
SYMBOLTYPE_CURREXT = -15, // currency symbol extension -xxx
SYMBOLTYPE_CALENDAR = -16, // calendar ID
SYMBOLTYPE_CALDEL = -17 // calendar delimiter [~]
};
class ImpSvNumberformatScan
{
public:
ImpSvNumberformatScan( SvNumberFormatter* pFormatter );
~ImpSvNumberformatScan();
void ChangeIntl(); // tauscht Keywords aus
void ChangeNullDate(USHORT nDay, USHORT nMonth, USHORT nYear);
// tauscht Referenzdatum aus
void ChangeStandardPrec(short nPrec); // tauscht Standardprecision aus
xub_StrLen ScanFormat( String& rString, String& rComment ); // Aufruf der Scan-Analyse
void CopyInfo(ImpSvNumberformatInfo* pInfo,
USHORT nAnz); // Kopiert die FormatInfo
USHORT GetAnzResStrings() const { return nAnzResStrings; }
const CharClass& GetChrCls() const { return *pFormatter->GetCharClass(); }
const LocaleDataWrapper& GetLoc() const { return *pFormatter->GetLocaleData(); }
CalendarWrapper& GetCal() const { return *pFormatter->GetCalendar(); }
const String* GetKeywords() const
{
if ( bKeywordsNeedInit )
InitKeywords();
return sKeyword;
}
// Keywords used in output like TRUE and FALSE
const String& GetSpecialKeyword( NfKeywordIndex eIdx ) const
{
if ( !sKeyword[eIdx].Len() )
InitSpecialKeyword( eIdx );
return sKeyword[eIdx];
}
const String& GetTrueString() const { return GetSpecialKeyword( NF_KEY_TRUE ); }
const String& GetFalseString() const { return GetSpecialKeyword( NF_KEY_FALSE ); }
const String& GetColorString() const { return GetKeywords()[NF_KEY_COLOR]; }
const String& GetRedString() const { return GetKeywords()[NF_KEY_RED]; }
const String& GetBooleanString() const { return GetKeywords()[NF_KEY_BOOLEAN]; }
const String& GetErrorString() const { return sErrStr; }
Date* GetNullDate() const { return pNullDate; }
const String& GetStandardName() const
{
if ( bKeywordsNeedInit )
InitKeywords();
return sNameStandardFormat;
}
short GetStandardPrec() const { return nStandardPrec; }
const Color& GetRedColor() const { return StandardColor[4]; }
Color* GetColor(String& sStr); // Setzt Hauptfarben oder
// definierte Farben
// the compatibility currency symbol for old automatic currency formats
const String& GetCurSymbol() const
{
if ( bCompatCurNeedInit )
InitCompatCur();
return sCurSymbol;
}
// the compatibility currency abbreviation for CCC format code
const String& GetCurAbbrev() const
{
if ( bCompatCurNeedInit )
InitCompatCur();
return sCurAbbrev;
}
// the compatibility currency symbol upper case for old automatic currency formats
const String& GetCurString() const
{
if ( bCompatCurNeedInit )
InitCompatCur();
return sCurString;
}
void SetConvertMode(LanguageType eTmpLge, LanguageType eNewLge,
BOOL bSystemToSystem = FALSE )
{
bConvertMode = TRUE;
eNewLnge = eNewLge;
eTmpLnge = eTmpLge;
bConvertSystemToSystem = bSystemToSystem;
}
void SetConvertMode(BOOL bMode) { bConvertMode = bMode; }
// Veraendert nur die Bool-Variable
// (zum temporaeren Unterbrechen des
// Convert-Modus)
const BOOL GetConvertMode() { return bConvertMode; }
const LanguageType GetNewLnge() { return eNewLnge; }
// Lesezugriff auf ConvertMode
// und Konvertierungsland/Spr.
const LanguageType GetTmpLnge() { return eTmpLnge; }
// Lesezugriff auf
// und Ausgangsland/Spr.
SvNumberFormatter* GetNumberformatter() { return pFormatter; }
// Zugriff auf Formatierer
// (fuer zformat.cxx)
private: // ---- privater Teil
static String theEnglishColors[SC_MAX_ANZ_STANDARD_FARBEN];
NfKeywordTable sKeyword; // Schluesselworte der Syntax
Color StandardColor[SC_MAX_ANZ_STANDARD_FARBEN];
// Array der Standardfarben
Date* pNullDate; // 30Dec1899
String sNameStandardFormat; // "Standard"
short nStandardPrec; // default Precision fuer Standardformat (2)
SvNumberFormatter* pFormatter; // Pointer auf die Formatliste
String sStrArray[SC_MAX_ANZ_FORMAT_STRINGS];// Array der Symbole
short nTypeArray[SC_MAX_ANZ_FORMAT_STRINGS];// Array der Infos
// externe Infos:
USHORT nAnzResStrings; // Anzahl der Ergebnissymbole
#if !(defined SOLARIS && defined X86)
short eScannedType; // Typ gemaess Scan
#else
int eScannedType; // wg. Optimierung
#endif
BOOL bThousand; // Mit Tausenderpunkt
USHORT nThousand; // Zaehlt ....-Folgen
USHORT nCntPre; // Zaehlt Vorkommastellen
USHORT nCntPost; // Zaehlt Nachkommastellen
USHORT nCntExp; // Zaehlt Exp.Stellen, AM/PM
// interne Infos:
USHORT nAnzStrings; // Anzahl der Symbole
USHORT nRepPos; // Position eines '*'
USHORT nExpPos; // interne Position des E
USHORT nBlankPos; // interne Position des Blank
short nDecPos; // interne Pos. des ,
BOOL bExp; // wird bei Lesen des E gesetzt
BOOL bFrac; // wird bei Lesen des / gesetzt
BOOL bBlank; // wird bei ' '(Fraction) ges.
BOOL bDecSep; // Wird beim ersten , gesetzt
mutable BOOL bKeywordsNeedInit; // Locale dependent keywords need to be initialized
mutable BOOL bCompatCurNeedInit; // Locale dependent compatibility currency need to be initialized
String sCurSymbol; // Currency symbol for compatibility format codes
String sCurString; // Currency symbol in upper case
String sCurAbbrev; // Currency abbreviation
String sErrStr; // String fuer Fehlerausgaben
BOOL bConvertMode; // Wird im Convert-Mode gesetzt
// Land/Sprache, in die der
LanguageType eNewLnge; // gescannte String konvertiert
// wird (fuer Excel Filter)
// Land/Sprache, aus der der
LanguageType eTmpLnge; // gescannte String konvertiert
// wird (fuer Excel Filter)
BOOL bConvertSystemToSystem; // Whether the conversion is
// from one system locale to
// another system locale (in
// this case the automatic
// currency symbol is converted
// too).
xub_StrLen nCurrPos; // Position des Waehrungssymbols
void InitKeywords() const;
void InitSpecialKeyword( NfKeywordIndex eIdx ) const;
void InitCompatCur() const;
#ifdef _ZFORSCAN_CXX // ----- private Methoden -----
void SetDependentKeywords();
// Setzt die Sprachabh. Keyw.
void SkipStrings(USHORT& i,xub_StrLen& nPos);// Ueberspringt StringSymbole
USHORT PreviousKeyword(USHORT i); // Gibt Index des vorangeh.
// Schluesselworts oder 0
USHORT NextKeyword(USHORT i); // Gibt Index des naechsten
// Schluesselworts oder 0
sal_Unicode PreviousChar(USHORT i); // Gibt letzten Buchstaben
// vor der Position,
// skipt EMPTY, STRING, STAR, BLANK
sal_Unicode NextChar(USHORT i); // Gibt ersten Buchst. danach
short PreviousType( USHORT i ); // Gibt Typ vor Position,
// skipt EMPTY
BOOL IsLastBlankBeforeFrac(USHORT i); // True <=> es kommt kein ' '
// mehr bis zum '/'
void Reset(); // Reset aller Variablen
// vor Analysestart
short GetKeyWord( const String& sSymbol, // determine keyword at nPos
xub_StrLen nPos ); // return 0 <=> not found
inline BOOL IsAmbiguousE( short nKey ) // whether nKey is ambiguous E of NF_KEY_E/NF_KEY_EC
{
return (nKey == NF_KEY_EC || nKey == NF_KEY_E) &&
(GetKeywords()[NF_KEY_EC] == GetKeywords()[NF_KEY_E]);
}
// if 0 at strArray[i] is of S,00 or SS,00 or SS"any"00 in ScanType() or FinalScan()
BOOL Is100SecZero( USHORT i, BOOL bHadDecSep );
short Next_Symbol(const String& rStr,
xub_StrLen& nPos,
String& sSymbol); // Naechstes Symbol
xub_StrLen Symbol_Division(const String& rString);// lexikalische Voranalyse
xub_StrLen ScanType(const String& rString); // Analyse des Formattyps
xub_StrLen FinalScan( String& rString, String& rComment ); // Endanalyse mit Vorgabe
// des Typs
// -1:= error, return nPos in FinalScan; 0:= no calendar, 1:= calendar found
int FinalScanGetCalendar( xub_StrLen& nPos, USHORT& i, USHORT& nAnzResStrings );
static inline BOOL StringEqualsChar( const String& rStr, sal_Unicode ch )
{ return rStr.GetChar(0) == ch && rStr.Len() == 1; }
// Yes, for efficiency get the character first and then compare length
// because in most places where this is used the string is one char.
// remove "..." and \... quotes from rStr, return how many chars removed
static xub_StrLen RemoveQuotes( String& rStr );
#endif //_ZFORSCAN_CXX
};
#endif // _ZFORSCAN_HXX
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include <accfrmobj.hxx>
#include <accmap.hxx>
#include <acccontext.hxx>
#include <viewsh.hxx>
#include <rootfrm.hxx>
#include <flyfrm.hxx>
#include <pagefrm.hxx>
#include <cellfrm.hxx>
#include <swtable.hxx>
#include <dflyobj.hxx>
#include <frmfmt.hxx>
#include <fmtanchr.hxx>
#include <dcontact.hxx>
#include <pam.hxx>
#include <vcl/window.hxx>
namespace sw { namespace access {
SwAccessibleChild::SwAccessibleChild()
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{}
SwAccessibleChild::SwAccessibleChild( const SdrObject* pDrawObj )
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{
Init( pDrawObj );
}
SwAccessibleChild::SwAccessibleChild( const SwFrm* pFrm )
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{
Init( pFrm );
}
SwAccessibleChild::SwAccessibleChild( vcl::Window* pWindow )
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{
Init( pWindow );
}
SwAccessibleChild::SwAccessibleChild( const SwFrm* pFrm,
const SdrObject* pDrawObj,
vcl::Window* pWindow )
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{
if ( pFrm )
{
Init( pFrm );
}
else if ( pDrawObj )
{
Init( pDrawObj );
}
else if ( pWindow )
{
Init( pWindow );
}
OSL_ENSURE( (!pFrm || pFrm == mpFrm) &&
(!pDrawObj || pDrawObj == mpDrawObj) &&
(!pWindow || pWindow == mpWindow),
"invalid frame/object/window combination" );
}
void SwAccessibleChild::Init( const SdrObject* pDrawObj )
{
mpDrawObj = pDrawObj;
mpFrm = mpDrawObj && mpDrawObj->ISA(SwVirtFlyDrawObj)
? static_cast < const SwVirtFlyDrawObj * >( mpDrawObj )->GetFlyFrm()
: 0;
mpWindow = 0;
}
void SwAccessibleChild::Init( const SwFrm* pFrm )
{
mpFrm = pFrm;
mpDrawObj = mpFrm && mpFrm->IsFlyFrm()
? static_cast < const SwFlyFrm * >( mpFrm )->GetVirtDrawObj()
: 0;
mpWindow = 0;
}
void SwAccessibleChild::Init( vcl::Window* pWindow )
{
mpWindow = pWindow;
mpFrm = 0;
mpDrawObj = 0;
}
bool SwAccessibleChild::IsAccessible( bool bPagePreview ) const
{
bool bRet( false );
if ( mpFrm )
{
bRet = mpFrm->IsAccessibleFrm() &&
( !mpFrm->IsCellFrm() ||
static_cast<const SwCellFrm *>( mpFrm )->GetTabBox()->GetSttNd() != 0 ) &&
!mpFrm->IsInCoveredCell() &&
( bPagePreview ||
!mpFrm->IsPageFrm() );
}
else if ( mpDrawObj )
{
bRet = true;
}
else if ( mpWindow )
{
bRet = true;
}
return bRet;
}
bool SwAccessibleChild::IsBoundAsChar() const
{
bool bRet( false );
if ( mpFrm )
{
bRet = mpFrm->IsFlyFrm() &&
static_cast< const SwFlyFrm *>(mpFrm)->IsFlyInCntFrm();
}
else if ( mpDrawObj )
{
const SwFrameFormat* mpFrameFormat = ::FindFrameFormat( mpDrawObj );
bRet = mpFrameFormat
&& (FLY_AS_CHAR == mpFrameFormat->GetAnchor().GetAnchorId());
}
else if ( mpWindow )
{
bRet = false;
}
return bRet;
}
SwAccessibleChild::SwAccessibleChild( const SwAccessibleChild& r )
: mpFrm( r.mpFrm )
, mpDrawObj( r.mpDrawObj )
, mpWindow( r.mpWindow )
{}
SwAccessibleChild& SwAccessibleChild::operator=( const SwAccessibleChild& r )
{
mpDrawObj = r.mpDrawObj;
mpFrm = r.mpFrm;
mpWindow = r.mpWindow;
return *this;
}
SwAccessibleChild& SwAccessibleChild::operator=( const SdrObject* pDrawObj )
{
Init( pDrawObj );
return *this;
}
SwAccessibleChild& SwAccessibleChild::operator=( const SwFrm* pFrm )
{
Init( pFrm );
return *this;
}
SwAccessibleChild& SwAccessibleChild::operator=( vcl::Window* pWindow )
{
Init( pWindow );
return *this;
}
bool SwAccessibleChild::operator==( const SwAccessibleChild& r ) const
{
return mpFrm == r.mpFrm &&
mpDrawObj == r.mpDrawObj &&
mpWindow == r.mpWindow;
}
bool SwAccessibleChild::IsValid() const
{
return mpFrm != 0 ||
mpDrawObj != 0 ||
mpWindow != nullptr;
}
bool SwAccessibleChild::IsVisibleChildrenOnly() const
{
bool bRet( false );
if ( !mpFrm )
{
bRet = true;
}
else
{
bRet = mpFrm->IsRootFrm() ||
!( mpFrm->IsTabFrm() ||
mpFrm->IsInTab() ||
( IsBoundAsChar() &&
static_cast<const SwFlyFrm*>(mpFrm)->GetAnchorFrm()->IsInTab() ) );
}
return bRet;
}
SwRect SwAccessibleChild::GetBox( const SwAccessibleMap& rAccMap ) const
{
SwRect aBox;
if ( mpFrm )
{
if ( mpFrm->IsPageFrm() &&
static_cast< const SwPageFrm * >( mpFrm )->IsEmptyPage() )
{
aBox = SwRect( mpFrm->Frm().Left(), mpFrm->Frm().Top()-1, 1, 1 );
}
else if ( mpFrm->IsTabFrm() )
{
aBox = SwRect( mpFrm->Frm() );
aBox.Intersection( mpFrm->GetUpper()->Frm() );
}
else
{
aBox = mpFrm->Frm();
}
}
else if( mpDrawObj )
{
aBox = SwRect( mpDrawObj->GetCurrentBoundRect() );
}
else if ( mpWindow )
{
aBox = SwRect( rAccMap.GetShell()->GetWin()->PixelToLogic(
Rectangle( mpWindow->GetPosPixel(),
mpWindow->GetSizePixel() ) ) );
}
return aBox;
}
SwRect SwAccessibleChild::GetBounds( const SwAccessibleMap& rAccMap ) const
{
SwRect aBound;
if( mpFrm )
{
if( mpFrm->IsPageFrm() &&
static_cast< const SwPageFrm * >( mpFrm )->IsEmptyPage() )
{
aBound = SwRect( mpFrm->Frm().Left(), mpFrm->Frm().Top()-1, 0, 0 );
}
else
aBound = mpFrm->PaintArea();
}
else if( mpDrawObj )
{
aBound = GetBox( rAccMap );
}
else if ( mpWindow )
{
aBound = GetBox( rAccMap );
}
return aBound;
}
bool SwAccessibleChild::AlwaysIncludeAsChild() const
{
bool bAlwaysIncludedAsChild( false );
if ( mpWindow )
{
bAlwaysIncludedAsChild = true;
}
return bAlwaysIncludedAsChild;
}
const SwFrm* SwAccessibleChild::GetParent( const bool bInPagePreview ) const
{
const SwFrm* pParent( 0 );
if ( mpFrm )
{
if( mpFrm->IsFlyFrm() )
{
const SwFlyFrm* pFly = static_cast< const SwFlyFrm *>( mpFrm );
if( pFly->IsFlyInCntFrm() )
{
// For FLY_AS_CHAR the parent is the anchor
pParent = pFly->GetAnchorFrm();
OSL_ENSURE( SwAccessibleChild( pParent ).IsAccessible( bInPagePreview ),
"parent is not accessible" );
}
else
{
// In any other case the parent is the root frm
// (in page preview, the page frame)
if( bInPagePreview )
pParent = pFly->FindPageFrm();
else
pParent = pFly->getRootFrm();
}
}
else
{
SwAccessibleChild aUpper( mpFrm->GetUpper() );
while( aUpper.GetSwFrm() && !aUpper.IsAccessible(bInPagePreview) )
{
aUpper = aUpper.GetSwFrm()->GetUpper();
}
pParent = aUpper.GetSwFrm();
}
}
else if( mpDrawObj )
{
const SwDrawContact *pContact =
static_cast< const SwDrawContact* >( GetUserCall( mpDrawObj ) );
OSL_ENSURE( pContact, "sdr contact is missing" );
if( pContact )
{
const SwFrameFormat *pFrameFormat = pContact->GetFormat();
OSL_ENSURE( pFrameFormat, "frame format is missing" );
if( pFrameFormat && FLY_AS_CHAR == pFrameFormat->GetAnchor().GetAnchorId() )
{
// For FLY_AS_CHAR the parent is the anchor
pParent = pContact->GetAnchorFrm();
OSL_ENSURE( SwAccessibleChild( pParent ).IsAccessible( bInPagePreview ),
"parent is not accessible" );
}
else
{
// In any other case the parent is the root frm
if( bInPagePreview )
pParent = pContact->GetAnchorFrm()->FindPageFrm();
else
pParent = pContact->GetAnchorFrm()->getRootFrm();
}
}
}
else if ( mpWindow )
{
css::uno::Reference < css::accessibility::XAccessible > xAcc =
mpWindow->GetAccessible();
if ( xAcc.is() )
{
css::uno::Reference < css::accessibility::XAccessibleContext > xAccContext =
xAcc->getAccessibleContext();
if ( xAccContext.is() )
{
css::uno::Reference < css::accessibility::XAccessible > xAccParent =
xAccContext->getAccessibleParent();
if ( xAccParent.is() )
{
SwAccessibleContext* pAccParentImpl =
dynamic_cast< SwAccessibleContext *>( xAccParent.get() );
if ( pAccParentImpl )
{
pParent = pAccParentImpl->GetFrm();
}
}
}
}
}
return pParent;
}
} } // eof of namespace sw::access
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>GetWin seen as NULL sometimes<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include <accfrmobj.hxx>
#include <accmap.hxx>
#include <acccontext.hxx>
#include <viewsh.hxx>
#include <rootfrm.hxx>
#include <flyfrm.hxx>
#include <pagefrm.hxx>
#include <cellfrm.hxx>
#include <swtable.hxx>
#include <dflyobj.hxx>
#include <frmfmt.hxx>
#include <fmtanchr.hxx>
#include <dcontact.hxx>
#include <pam.hxx>
#include <vcl/window.hxx>
namespace sw { namespace access {
SwAccessibleChild::SwAccessibleChild()
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{}
SwAccessibleChild::SwAccessibleChild( const SdrObject* pDrawObj )
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{
Init( pDrawObj );
}
SwAccessibleChild::SwAccessibleChild( const SwFrm* pFrm )
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{
Init( pFrm );
}
SwAccessibleChild::SwAccessibleChild( vcl::Window* pWindow )
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{
Init( pWindow );
}
SwAccessibleChild::SwAccessibleChild( const SwFrm* pFrm,
const SdrObject* pDrawObj,
vcl::Window* pWindow )
: mpFrm( 0 )
, mpDrawObj( 0 )
, mpWindow( 0 )
{
if ( pFrm )
{
Init( pFrm );
}
else if ( pDrawObj )
{
Init( pDrawObj );
}
else if ( pWindow )
{
Init( pWindow );
}
OSL_ENSURE( (!pFrm || pFrm == mpFrm) &&
(!pDrawObj || pDrawObj == mpDrawObj) &&
(!pWindow || pWindow == mpWindow),
"invalid frame/object/window combination" );
}
void SwAccessibleChild::Init( const SdrObject* pDrawObj )
{
mpDrawObj = pDrawObj;
mpFrm = mpDrawObj && mpDrawObj->ISA(SwVirtFlyDrawObj)
? static_cast < const SwVirtFlyDrawObj * >( mpDrawObj )->GetFlyFrm()
: 0;
mpWindow = 0;
}
void SwAccessibleChild::Init( const SwFrm* pFrm )
{
mpFrm = pFrm;
mpDrawObj = mpFrm && mpFrm->IsFlyFrm()
? static_cast < const SwFlyFrm * >( mpFrm )->GetVirtDrawObj()
: 0;
mpWindow = 0;
}
void SwAccessibleChild::Init( vcl::Window* pWindow )
{
mpWindow = pWindow;
mpFrm = 0;
mpDrawObj = 0;
}
bool SwAccessibleChild::IsAccessible( bool bPagePreview ) const
{
bool bRet( false );
if ( mpFrm )
{
bRet = mpFrm->IsAccessibleFrm() &&
( !mpFrm->IsCellFrm() ||
static_cast<const SwCellFrm *>( mpFrm )->GetTabBox()->GetSttNd() != 0 ) &&
!mpFrm->IsInCoveredCell() &&
( bPagePreview ||
!mpFrm->IsPageFrm() );
}
else if ( mpDrawObj )
{
bRet = true;
}
else if ( mpWindow )
{
bRet = true;
}
return bRet;
}
bool SwAccessibleChild::IsBoundAsChar() const
{
bool bRet( false );
if ( mpFrm )
{
bRet = mpFrm->IsFlyFrm() &&
static_cast< const SwFlyFrm *>(mpFrm)->IsFlyInCntFrm();
}
else if ( mpDrawObj )
{
const SwFrameFormat* mpFrameFormat = ::FindFrameFormat( mpDrawObj );
bRet = mpFrameFormat
&& (FLY_AS_CHAR == mpFrameFormat->GetAnchor().GetAnchorId());
}
else if ( mpWindow )
{
bRet = false;
}
return bRet;
}
SwAccessibleChild::SwAccessibleChild( const SwAccessibleChild& r )
: mpFrm( r.mpFrm )
, mpDrawObj( r.mpDrawObj )
, mpWindow( r.mpWindow )
{}
SwAccessibleChild& SwAccessibleChild::operator=( const SwAccessibleChild& r )
{
mpDrawObj = r.mpDrawObj;
mpFrm = r.mpFrm;
mpWindow = r.mpWindow;
return *this;
}
SwAccessibleChild& SwAccessibleChild::operator=( const SdrObject* pDrawObj )
{
Init( pDrawObj );
return *this;
}
SwAccessibleChild& SwAccessibleChild::operator=( const SwFrm* pFrm )
{
Init( pFrm );
return *this;
}
SwAccessibleChild& SwAccessibleChild::operator=( vcl::Window* pWindow )
{
Init( pWindow );
return *this;
}
bool SwAccessibleChild::operator==( const SwAccessibleChild& r ) const
{
return mpFrm == r.mpFrm &&
mpDrawObj == r.mpDrawObj &&
mpWindow == r.mpWindow;
}
bool SwAccessibleChild::IsValid() const
{
return mpFrm != 0 ||
mpDrawObj != 0 ||
mpWindow != nullptr;
}
bool SwAccessibleChild::IsVisibleChildrenOnly() const
{
bool bRet( false );
if ( !mpFrm )
{
bRet = true;
}
else
{
bRet = mpFrm->IsRootFrm() ||
!( mpFrm->IsTabFrm() ||
mpFrm->IsInTab() ||
( IsBoundAsChar() &&
static_cast<const SwFlyFrm*>(mpFrm)->GetAnchorFrm()->IsInTab() ) );
}
return bRet;
}
SwRect SwAccessibleChild::GetBox( const SwAccessibleMap& rAccMap ) const
{
SwRect aBox;
if ( mpFrm )
{
if ( mpFrm->IsPageFrm() &&
static_cast< const SwPageFrm * >( mpFrm )->IsEmptyPage() )
{
aBox = SwRect( mpFrm->Frm().Left(), mpFrm->Frm().Top()-1, 1, 1 );
}
else if ( mpFrm->IsTabFrm() )
{
aBox = SwRect( mpFrm->Frm() );
aBox.Intersection( mpFrm->GetUpper()->Frm() );
}
else
{
aBox = mpFrm->Frm();
}
}
else if( mpDrawObj )
{
aBox = SwRect( mpDrawObj->GetCurrentBoundRect() );
}
else if ( mpWindow )
{
vcl::Window *pWin = rAccMap.GetShell()->GetWin();
if (pWin)
{
aBox = SwRect( pWin->PixelToLogic(
Rectangle( mpWindow->GetPosPixel(),
mpWindow->GetSizePixel() ) ) );
}
}
return aBox;
}
SwRect SwAccessibleChild::GetBounds( const SwAccessibleMap& rAccMap ) const
{
SwRect aBound;
if( mpFrm )
{
if( mpFrm->IsPageFrm() &&
static_cast< const SwPageFrm * >( mpFrm )->IsEmptyPage() )
{
aBound = SwRect( mpFrm->Frm().Left(), mpFrm->Frm().Top()-1, 0, 0 );
}
else
aBound = mpFrm->PaintArea();
}
else if( mpDrawObj )
{
aBound = GetBox( rAccMap );
}
else if ( mpWindow )
{
aBound = GetBox( rAccMap );
}
return aBound;
}
bool SwAccessibleChild::AlwaysIncludeAsChild() const
{
bool bAlwaysIncludedAsChild( false );
if ( mpWindow )
{
bAlwaysIncludedAsChild = true;
}
return bAlwaysIncludedAsChild;
}
const SwFrm* SwAccessibleChild::GetParent( const bool bInPagePreview ) const
{
const SwFrm* pParent( 0 );
if ( mpFrm )
{
if( mpFrm->IsFlyFrm() )
{
const SwFlyFrm* pFly = static_cast< const SwFlyFrm *>( mpFrm );
if( pFly->IsFlyInCntFrm() )
{
// For FLY_AS_CHAR the parent is the anchor
pParent = pFly->GetAnchorFrm();
OSL_ENSURE( SwAccessibleChild( pParent ).IsAccessible( bInPagePreview ),
"parent is not accessible" );
}
else
{
// In any other case the parent is the root frm
// (in page preview, the page frame)
if( bInPagePreview )
pParent = pFly->FindPageFrm();
else
pParent = pFly->getRootFrm();
}
}
else
{
SwAccessibleChild aUpper( mpFrm->GetUpper() );
while( aUpper.GetSwFrm() && !aUpper.IsAccessible(bInPagePreview) )
{
aUpper = aUpper.GetSwFrm()->GetUpper();
}
pParent = aUpper.GetSwFrm();
}
}
else if( mpDrawObj )
{
const SwDrawContact *pContact =
static_cast< const SwDrawContact* >( GetUserCall( mpDrawObj ) );
OSL_ENSURE( pContact, "sdr contact is missing" );
if( pContact )
{
const SwFrameFormat *pFrameFormat = pContact->GetFormat();
OSL_ENSURE( pFrameFormat, "frame format is missing" );
if( pFrameFormat && FLY_AS_CHAR == pFrameFormat->GetAnchor().GetAnchorId() )
{
// For FLY_AS_CHAR the parent is the anchor
pParent = pContact->GetAnchorFrm();
OSL_ENSURE( SwAccessibleChild( pParent ).IsAccessible( bInPagePreview ),
"parent is not accessible" );
}
else
{
// In any other case the parent is the root frm
if( bInPagePreview )
pParent = pContact->GetAnchorFrm()->FindPageFrm();
else
pParent = pContact->GetAnchorFrm()->getRootFrm();
}
}
}
else if ( mpWindow )
{
css::uno::Reference < css::accessibility::XAccessible > xAcc =
mpWindow->GetAccessible();
if ( xAcc.is() )
{
css::uno::Reference < css::accessibility::XAccessibleContext > xAccContext =
xAcc->getAccessibleContext();
if ( xAccContext.is() )
{
css::uno::Reference < css::accessibility::XAccessible > xAccParent =
xAccContext->getAccessibleParent();
if ( xAccParent.is() )
{
SwAccessibleContext* pAccParentImpl =
dynamic_cast< SwAccessibleContext *>( xAccParent.get() );
if ( pAccParentImpl )
{
pParent = pAccParentImpl->GetFrm();
}
}
}
}
}
return pParent;
}
} } // eof of namespace sw::access
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "PolygonProximityLinker.h"
#include <cmath> // isfinite
#include <sstream> // ostream
#include "AABB.h" // for debug output svg html
#include "SVG.h"
namespace cura
{
PolygonProximityLinker::PolygonProximityLinker(Polygons& polygons, int proximity_distance)
: polygons(polygons)
, proximity_distance(proximity_distance)
{
unsigned int n_points = 0;
for (PolygonRef poly : polygons)
{
n_points += poly.size();
}
// reserve enough elements so that iterators don't get invalidated
proximity_point_links.reserve(n_points * 2); // generally enough, unless there are a lot of 3-way intersections in the model
proximity_point_links_endings.reserve(n_points * 2); // any point can at most introduce two endings
// convert to list polygons for insertion of points
ListPolyIt::convertPolygonsToLists(polygons, list_polygons);
findProximatePoints();
addProximityEndings();
// TODO: add sharp corners
// convert list polygons back
ListPolyIt::convertListPolygonsToPolygons(list_polygons, polygons);
// wallOverlaps2HTML("output/output.html");
// list_polygons.clear(); // clear up some space! (unneccesary? it's just for the time the gcode is being generated...)
}
const PolygonProximityLinker::ProximityPointLink* PolygonProximityLinker::getLink(Point from)
{
Point2Link::iterator from_link_pair = point_to_link.find(from);
if (from_link_pair == point_to_link.end())
{
return nullptr;
}
return &from_link_pair->second;
}
void PolygonProximityLinker::findProximatePoints()
{
for (unsigned int poly_idx = 0; poly_idx < list_polygons.size(); poly_idx++)
{
ListPolygon& poly = list_polygons[poly_idx];
for (unsigned int poly2_idx = 0; poly2_idx <= poly_idx; poly2_idx++)
{
for (ListPolygon::iterator it = poly.begin(); it != poly.end(); ++it)
{
ListPolyIt lpi(poly, it);
if (poly_idx == poly2_idx)
{
// ListPolygon::iterator it2(it);
// ++it2;
// if (it2 != poly.end())
{
findProximatePoints(lpi, poly2_idx, it);
}
}
else
{
findProximatePoints(lpi, poly2_idx);
}
}
}
}
}
void PolygonProximityLinker::findProximatePoints(ListPolyIt from, unsigned int to_list_poly_idx)
{
findProximatePoints(from, to_list_poly_idx, list_polygons[to_list_poly_idx].begin());
}
void PolygonProximityLinker::findProximatePoints(ListPolyIt from_it, unsigned int to_list_poly_idx, const ListPolygon::iterator start)
{
ListPolygon& to_list_poly = list_polygons[to_list_poly_idx];
Point& from = from_it.p();
ListPolygon::iterator last_it = to_list_poly.end();
last_it--;
for (ListPolygon::iterator it = start; it != to_list_poly.end(); ++it)
{
Point& last_point = *last_it;
Point& point = *it;
if (&from_it.poly == &to_list_poly
&& (
(from_it.it == last_it || from_it.it == it) // we currently consider a linesegment directly connected to [from]
|| (from_it.prev().it == it || from_it.next().it == last_it) // line segment from [last_point] to [point] is connected to line segment of which [from] is the other end
)
)
{
last_it = it;
continue;
}
Point closest = LinearAlg2D::getClosestOnLineSegment(from, last_point, point);
int64_t dist2 = vSize2(closest - from);
if (dist2 > proximity_distance * proximity_distance
|| (&from_it.poly == &to_list_poly
&& dot(from_it.next().p() - from, point - last_point) > 0
&& dot(from - from_it.prev().p(), point - last_point) > 0 ) // line segments are likely connected, because the winding order is in the same general direction
)
{ // line segment too far away to be proximate
last_it = it;
continue;
}
int64_t dist = sqrt(dist2);
if (shorterThen(closest - last_point, 10))
{
addProximityLink(from_it, ListPolyIt(to_list_poly, last_it), dist);
}
else if (shorterThen(closest - point, 10))
{
addProximityLink(from_it, ListPolyIt(to_list_poly, it), dist);
}
else
{
ListPolygon::iterator new_it = to_list_poly.insert(it, closest);
addProximityLink(from_it, ListPolyIt(to_list_poly, new_it), dist);
}
last_it = it;
}
}
bool PolygonProximityLinker::addProximityLink(ListPolyIt from, ListPolyIt to, int64_t dist)
{
ProximityPointLink link(from, to, dist);
std::pair<ProximityPointLinks::iterator, bool> result =
proximity_point_links.emplace(link);
// if (! result.second)
// { // we already have the link
// DEBUG_PRINTLN("couldn't emplace in overlap_point_links! : ");
// result.first->second = attr;
// }
ProximityPointLinks::iterator it = result.first;
addToPoint2LinkMap(*it->a.it, it);
addToPoint2LinkMap(*it->b.it, it);
return result.second;
}
bool PolygonProximityLinker::addProximityLink_endings(ListPolyIt from, ListPolyIt to, int64_t dist)
{
ProximityPointLink link(from, to, dist);
std::pair<ProximityPointLinks::iterator, bool> result =
proximity_point_links_endings.emplace(link);
// if (! result.second)
// {
// DEBUG_PRINTLN("couldn't emplace in overlap_point_links! : ");
// result.first->second = attr;
// }
ProximityPointLinks::iterator it = result.first;
addToPoint2LinkMap(*it->a.it, it);
addToPoint2LinkMap(*it->b.it, it);
return result.second;
}
void PolygonProximityLinker::addProximityEndings()
{
for (const ProximityPointLink& link : proximity_point_links)
{
if (link.dist == proximity_distance)
{ // its ending itself
continue;
}
const ListPolyIt& a_1 = link.a;
const ListPolyIt& b_1 = link.b;
// an overlap segment can be an ending in two directions
{
ListPolyIt a_2 = a_1.next();
ListPolyIt b_2 = b_1.prev();
addProximityEnding(link, a_2, b_2, a_2, b_1);
}
{
ListPolyIt a_2 = a_1.prev();
ListPolyIt b_2 = b_1.next();
addProximityEnding(link, a_2, b_2, a_1, b_2);
}
}
}
void PolygonProximityLinker::addProximityEnding(const ProximityPointLink& link, const ListPolyIt& a2_it, const ListPolyIt& b2_it, const ListPolyIt& a_after_middle, const ListPolyIt& b_after_middle)
{
Point& a1 = link.a.p();
Point& a2 = a2_it.p();
Point& b1 = link.b.p();
Point& b2 = b2_it.p();
Point a = a2-a1;
Point b = b2-b1;
if (point_to_link.find(a2_it.p()) == point_to_link.end()
|| point_to_link.find(b2_it.p()) == point_to_link.end())
{
int64_t dist = proximityEndingDistance(a1, a2, b1, b2, link.dist);
if (dist < 0) { return; }
int64_t a_length2 = vSize2(a);
int64_t b_length2 = vSize2(b);
if (dist*dist > std::min(a_length2, b_length2) )
{ // TODO remove this /\ case if error below is never shown
// DEBUG_PRINTLN("Next point should have been linked already!!");
dist = std::sqrt(std::min(a_length2, b_length2));
if (a_length2 < b_length2)
{
Point b_p = b1 + normal(b, dist);
ListPolygon::iterator new_b = link.b.poly.insert(b_after_middle.it, b_p);
addProximityLink_endings(a2_it, ListPolyIt(link.b.poly, new_b), proximity_distance);
}
else if (b_length2 < a_length2)
{
Point a_p = a1 + normal(a, dist);
ListPolygon::iterator new_a = link.a.poly.insert(a_after_middle.it, a_p);
addProximityLink_endings(ListPolyIt(link.a.poly, new_a), b2_it, proximity_distance);
}
else // equal
{
addProximityLink_endings(a2_it, b2_it, proximity_distance);
}
}
if (dist > 0)
{
Point a_p = a1 + normal(a, dist);
ListPolygon::iterator new_a = link.a.poly.insert(a_after_middle.it, a_p);
Point b_p = b1 + normal(b, dist);
ListPolygon::iterator new_b = link.b.poly.insert(b_after_middle.it, b_p);
addProximityLink_endings(ListPolyIt(link.a.poly, new_a), ListPolyIt(link.b.poly, new_b), proximity_distance);
}
else if (dist == 0)
{
addProximityLink_endings(link.a, link.b, proximity_distance);
}
}
}
int64_t PolygonProximityLinker::proximityEndingDistance(Point& a1, Point& a2, Point& b1, Point& b2, int a1b1_dist)
{
int overlap = proximity_distance - a1b1_dist;
Point a = a2-a1;
Point b = b2-b1;
double cos_angle = INT2MM2(dot(a, b)) / vSizeMM(a) / vSizeMM(b);
// result == .5*overlap / tan(.5*angle) == .5*overlap / tan(.5*acos(cos_angle))
// [wolfram alpha] == 0.5*overlap * sqrt(cos_angle+1)/sqrt(1-cos_angle)
// [assuming positive x] == 0.5*overlap / sqrt( 2 / (cos_angle + 1) - 1 )
if (cos_angle <= 0
|| ! std::isfinite(cos_angle) )
{
return -1; // line_width / 2;
}
else if (cos_angle > .9999) // values near 1 can lead too large numbers for 1/x
{
return std::min(vSize(b), vSize(a));
}
else
{
int64_t dist = overlap * double ( 1.0 / (2.0 * sqrt(2.0 / (cos_angle+1.0) - 1.0)) );
return dist;
}
}
void PolygonProximityLinker::addSharpCorners()
{
}
void PolygonProximityLinker::addToPoint2LinkMap(Point p, ProximityPointLinks::iterator it)
{
point_to_link.emplace(p, *it); // copy element from proximity_point_links set to Point2Link map
// TODO: what to do if the map already contained a link? > three-way proximity
}
void PolygonProximityLinker::proximity2HTML(const char* filename) const
{
PolygonProximityLinker copy = *this; // copy, cause getFlow might change the state of the overlap computation!
AABB aabb(copy.polygons);
aabb.expand(200);
SVG svg(filename, aabb, Point(1024 * 2, 1024 * 2));
svg.writeAreas(copy.polygons);
{ // output points and coords
for (ListPolygon poly : copy.list_polygons)
{
for (Point& p : poly)
{
svg.writePoint(p, true);
}
}
}
{ // output links
// output normal links
for (const ProximityPointLink& link : copy.proximity_point_links)
{
Point a = svg.transform(link.a.p());
Point b = svg.transform(link.b.p());
svg.printf("<line x1=\"%lli\" y1=\"%lli\" x2=\"%lli\" y2=\"%lli\" style=\"stroke:rgb(%d,%d,0);stroke-width:1\" />", a.X, a.Y, b.X, b.Y, link.dist == proximity_distance? 0 : 255, link.dist==proximity_distance? 255 : 0);
}
// output ending links
for (const ProximityPointLink& link: copy.proximity_point_links_endings)
{
Point a = svg.transform(link.a.p());
Point b = svg.transform(link.b.p());
svg.printf("<line x1=\"%lli\" y1=\"%lli\" x2=\"%lli\" y2=\"%lli\" style=\"stroke:rgb(%d,%d,0);stroke-width:1\" />", a.X, a.Y, b.X, b.Y, link.dist == proximity_distance? 0 : 255, link.dist==proximity_distance? 255 : 0);
}
}
/*
{ // output flow
for (ListPolygon poly : copy.list_polygons)
{
Point p0 = poly.back();
svg.writePoint(p0, false, 5, SVG::Color::BLUE); // make start points of each poly blue
for (Point& p1 : poly)
{
Point middle = (p0 + p1) / 2;
float flow = copy.getFlow(p0, p1);
std::ostringstream oss;
oss << "flow: " << flow;
svg.writeText(middle, oss.str());
p0 = p1;
}
}
}
*/
}
}//namespace cura
<commit_msg>cleanup: removed unused commented code (CURA-1640)<commit_after>#include "PolygonProximityLinker.h"
#include <cmath> // isfinite
#include <sstream> // ostream
#include "AABB.h" // for debug output svg html
#include "SVG.h"
namespace cura
{
PolygonProximityLinker::PolygonProximityLinker(Polygons& polygons, int proximity_distance)
: polygons(polygons)
, proximity_distance(proximity_distance)
{
unsigned int n_points = 0;
for (PolygonRef poly : polygons)
{
n_points += poly.size();
}
// reserve enough elements so that iterators don't get invalidated
proximity_point_links.reserve(n_points * 2); // generally enough, unless there are a lot of 3-way intersections in the model
proximity_point_links_endings.reserve(n_points * 2); // any point can at most introduce two endings
// convert to list polygons for insertion of points
ListPolyIt::convertPolygonsToLists(polygons, list_polygons);
findProximatePoints();
addProximityEndings();
// TODO: add sharp corners
// convert list polygons back
ListPolyIt::convertListPolygonsToPolygons(list_polygons, polygons);
// wallOverlaps2HTML("output/output.html");
// list_polygons.clear(); // clear up some space! (unneccesary? it's just for the time the gcode is being generated...)
}
const PolygonProximityLinker::ProximityPointLink* PolygonProximityLinker::getLink(Point from)
{
Point2Link::iterator from_link_pair = point_to_link.find(from);
if (from_link_pair == point_to_link.end())
{
return nullptr;
}
return &from_link_pair->second;
}
void PolygonProximityLinker::findProximatePoints()
{
for (unsigned int poly_idx = 0; poly_idx < list_polygons.size(); poly_idx++)
{
ListPolygon& poly = list_polygons[poly_idx];
for (unsigned int poly2_idx = 0; poly2_idx <= poly_idx; poly2_idx++)
{
for (ListPolygon::iterator it = poly.begin(); it != poly.end(); ++it)
{
ListPolyIt lpi(poly, it);
if (poly_idx == poly2_idx)
{
// ListPolygon::iterator it2(it);
// ++it2;
// if (it2 != poly.end())
{
findProximatePoints(lpi, poly2_idx, it);
}
}
else
{
findProximatePoints(lpi, poly2_idx);
}
}
}
}
}
void PolygonProximityLinker::findProximatePoints(ListPolyIt from, unsigned int to_list_poly_idx)
{
findProximatePoints(from, to_list_poly_idx, list_polygons[to_list_poly_idx].begin());
}
void PolygonProximityLinker::findProximatePoints(ListPolyIt from_it, unsigned int to_list_poly_idx, const ListPolygon::iterator start)
{
ListPolygon& to_list_poly = list_polygons[to_list_poly_idx];
Point& from = from_it.p();
ListPolygon::iterator last_it = to_list_poly.end();
last_it--;
for (ListPolygon::iterator it = start; it != to_list_poly.end(); ++it)
{
Point& last_point = *last_it;
Point& point = *it;
if (&from_it.poly == &to_list_poly
&& (
(from_it.it == last_it || from_it.it == it) // we currently consider a linesegment directly connected to [from]
|| (from_it.prev().it == it || from_it.next().it == last_it) // line segment from [last_point] to [point] is connected to line segment of which [from] is the other end
)
)
{
last_it = it;
continue;
}
Point closest = LinearAlg2D::getClosestOnLineSegment(from, last_point, point);
int64_t dist2 = vSize2(closest - from);
if (dist2 > proximity_distance * proximity_distance
|| (&from_it.poly == &to_list_poly
&& dot(from_it.next().p() - from, point - last_point) > 0
&& dot(from - from_it.prev().p(), point - last_point) > 0 ) // line segments are likely connected, because the winding order is in the same general direction
)
{ // line segment too far away to be proximate
last_it = it;
continue;
}
int64_t dist = sqrt(dist2);
if (shorterThen(closest - last_point, 10))
{
addProximityLink(from_it, ListPolyIt(to_list_poly, last_it), dist);
}
else if (shorterThen(closest - point, 10))
{
addProximityLink(from_it, ListPolyIt(to_list_poly, it), dist);
}
else
{
ListPolygon::iterator new_it = to_list_poly.insert(it, closest);
addProximityLink(from_it, ListPolyIt(to_list_poly, new_it), dist);
}
last_it = it;
}
}
bool PolygonProximityLinker::addProximityLink(ListPolyIt from, ListPolyIt to, int64_t dist)
{
ProximityPointLink link(from, to, dist);
std::pair<ProximityPointLinks::iterator, bool> result =
proximity_point_links.emplace(link);
// if (! result.second)
// { // we already have the link
// DEBUG_PRINTLN("couldn't emplace in overlap_point_links! : ");
// result.first->second = attr;
// }
ProximityPointLinks::iterator it = result.first;
addToPoint2LinkMap(*it->a.it, it);
addToPoint2LinkMap(*it->b.it, it);
return result.second;
}
bool PolygonProximityLinker::addProximityLink_endings(ListPolyIt from, ListPolyIt to, int64_t dist)
{
ProximityPointLink link(from, to, dist);
std::pair<ProximityPointLinks::iterator, bool> result =
proximity_point_links_endings.emplace(link);
// if (! result.second)
// {
// DEBUG_PRINTLN("couldn't emplace in overlap_point_links! : ");
// result.first->second = attr;
// }
ProximityPointLinks::iterator it = result.first;
addToPoint2LinkMap(*it->a.it, it);
addToPoint2LinkMap(*it->b.it, it);
return result.second;
}
void PolygonProximityLinker::addProximityEndings()
{
for (const ProximityPointLink& link : proximity_point_links)
{
if (link.dist == proximity_distance)
{ // its ending itself
continue;
}
const ListPolyIt& a_1 = link.a;
const ListPolyIt& b_1 = link.b;
// an overlap segment can be an ending in two directions
{
ListPolyIt a_2 = a_1.next();
ListPolyIt b_2 = b_1.prev();
addProximityEnding(link, a_2, b_2, a_2, b_1);
}
{
ListPolyIt a_2 = a_1.prev();
ListPolyIt b_2 = b_1.next();
addProximityEnding(link, a_2, b_2, a_1, b_2);
}
}
}
void PolygonProximityLinker::addProximityEnding(const ProximityPointLink& link, const ListPolyIt& a2_it, const ListPolyIt& b2_it, const ListPolyIt& a_after_middle, const ListPolyIt& b_after_middle)
{
Point& a1 = link.a.p();
Point& a2 = a2_it.p();
Point& b1 = link.b.p();
Point& b2 = b2_it.p();
Point a = a2-a1;
Point b = b2-b1;
if (point_to_link.find(a2_it.p()) == point_to_link.end()
|| point_to_link.find(b2_it.p()) == point_to_link.end())
{
int64_t dist = proximityEndingDistance(a1, a2, b1, b2, link.dist);
if (dist < 0) { return; }
int64_t a_length2 = vSize2(a);
int64_t b_length2 = vSize2(b);
if (dist*dist > std::min(a_length2, b_length2) )
{ // TODO remove this /\ case if error below is never shown
// DEBUG_PRINTLN("Next point should have been linked already!!");
dist = std::sqrt(std::min(a_length2, b_length2));
if (a_length2 < b_length2)
{
Point b_p = b1 + normal(b, dist);
ListPolygon::iterator new_b = link.b.poly.insert(b_after_middle.it, b_p);
addProximityLink_endings(a2_it, ListPolyIt(link.b.poly, new_b), proximity_distance);
}
else if (b_length2 < a_length2)
{
Point a_p = a1 + normal(a, dist);
ListPolygon::iterator new_a = link.a.poly.insert(a_after_middle.it, a_p);
addProximityLink_endings(ListPolyIt(link.a.poly, new_a), b2_it, proximity_distance);
}
else // equal
{
addProximityLink_endings(a2_it, b2_it, proximity_distance);
}
}
if (dist > 0)
{
Point a_p = a1 + normal(a, dist);
ListPolygon::iterator new_a = link.a.poly.insert(a_after_middle.it, a_p);
Point b_p = b1 + normal(b, dist);
ListPolygon::iterator new_b = link.b.poly.insert(b_after_middle.it, b_p);
addProximityLink_endings(ListPolyIt(link.a.poly, new_a), ListPolyIt(link.b.poly, new_b), proximity_distance);
}
else if (dist == 0)
{
addProximityLink_endings(link.a, link.b, proximity_distance);
}
}
}
int64_t PolygonProximityLinker::proximityEndingDistance(Point& a1, Point& a2, Point& b1, Point& b2, int a1b1_dist)
{
int overlap = proximity_distance - a1b1_dist;
Point a = a2-a1;
Point b = b2-b1;
double cos_angle = INT2MM2(dot(a, b)) / vSizeMM(a) / vSizeMM(b);
// result == .5*overlap / tan(.5*angle) == .5*overlap / tan(.5*acos(cos_angle))
// [wolfram alpha] == 0.5*overlap * sqrt(cos_angle+1)/sqrt(1-cos_angle)
// [assuming positive x] == 0.5*overlap / sqrt( 2 / (cos_angle + 1) - 1 )
if (cos_angle <= 0
|| ! std::isfinite(cos_angle) )
{
return -1; // line_width / 2;
}
else if (cos_angle > .9999) // values near 1 can lead too large numbers for 1/x
{
return std::min(vSize(b), vSize(a));
}
else
{
int64_t dist = overlap * double ( 1.0 / (2.0 * sqrt(2.0 / (cos_angle+1.0) - 1.0)) );
return dist;
}
}
void PolygonProximityLinker::addSharpCorners()
{
}
void PolygonProximityLinker::addToPoint2LinkMap(Point p, ProximityPointLinks::iterator it)
{
point_to_link.emplace(p, *it); // copy element from proximity_point_links set to Point2Link map
// TODO: what to do if the map already contained a link? > three-way proximity
}
void PolygonProximityLinker::proximity2HTML(const char* filename) const
{
PolygonProximityLinker copy = *this; // copy, cause getFlow might change the state of the overlap computation!
AABB aabb(copy.polygons);
aabb.expand(200);
SVG svg(filename, aabb, Point(1024 * 2, 1024 * 2));
svg.writeAreas(copy.polygons);
{ // output points and coords
for (ListPolygon poly : copy.list_polygons)
{
for (Point& p : poly)
{
svg.writePoint(p, true);
}
}
}
{ // output links
// output normal links
for (const ProximityPointLink& link : copy.proximity_point_links)
{
Point a = svg.transform(link.a.p());
Point b = svg.transform(link.b.p());
svg.printf("<line x1=\"%lli\" y1=\"%lli\" x2=\"%lli\" y2=\"%lli\" style=\"stroke:rgb(%d,%d,0);stroke-width:1\" />", a.X, a.Y, b.X, b.Y, link.dist == proximity_distance? 0 : 255, link.dist==proximity_distance? 255 : 0);
}
// output ending links
for (const ProximityPointLink& link: copy.proximity_point_links_endings)
{
Point a = svg.transform(link.a.p());
Point b = svg.transform(link.b.p());
svg.printf("<line x1=\"%lli\" y1=\"%lli\" x2=\"%lli\" y2=\"%lli\" style=\"stroke:rgb(%d,%d,0);stroke-width:1\" />", a.X, a.Y, b.X, b.Y, link.dist == proximity_distance? 0 : 255, link.dist==proximity_distance? 255 : 0);
}
}
}
}//namespace cura
<|endoftext|> |
<commit_before>//===-- Win32 function wrapper implementations ----------------------------===//
//
// Copyright (c) 2013 Philip Jackson
// This file may be freely distributed under the MIT license.
//
//===----------------------------------------------------------------------===//
//
// The functions in this file try to do as little as possible.
//
// If a Windows function fails, and MSDN says to use GetLastError for more
// information, then call throwLastWin32Error(). This throws a std::system_error
// which wraps up the windows error code and it also looks like it tries to find
// a text description of the error too.
//
// If a Windows function sends a message as part of it's implementation, then
// it should call throwIfSavedException() immediately after it returns. This
// ensures any exceptions thrown in client code are propagated.
//
//===----------------------------------------------------------------------===//
#include "curt.h"
#include "error.h"
#include "include_windows.h"
#include "util.h"
#include <CommCtrl.h>
using namespace std;
namespace curt {
Font createFontIndirect(const LOGFONTA* logfont) {
return { CreateFontIndirectA(logfont) };
}
Font createFontIndirect(const LOGFONTW* logfont) {
return { CreateFontIndirectW(logfont) };
}
Window createWindowEx(
unsigned long exStyle,
StringOrAtom className,
OptString windowName,
unsigned long style,
int x, int y, int w, int h,
HandleOr<HWND> parent,
HMENU menu,
HINSTANCE hInst,
void *createParam
) {
auto newWindow = CreateWindowExW(
exStyle,
className,
windowName,
style,
x, y, w, h,
parent,
menu,
hInst,
createParam
);
throwIfSavedException();
if (!newWindow)
throwLastWin32Error();
return { newWindow };
}
LRESULT defSubclassProc(HandleOr<HWND> h, unsigned int m, WPARAM w, LPARAM l) {
auto result = DefSubclassProc(h, m, w, l);
throwIfSavedException();
return result;
}
LRESULT defWindowProc(HandleOr<HWND> h, unsigned int m, WPARAM w, LPARAM l) {
auto result = DefWindowProcW(h, m, w, l);
throwIfSavedException();
return result;
}
void destroyWindow(HandleOr<HWND> wnd) {
auto result = DestroyWindow(wnd);
throwIfSavedException();
if (!result)
throwLastWin32Error();
}
intptr_t dialogBoxParam(
HINSTANCE hInst,
StringOrId templateName,
HandleOr<HWND> parent,
DLGPROC proc,
intptr_t param
) {
auto result = DialogBoxParamW(hInst, templateName, parent, proc, param);
throwIfWin32Error();
return result;
}
LRESULT dispatchMessage(const MSG* msg) {
auto result = DispatchMessageW(msg);
throwIfSavedException();
return result;
}
void endDialog(HandleOr<HWND> dlg, intptr_t result) {
if (!EndDialog(dlg, result))
throwLastWin32Error();
}
int getDlgCtrlID(HandleOr<HWND> hwndCtl) {
auto result = GetDlgCtrlID(hwndCtl);
if (!result)
throwLastWin32Error();
return result;
}
HWND getDlgItem(HandleOr<HWND> wnd, int childId) {
auto result = GetDlgItem(wnd, childId);
if (!result)
throwLastWin32Error();
return result;
}
int messageBox(
HandleOr<HWND> parent,
String text,
String caption,
unsigned int type
) {
auto result = MessageBoxW(parent, text, caption, type);
throwIfSavedException();
if (!result)
throwLastWin32Error();
return result;
}
bool getMessage(
MSG* msg,
HandleOr<HWND> wnd,
unsigned int msgFilterMin,
unsigned int msgFilterMax
) {
auto result = GetMessageW(msg, wnd, msgFilterMin, msgFilterMax);
if (result < 0)
throwLastWin32Error();
return result != 0;
}
int multiByteToWideChar(
unsigned int cp,
unsigned long flags,
const char* mbStr,
int mbSize,
wchar_t* wideStr,
int numChars
) {
auto res = MultiByteToWideChar(cp, flags, mbStr, mbSize, wideStr, numChars);
if (!res)
throwLastWin32Error();
return res;
}
ATOM registerClassEx(const WNDCLASSEXA* wc) {
auto atom = RegisterClassExA(wc);
if (!atom)
throwLastWin32Error();
return atom;
}
ATOM registerClassEx(const WNDCLASSEXW* wc) {
auto atom = RegisterClassExW(wc);
if (!atom)
throwLastWin32Error();
return atom;
}
unsigned int registerWindowMessage(String str) {
auto msg = RegisterWindowMessageW(str);
if (!msg)
throwLastWin32Error();
return msg;
}
LRESULT sendDlgItemMessage(
HandleOr<HWND> dlg,
int dlgItemId,
unsigned int msg,
WPARAM wParam,
LPARAM lParam
) {
auto result = SendDlgItemMessageW(dlg, dlgItemId, msg, wParam, lParam);
throwIfSavedException();
return result;
}
LRESULT sendMessage(HandleOr<HWND> wnd, unsigned int m, WPARAM w, LPARAM l) {
auto result = SendMessageW(wnd, m, w, l);
throwIfSavedException();
auto error = GetLastError();
if (error)
throwWin32Error(error);
return result;
}
COLORREF setDCBrushColor(HDC hdc, COLORREF color) {
auto prev = SetDCBrushColor(hdc, color);
if (prev == CLR_INVALID)
throw std::invalid_argument("Invalid color argument for SetDCBrushColor");
return prev;
}
void setWindowPos(
HandleOr<HWND> wnd,
HandleOr<HWND> insertAfter,
int x, int y, int w, int h,
unsigned int flags
) {
auto result = SetWindowPos(wnd, insertAfter, x, y, w, h, flags);
throwIfSavedException();
if (!result)
throwLastWin32Error();
}
void setWindowSubclass(
HandleOr<HWND> wnd,
SUBCLASSPROC subclassProc,
std::uintptr_t subclassId,
std::uintptr_t refData
) {
if (!SetWindowSubclass(wnd, subclassProc, subclassId, refData))
throwLastWin32Error();
}
void setWindowText(HandleOr<HWND> wnd, String str) {
auto result = SetWindowTextW(wnd, str);
// SetWindowText sends a WM_SETTEXT message
throwIfSavedException();
if (!result)
throwLastWin32Error();
}
bool showWindow(HandleOr<HWND> wnd, int showCmd) {
auto result = ShowWindow(wnd, showCmd);
// showWindow is often called outside of a message loop
throwIfSavedException();
return result != 0;
}
void systemParametersInfo(
unsigned int action,
unsigned int uiParam,
void* pvParam,
unsigned int winIni
) {
if (!SystemParametersInfoW(action, uiParam, pvParam, winIni))
throwLastWin32Error();
}
bool translateAccelerator(HandleOr<HWND> wnd, HACCEL accelTable, MSG* msg) {
auto result = TranslateAcceleratorW(wnd, accelTable, msg) != 0;
// TranslateAccelerator sends the message directly after translating
throwIfSavedException();
return result;
}
bool translateMessage(const MSG* msg) {
return TranslateMessage(msg) != 0;
}
void updateWindow(HandleOr<HWND> wnd) {
auto result = UpdateWindow(wnd);
// updateWindow is often called outside of a message loop
throwIfSavedException();
if (!result)
throwLastWin32Error();
}
HGDIOBJ getStockObject(int object) {
auto result = GetStockObject(object);
if (!result)
throwLastWin32Error();
return result;
}
int getWindowTextLength(HandleOr<HWND> wnd) {
auto result = GetWindowTextLengthW(wnd);
// GetWindowTextLength sends the WM_GETTEXTLENGTH message
throwIfSavedException();
auto error = GetLastError();
if (error)
throwWin32Error(error);
return result;
}
int getWindowTextA(HandleOr<HWND> wnd, char* buffer, int bufferSize) {
auto result = GetWindowTextA(wnd, buffer, bufferSize);
// GetWindowText sends the WM_GETTEXT message
throwIfSavedException();
auto error = GetLastError();
if (error)
throwWin32Error(error);
return result;
}
int getWindowTextW(HandleOr<HWND> wnd, wchar_t* buffer, int bufferSize) {
auto result = GetWindowTextW(wnd, buffer, bufferSize);
// GetWindowText sends the WM_GETTEXT message
throwIfSavedException();
auto error = GetLastError();
if (error)
throwWin32Error(error);
return result;
}
HACCEL loadAccelerators(HINSTANCE hInst, StringOrId tableName) {
auto result = LoadAcceleratorsW(hInst, tableName);
if (!result)
throwLastWin32Error();
return result;
}
int loadString(HINSTANCE hInst, unsigned int id, wchar_t* buffer, int buffSz) {
auto result = LoadStringW(hInst, id, buffer, buffSz);
if (!result)
throwLastWin32Error();
return result;
}
int wideCharToMultiByte(
unsigned int codePage,
unsigned long flags,
const wchar_t* wideStr,
int numChars,
char* multiByteStr,
int multiByteSize,
const char* defaultChar,
bool* usedDefaultChar
) {
auto localUsedDefault = 0;
if (usedDefaultChar && *usedDefaultChar)
localUsedDefault = 1;
auto res = WideCharToMultiByte(
codePage,
flags,
wideStr,
numChars,
multiByteStr,
multiByteSize,
defaultChar,
usedDefaultChar ? &localUsedDefault : nullptr
);
if (!res)
throwLastWin32Error();
if (usedDefaultChar)
*usedDefaultChar = localUsedDefault != 0;
return res;
}
} // end namespace curt
<commit_msg>We have an easier way to check for the last error message.<commit_after>//===-- Win32 function wrapper implementations ----------------------------===//
//
// Copyright (c) 2013 Philip Jackson
// This file may be freely distributed under the MIT license.
//
//===----------------------------------------------------------------------===//
//
// The functions in this file try to do as little as possible.
//
// If a Windows function fails, and MSDN says to use GetLastError for more
// information, then call throwLastWin32Error(). This throws a std::system_error
// which wraps up the windows error code and it also looks like it tries to find
// a text description of the error too.
//
// If a Windows function sends a message as part of it's implementation, then
// it should call throwIfSavedException() immediately after it returns. This
// ensures any exceptions thrown in client code are propagated.
//
//===----------------------------------------------------------------------===//
#include "curt.h"
#include "error.h"
#include "include_windows.h"
#include "util.h"
#include <CommCtrl.h>
using namespace std;
namespace curt {
Font createFontIndirect(const LOGFONTA* logfont) {
return { CreateFontIndirectA(logfont) };
}
Font createFontIndirect(const LOGFONTW* logfont) {
return { CreateFontIndirectW(logfont) };
}
Window createWindowEx(
unsigned long exStyle,
StringOrAtom className,
OptString windowName,
unsigned long style,
int x, int y, int w, int h,
HandleOr<HWND> parent,
HMENU menu,
HINSTANCE hInst,
void *createParam
) {
auto newWindow = CreateWindowExW(
exStyle,
className,
windowName,
style,
x, y, w, h,
parent,
menu,
hInst,
createParam
);
throwIfSavedException();
if (!newWindow)
throwLastWin32Error();
return { newWindow };
}
LRESULT defSubclassProc(HandleOr<HWND> h, unsigned int m, WPARAM w, LPARAM l) {
auto result = DefSubclassProc(h, m, w, l);
throwIfSavedException();
return result;
}
LRESULT defWindowProc(HandleOr<HWND> h, unsigned int m, WPARAM w, LPARAM l) {
auto result = DefWindowProcW(h, m, w, l);
throwIfSavedException();
return result;
}
void destroyWindow(HandleOr<HWND> wnd) {
auto result = DestroyWindow(wnd);
throwIfSavedException();
if (!result)
throwLastWin32Error();
}
intptr_t dialogBoxParam(
HINSTANCE hInst,
StringOrId templateName,
HandleOr<HWND> parent,
DLGPROC proc,
intptr_t param
) {
auto result = DialogBoxParamW(hInst, templateName, parent, proc, param);
throwIfWin32Error();
return result;
}
LRESULT dispatchMessage(const MSG* msg) {
auto result = DispatchMessageW(msg);
throwIfSavedException();
return result;
}
void endDialog(HandleOr<HWND> dlg, intptr_t result) {
if (!EndDialog(dlg, result))
throwLastWin32Error();
}
int getDlgCtrlID(HandleOr<HWND> hwndCtl) {
auto result = GetDlgCtrlID(hwndCtl);
if (!result)
throwLastWin32Error();
return result;
}
HWND getDlgItem(HandleOr<HWND> wnd, int childId) {
auto result = GetDlgItem(wnd, childId);
if (!result)
throwLastWin32Error();
return result;
}
int messageBox(
HandleOr<HWND> parent,
String text,
String caption,
unsigned int type
) {
auto result = MessageBoxW(parent, text, caption, type);
throwIfSavedException();
if (!result)
throwLastWin32Error();
return result;
}
bool getMessage(
MSG* msg,
HandleOr<HWND> wnd,
unsigned int msgFilterMin,
unsigned int msgFilterMax
) {
auto result = GetMessageW(msg, wnd, msgFilterMin, msgFilterMax);
if (result < 0)
throwLastWin32Error();
return result != 0;
}
int multiByteToWideChar(
unsigned int cp,
unsigned long flags,
const char* mbStr,
int mbSize,
wchar_t* wideStr,
int numChars
) {
auto res = MultiByteToWideChar(cp, flags, mbStr, mbSize, wideStr, numChars);
if (!res)
throwLastWin32Error();
return res;
}
ATOM registerClassEx(const WNDCLASSEXA* wc) {
auto atom = RegisterClassExA(wc);
if (!atom)
throwLastWin32Error();
return atom;
}
ATOM registerClassEx(const WNDCLASSEXW* wc) {
auto atom = RegisterClassExW(wc);
if (!atom)
throwLastWin32Error();
return atom;
}
unsigned int registerWindowMessage(String str) {
auto msg = RegisterWindowMessageW(str);
if (!msg)
throwLastWin32Error();
return msg;
}
LRESULT sendDlgItemMessage(
HandleOr<HWND> dlg,
int dlgItemId,
unsigned int msg,
WPARAM wParam,
LPARAM lParam
) {
auto result = SendDlgItemMessageW(dlg, dlgItemId, msg, wParam, lParam);
throwIfSavedException();
return result;
}
LRESULT sendMessage(HandleOr<HWND> wnd, unsigned int m, WPARAM w, LPARAM l) {
auto result = SendMessageW(wnd, m, w, l);
throwIfSavedException();
throwIfWin32Error();
return result;
}
COLORREF setDCBrushColor(HDC hdc, COLORREF color) {
auto prev = SetDCBrushColor(hdc, color);
if (prev == CLR_INVALID)
throw std::invalid_argument("Invalid color argument for SetDCBrushColor");
return prev;
}
void setWindowPos(
HandleOr<HWND> wnd,
HandleOr<HWND> insertAfter,
int x, int y, int w, int h,
unsigned int flags
) {
auto result = SetWindowPos(wnd, insertAfter, x, y, w, h, flags);
throwIfSavedException();
if (!result)
throwLastWin32Error();
}
void setWindowSubclass(
HandleOr<HWND> wnd,
SUBCLASSPROC subclassProc,
std::uintptr_t subclassId,
std::uintptr_t refData
) {
if (!SetWindowSubclass(wnd, subclassProc, subclassId, refData))
throwLastWin32Error();
}
void setWindowText(HandleOr<HWND> wnd, String str) {
auto result = SetWindowTextW(wnd, str);
// SetWindowText sends a WM_SETTEXT message
throwIfSavedException();
if (!result)
throwLastWin32Error();
}
bool showWindow(HandleOr<HWND> wnd, int showCmd) {
auto result = ShowWindow(wnd, showCmd);
// showWindow is often called outside of a message loop
throwIfSavedException();
return result != 0;
}
void systemParametersInfo(
unsigned int action,
unsigned int uiParam,
void* pvParam,
unsigned int winIni
) {
if (!SystemParametersInfoW(action, uiParam, pvParam, winIni))
throwLastWin32Error();
}
bool translateAccelerator(HandleOr<HWND> wnd, HACCEL accelTable, MSG* msg) {
auto result = TranslateAcceleratorW(wnd, accelTable, msg) != 0;
// TranslateAccelerator sends the message directly after translating
throwIfSavedException();
return result;
}
bool translateMessage(const MSG* msg) {
return TranslateMessage(msg) != 0;
}
void updateWindow(HandleOr<HWND> wnd) {
auto result = UpdateWindow(wnd);
// updateWindow is often called outside of a message loop
throwIfSavedException();
if (!result)
throwLastWin32Error();
}
HGDIOBJ getStockObject(int object) {
auto result = GetStockObject(object);
if (!result)
throwLastWin32Error();
return result;
}
int getWindowTextLength(HandleOr<HWND> wnd) {
auto result = GetWindowTextLengthW(wnd);
// GetWindowTextLength sends the WM_GETTEXTLENGTH message
throwIfSavedException();
throwIfWin32Error();
return result;
}
int getWindowTextA(HandleOr<HWND> wnd, char* buffer, int bufferSize) {
auto result = GetWindowTextA(wnd, buffer, bufferSize);
// GetWindowText sends the WM_GETTEXT message
throwIfSavedException();
throwIfWin32Error();
return result;
}
int getWindowTextW(HandleOr<HWND> wnd, wchar_t* buffer, int bufferSize) {
auto result = GetWindowTextW(wnd, buffer, bufferSize);
// GetWindowText sends the WM_GETTEXT message
throwIfSavedException();
throwIfWin32Error();
return result;
}
HACCEL loadAccelerators(HINSTANCE hInst, StringOrId tableName) {
auto result = LoadAcceleratorsW(hInst, tableName);
if (!result)
throwLastWin32Error();
return result;
}
int loadString(HINSTANCE hInst, unsigned int id, wchar_t* buffer, int buffSz) {
auto result = LoadStringW(hInst, id, buffer, buffSz);
if (!result)
throwLastWin32Error();
return result;
}
int wideCharToMultiByte(
unsigned int codePage,
unsigned long flags,
const wchar_t* wideStr,
int numChars,
char* multiByteStr,
int multiByteSize,
const char* defaultChar,
bool* usedDefaultChar
) {
auto localUsedDefault = 0;
if (usedDefaultChar && *usedDefaultChar)
localUsedDefault = 1;
auto res = WideCharToMultiByte(
codePage,
flags,
wideStr,
numChars,
multiByteStr,
multiByteSize,
defaultChar,
usedDefaultChar ? &localUsedDefault : nullptr
);
if (!res)
throwLastWin32Error();
if (usedDefaultChar)
*usedDefaultChar = localUsedDefault != 0;
return res;
}
} // end namespace curt
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include <sfx2/request.hxx>
#include <svl/eitem.hxx>
#include <basic/sbxvar.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/bindings.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <textsh.hxx>
#include <num.hxx>
#include <edtwin.hxx>
#include <crsskip.hxx>
#include <doc.hxx>
#include <docsh.hxx>
#include <cmdid.h>
#include <globals.h>
#include <globals.hrc>
#include <svx/svdouno.hxx>
#include <svx/fmshell.hxx>
#include <svx/sdrobjectfilter.hxx>
#include <boost/scoped_ptr.hpp>
using namespace ::com::sun::star;
void SwTextShell::ExecBasicMove(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
GetView().GetEditWin().FlushInBuffer();
const SfxItemSet *pArgs = rReq.GetArgs();
bool bSelect = false;
sal_Int32 nCount = 1;
if(pArgs)
{
const SfxPoolItem *pItem;
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_MOVE_COUNT, true, &pItem))
nCount = ((const SfxInt32Item *)pItem)->GetValue();
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_MOVE_SELECTION, true, &pItem))
bSelect = ((const SfxBoolItem *)pItem)->GetValue();
}
switch(rReq.GetSlot())
{
case FN_CHAR_LEFT_SEL:
rReq.SetSlot( FN_CHAR_LEFT );
bSelect = true;
break;
case FN_CHAR_RIGHT_SEL:
rReq.SetSlot( FN_CHAR_RIGHT );
bSelect = true;
break;
case FN_LINE_UP_SEL:
rReq.SetSlot( FN_LINE_UP );
bSelect = true;
break;
case FN_LINE_DOWN_SEL:
rReq.SetSlot( FN_LINE_DOWN );
bSelect = true;
break;
}
uno::Reference< frame::XDispatchRecorder > xRecorder =
GetView().GetViewFrame()->GetBindings().GetRecorder();
if ( xRecorder.is() )
{
rReq.AppendItem( SfxInt32Item(FN_PARAM_MOVE_COUNT, nCount) );
rReq.AppendItem( SfxBoolItem(FN_PARAM_MOVE_SELECTION, bSelect) );
}
sal_uInt16 nSlot = rReq.GetSlot();
rReq.Done();
// Get EditWin before calling the move functions (shell change may occur!)
SwEditWin& rTmpEditWin = GetView().GetEditWin();
for( sal_Int32 i = 0; i < nCount; i++ )
{
switch(nSlot)
{
case FN_CHAR_LEFT:
rSh.Left( CRSR_SKIP_CELLS, bSelect, 1, false, true );
break;
case FN_CHAR_RIGHT:
rSh.Right( CRSR_SKIP_CELLS, bSelect, 1, false, true );
break;
case FN_LINE_UP:
rSh.Up( bSelect, 1 );
break;
case FN_LINE_DOWN:
rSh.Down( bSelect, 1 );
break;
default:
OSL_FAIL("wrong Dispatcher");
return;
}
}
//#i42732# - notify the edit window that from now on we do not use the input language
rTmpEditWin.SetUseInputLanguage( false );
}
void SwTextShell::ExecMove(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
SwEditWin& rTmpEditWin = GetView().GetEditWin();
rTmpEditWin.FlushInBuffer();
sal_uInt16 nSlot = rReq.GetSlot();
bool bRet = false;
switch ( nSlot )
{
case FN_START_OF_LINE_SEL:
bRet = rSh.LeftMargin( true, false );
break;
case FN_START_OF_LINE:
bRet = rSh.LeftMargin( false, false );
break;
case FN_END_OF_LINE_SEL:
bRet = rSh.RightMargin( true, false );
break;
case FN_END_OF_LINE:
bRet = rSh.RightMargin( false, false );
break;
case FN_START_OF_DOCUMENT_SEL:
bRet = rSh.SttDoc( true );
break;
case FN_START_OF_DOCUMENT:
bRet = rSh.SttDoc( false );
break;
case FN_END_OF_DOCUMENT_SEL:
bRet = rSh.EndDoc( true );
break;
case FN_END_OF_DOCUMENT:
bRet = rSh.EndDoc( false );
break;
case FN_SELECT_WORD:
bRet = rSh.SelNearestWrd();
break;
case SID_SELECTALL:
bRet = 0 != rSh.SelAll();
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
if ( bRet )
rReq.Done();
else
rReq.Ignore();
//#i42732# - notify the edit window that from now on we do not use the input language
rTmpEditWin.SetUseInputLanguage( false );
}
void SwTextShell::ExecMovePage(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
GetView().GetEditWin().FlushInBuffer();
sal_uInt16 nSlot = rReq.GetSlot();
switch( nSlot )
{
case FN_START_OF_NEXT_PAGE_SEL :
rSh.SttNxtPg( true );
break;
case FN_START_OF_NEXT_PAGE:
rSh.SttNxtPg( false );
break;
case FN_END_OF_NEXT_PAGE_SEL:
rSh.EndNxtPg( true );
break;
case FN_END_OF_NEXT_PAGE:
rSh.EndNxtPg( false );
break;
case FN_START_OF_PREV_PAGE_SEL:
rSh.SttPrvPg( true );
break;
case FN_START_OF_PREV_PAGE:
rSh.SttPrvPg( false );
break;
case FN_END_OF_PREV_PAGE_SEL:
rSh.EndPrvPg( true );
break;
case FN_END_OF_PREV_PAGE:
rSh.EndPrvPg( false );
break;
case FN_START_OF_PAGE_SEL:
rSh.SttPg( true );
break;
case FN_START_OF_PAGE:
rSh.SttPg( false );
break;
case FN_END_OF_PAGE_SEL:
rSh.EndPg( true );
break;
case FN_END_OF_PAGE:
rSh.EndPg( false );
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
rReq.Done();
}
void SwTextShell::ExecMoveCol(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
switch ( rReq.GetSlot() )
{
case FN_START_OF_COLUMN:
rSh.StartOfColumn( false );
break;
case FN_END_OF_COLUMN:
rSh.EndOfColumn( false );
break;
case FN_START_OF_NEXT_COLUMN:
rSh.StartOfNextColumn( false ) ;
break;
case FN_END_OF_NEXT_COLUMN:
rSh.EndOfNextColumn( false );
break;
case FN_START_OF_PREV_COLUMN:
rSh.StartOfPrevColumn( false );
break;
case FN_END_OF_PREV_COLUMN:
rSh.EndOfPrevColumn( false );
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
rReq.Done();
}
void SwTextShell::ExecMoveLingu(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
GetView().GetEditWin().FlushInBuffer();
sal_uInt16 nSlot = rReq.GetSlot();
switch ( nSlot )
{
case FN_NEXT_WORD_SEL:
rSh.NxtWrd( true );
break;
case FN_NEXT_WORD:
rSh.NxtWrd( false );
break;
case FN_START_OF_PARA_SEL:
rSh.SttPara( true );
break;
case FN_START_OF_PARA:
rSh.SttPara( false );
break;
case FN_END_OF_PARA_SEL:
rSh.EndPara( true );
break;
case FN_END_OF_PARA:
rSh.EndPara( false );
break;
case FN_PREV_WORD_SEL:
rSh.PrvWrd( true );
break;
case FN_PREV_WORD:
rSh.PrvWrd( false );
break;
case FN_NEXT_SENT_SEL:
rSh.FwdSentence( true );
break;
case FN_NEXT_SENT:
rSh.FwdSentence( false );
break;
case FN_PREV_SENT_SEL:
rSh.BwdSentence( true );
break;
case FN_PREV_SENT:
rSh.BwdSentence( false );
break;
case FN_NEXT_PARA:
rSh.FwdPara( false );
break;
case FN_PREV_PARA:
rSh.BwdPara( false );
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
rReq.Done();
}
void SwTextShell::ExecMoveMisc(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
sal_uInt16 nSlot = rReq.GetSlot();
bool bSetRetVal = true, bRet = true;
switch ( nSlot )
{
case SID_FM_TOGGLECONTROLFOCUS:
{
const SwDoc* pDoc = rSh.GetDoc();
const SwDocShell* pDocShell = pDoc ? pDoc->GetDocShell() : NULL;
const SwView* pView = pDocShell ? pDocShell->GetView() : NULL;
const FmFormShell* pFormShell = pView ? pView->GetFormShell() : NULL;
SdrView* pDrawView = pView ? pView->GetDrawView() : NULL;
Window* pWindow = pView ? pView->GetWrtShell().GetWin() : NULL;
OSL_ENSURE( pFormShell && pDrawView && pWindow, "SwXTextView::ExecMoveMisc: no chance!" );
if ( !pFormShell || !pDrawView || !pWindow )
break;
boost::scoped_ptr< ::svx::ISdrObjectFilter > pFilter( pFormShell->CreateFocusableControlFilter(
*pDrawView, *pWindow ) );
if ( !pFilter.get() )
break;
const SdrObject* pNearestControl = rSh.GetBestObject( true, GOTOOBJ_DRAW_CONTROL, false, pFilter.get() );
if ( !pNearestControl )
break;
const SdrUnoObj* pUnoObject = dynamic_cast< const SdrUnoObj* >( pNearestControl );
OSL_ENSURE( pUnoObject, "SwTextShell::ExecMoveMisc: GetBestObject returned nonsense!" );
if ( !pUnoObject )
break;
pFormShell->ToggleControlFocus( *pUnoObject, *pDrawView, *pWindow );
}
break;
case FN_CNTNT_TO_NEXT_FRAME:
bRet = rSh.GotoObj(true, GOTOOBJ_GOTO_ANY);
if(bRet)
{
rSh.HideCrsr();
rSh.EnterSelFrmMode();
}
break;
case FN_NEXT_FOOTNOTE:
rSh.MoveCrsr();
bRet = rSh.GotoNextFtnAnchor();
break;
case FN_PREV_FOOTNOTE:
rSh.MoveCrsr();
bRet = rSh.GotoPrevFtnAnchor();
break;
case FN_TO_HEADER:
rSh.MoveCrsr();
if ( ( FRMTYPE_HEADER & rSh.GetFrmType(0,false) ) || rSh.GotoHeaderTxt() )
rSh.SttPg();
bSetRetVal = false;
break;
case FN_TO_FOOTER:
rSh.MoveCrsr();
if ( ( FRMTYPE_FOOTER & rSh.GetFrmType(0,false) ) || rSh.GotoFooterTxt() )
rSh.EndPg();
bSetRetVal = false;
break;
case FN_FOOTNOTE_TO_ANCHOR:
rSh.MoveCrsr();
if ( FRMTYPE_FOOTNOTE & rSh.GetFrmType(0,false) )
rSh.GotoFtnAnchor();
else
rSh.GotoFtnTxt();
bSetRetVal = false;
break;
case FN_TO_FOOTNOTE_AREA :
rSh.GotoFtnTxt();
break;
case FN_PREV_TABLE:
bRet = rSh.MoveTable( fnTablePrev, fnTableStart);
break;
case FN_NEXT_TABLE:
bRet = rSh.MoveTable(fnTableNext, fnTableStart);
break;
case FN_GOTO_NEXT_REGION :
bRet = rSh.MoveRegion(fnRegionNext, fnRegionStart);
break;
case FN_GOTO_PREV_REGION :
bRet = rSh.MoveRegion(fnRegionPrev, fnRegionStart);
break;
case FN_NEXT_TOXMARK:
bRet = rSh.GotoNxtPrvTOXMark( true );
break;
case FN_PREV_TOXMARK:
bRet = rSh.GotoNxtPrvTOXMark( false );
break;
case FN_NEXT_TBLFML:
bRet = rSh.GotoNxtPrvTblFormula( true, false );
break;
case FN_PREV_TBLFML:
bRet = rSh.GotoNxtPrvTblFormula( false, false );
break;
case FN_NEXT_TBLFML_ERR:
bRet = rSh.GotoNxtPrvTblFormula( true, true );
break;
case FN_PREV_TBLFML_ERR:
bRet = rSh.GotoNxtPrvTblFormula( false, true );
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
if( bSetRetVal )
rReq.SetReturnValue(SfxBoolItem( nSlot, bRet ));
rReq.Done();
bool bInHeader = true;
if ( rSh.IsInHeaderFooter( &bInHeader ) )
{
if ( !bInHeader )
{
rSh.SetShowHeaderFooterSeparator( Footer, true );
rSh.SetShowHeaderFooterSeparator( Header, false );
}
else
{
rSh.SetShowHeaderFooterSeparator( Header, true );
rSh.SetShowHeaderFooterSeparator( Footer, false );
}
// Force repaint
rSh.GetWin()->Invalidate();
}
if ( rSh.IsInHeaderFooter() != rSh.IsHeaderFooterEdit() )
rSh.ToggleHeaderFooterEdit();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>sal_uInt16: constify and avoid temporaries<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* 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/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include <sfx2/request.hxx>
#include <svl/eitem.hxx>
#include <basic/sbxvar.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/bindings.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <textsh.hxx>
#include <num.hxx>
#include <edtwin.hxx>
#include <crsskip.hxx>
#include <doc.hxx>
#include <docsh.hxx>
#include <cmdid.h>
#include <globals.h>
#include <globals.hrc>
#include <svx/svdouno.hxx>
#include <svx/fmshell.hxx>
#include <svx/sdrobjectfilter.hxx>
#include <boost/scoped_ptr.hpp>
using namespace ::com::sun::star;
void SwTextShell::ExecBasicMove(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
GetView().GetEditWin().FlushInBuffer();
const SfxItemSet *pArgs = rReq.GetArgs();
bool bSelect = false;
sal_Int32 nCount = 1;
if(pArgs)
{
const SfxPoolItem *pItem;
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_MOVE_COUNT, true, &pItem))
nCount = ((const SfxInt32Item *)pItem)->GetValue();
if(SFX_ITEM_SET == pArgs->GetItemState(FN_PARAM_MOVE_SELECTION, true, &pItem))
bSelect = ((const SfxBoolItem *)pItem)->GetValue();
}
switch(rReq.GetSlot())
{
case FN_CHAR_LEFT_SEL:
rReq.SetSlot( FN_CHAR_LEFT );
bSelect = true;
break;
case FN_CHAR_RIGHT_SEL:
rReq.SetSlot( FN_CHAR_RIGHT );
bSelect = true;
break;
case FN_LINE_UP_SEL:
rReq.SetSlot( FN_LINE_UP );
bSelect = true;
break;
case FN_LINE_DOWN_SEL:
rReq.SetSlot( FN_LINE_DOWN );
bSelect = true;
break;
}
uno::Reference< frame::XDispatchRecorder > xRecorder =
GetView().GetViewFrame()->GetBindings().GetRecorder();
if ( xRecorder.is() )
{
rReq.AppendItem( SfxInt32Item(FN_PARAM_MOVE_COUNT, nCount) );
rReq.AppendItem( SfxBoolItem(FN_PARAM_MOVE_SELECTION, bSelect) );
}
const sal_uInt16 nSlot = rReq.GetSlot();
rReq.Done();
// Get EditWin before calling the move functions (shell change may occur!)
SwEditWin& rTmpEditWin = GetView().GetEditWin();
for( sal_Int32 i = 0; i < nCount; i++ )
{
switch(nSlot)
{
case FN_CHAR_LEFT:
rSh.Left( CRSR_SKIP_CELLS, bSelect, 1, false, true );
break;
case FN_CHAR_RIGHT:
rSh.Right( CRSR_SKIP_CELLS, bSelect, 1, false, true );
break;
case FN_LINE_UP:
rSh.Up( bSelect, 1 );
break;
case FN_LINE_DOWN:
rSh.Down( bSelect, 1 );
break;
default:
OSL_FAIL("wrong Dispatcher");
return;
}
}
//#i42732# - notify the edit window that from now on we do not use the input language
rTmpEditWin.SetUseInputLanguage( false );
}
void SwTextShell::ExecMove(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
SwEditWin& rTmpEditWin = GetView().GetEditWin();
rTmpEditWin.FlushInBuffer();
bool bRet = false;
switch ( rReq.GetSlot() )
{
case FN_START_OF_LINE_SEL:
bRet = rSh.LeftMargin( true, false );
break;
case FN_START_OF_LINE:
bRet = rSh.LeftMargin( false, false );
break;
case FN_END_OF_LINE_SEL:
bRet = rSh.RightMargin( true, false );
break;
case FN_END_OF_LINE:
bRet = rSh.RightMargin( false, false );
break;
case FN_START_OF_DOCUMENT_SEL:
bRet = rSh.SttDoc( true );
break;
case FN_START_OF_DOCUMENT:
bRet = rSh.SttDoc( false );
break;
case FN_END_OF_DOCUMENT_SEL:
bRet = rSh.EndDoc( true );
break;
case FN_END_OF_DOCUMENT:
bRet = rSh.EndDoc( false );
break;
case FN_SELECT_WORD:
bRet = rSh.SelNearestWrd();
break;
case SID_SELECTALL:
bRet = 0 != rSh.SelAll();
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
if ( bRet )
rReq.Done();
else
rReq.Ignore();
//#i42732# - notify the edit window that from now on we do not use the input language
rTmpEditWin.SetUseInputLanguage( false );
}
void SwTextShell::ExecMovePage(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
GetView().GetEditWin().FlushInBuffer();
switch( rReq.GetSlot() )
{
case FN_START_OF_NEXT_PAGE_SEL :
rSh.SttNxtPg( true );
break;
case FN_START_OF_NEXT_PAGE:
rSh.SttNxtPg( false );
break;
case FN_END_OF_NEXT_PAGE_SEL:
rSh.EndNxtPg( true );
break;
case FN_END_OF_NEXT_PAGE:
rSh.EndNxtPg( false );
break;
case FN_START_OF_PREV_PAGE_SEL:
rSh.SttPrvPg( true );
break;
case FN_START_OF_PREV_PAGE:
rSh.SttPrvPg( false );
break;
case FN_END_OF_PREV_PAGE_SEL:
rSh.EndPrvPg( true );
break;
case FN_END_OF_PREV_PAGE:
rSh.EndPrvPg( false );
break;
case FN_START_OF_PAGE_SEL:
rSh.SttPg( true );
break;
case FN_START_OF_PAGE:
rSh.SttPg( false );
break;
case FN_END_OF_PAGE_SEL:
rSh.EndPg( true );
break;
case FN_END_OF_PAGE:
rSh.EndPg( false );
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
rReq.Done();
}
void SwTextShell::ExecMoveCol(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
switch ( rReq.GetSlot() )
{
case FN_START_OF_COLUMN:
rSh.StartOfColumn( false );
break;
case FN_END_OF_COLUMN:
rSh.EndOfColumn( false );
break;
case FN_START_OF_NEXT_COLUMN:
rSh.StartOfNextColumn( false ) ;
break;
case FN_END_OF_NEXT_COLUMN:
rSh.EndOfNextColumn( false );
break;
case FN_START_OF_PREV_COLUMN:
rSh.StartOfPrevColumn( false );
break;
case FN_END_OF_PREV_COLUMN:
rSh.EndOfPrevColumn( false );
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
rReq.Done();
}
void SwTextShell::ExecMoveLingu(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
GetView().GetEditWin().FlushInBuffer();
switch ( rReq.GetSlot() )
{
case FN_NEXT_WORD_SEL:
rSh.NxtWrd( true );
break;
case FN_NEXT_WORD:
rSh.NxtWrd( false );
break;
case FN_START_OF_PARA_SEL:
rSh.SttPara( true );
break;
case FN_START_OF_PARA:
rSh.SttPara( false );
break;
case FN_END_OF_PARA_SEL:
rSh.EndPara( true );
break;
case FN_END_OF_PARA:
rSh.EndPara( false );
break;
case FN_PREV_WORD_SEL:
rSh.PrvWrd( true );
break;
case FN_PREV_WORD:
rSh.PrvWrd( false );
break;
case FN_NEXT_SENT_SEL:
rSh.FwdSentence( true );
break;
case FN_NEXT_SENT:
rSh.FwdSentence( false );
break;
case FN_PREV_SENT_SEL:
rSh.BwdSentence( true );
break;
case FN_PREV_SENT:
rSh.BwdSentence( false );
break;
case FN_NEXT_PARA:
rSh.FwdPara( false );
break;
case FN_PREV_PARA:
rSh.BwdPara( false );
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
rReq.Done();
}
void SwTextShell::ExecMoveMisc(SfxRequest &rReq)
{
SwWrtShell &rSh = GetShell();
const sal_uInt16 nSlot = rReq.GetSlot();
bool bSetRetVal = true, bRet = true;
switch ( nSlot )
{
case SID_FM_TOGGLECONTROLFOCUS:
{
const SwDoc* pDoc = rSh.GetDoc();
const SwDocShell* pDocShell = pDoc ? pDoc->GetDocShell() : NULL;
const SwView* pView = pDocShell ? pDocShell->GetView() : NULL;
const FmFormShell* pFormShell = pView ? pView->GetFormShell() : NULL;
SdrView* pDrawView = pView ? pView->GetDrawView() : NULL;
Window* pWindow = pView ? pView->GetWrtShell().GetWin() : NULL;
OSL_ENSURE( pFormShell && pDrawView && pWindow, "SwXTextView::ExecMoveMisc: no chance!" );
if ( !pFormShell || !pDrawView || !pWindow )
break;
boost::scoped_ptr< ::svx::ISdrObjectFilter > pFilter( pFormShell->CreateFocusableControlFilter(
*pDrawView, *pWindow ) );
if ( !pFilter.get() )
break;
const SdrObject* pNearestControl = rSh.GetBestObject( true, GOTOOBJ_DRAW_CONTROL, false, pFilter.get() );
if ( !pNearestControl )
break;
const SdrUnoObj* pUnoObject = dynamic_cast< const SdrUnoObj* >( pNearestControl );
OSL_ENSURE( pUnoObject, "SwTextShell::ExecMoveMisc: GetBestObject returned nonsense!" );
if ( !pUnoObject )
break;
pFormShell->ToggleControlFocus( *pUnoObject, *pDrawView, *pWindow );
}
break;
case FN_CNTNT_TO_NEXT_FRAME:
bRet = rSh.GotoObj(true, GOTOOBJ_GOTO_ANY);
if(bRet)
{
rSh.HideCrsr();
rSh.EnterSelFrmMode();
}
break;
case FN_NEXT_FOOTNOTE:
rSh.MoveCrsr();
bRet = rSh.GotoNextFtnAnchor();
break;
case FN_PREV_FOOTNOTE:
rSh.MoveCrsr();
bRet = rSh.GotoPrevFtnAnchor();
break;
case FN_TO_HEADER:
rSh.MoveCrsr();
if ( ( FRMTYPE_HEADER & rSh.GetFrmType(0,false) ) || rSh.GotoHeaderTxt() )
rSh.SttPg();
bSetRetVal = false;
break;
case FN_TO_FOOTER:
rSh.MoveCrsr();
if ( ( FRMTYPE_FOOTER & rSh.GetFrmType(0,false) ) || rSh.GotoFooterTxt() )
rSh.EndPg();
bSetRetVal = false;
break;
case FN_FOOTNOTE_TO_ANCHOR:
rSh.MoveCrsr();
if ( FRMTYPE_FOOTNOTE & rSh.GetFrmType(0,false) )
rSh.GotoFtnAnchor();
else
rSh.GotoFtnTxt();
bSetRetVal = false;
break;
case FN_TO_FOOTNOTE_AREA :
rSh.GotoFtnTxt();
break;
case FN_PREV_TABLE:
bRet = rSh.MoveTable( fnTablePrev, fnTableStart);
break;
case FN_NEXT_TABLE:
bRet = rSh.MoveTable(fnTableNext, fnTableStart);
break;
case FN_GOTO_NEXT_REGION :
bRet = rSh.MoveRegion(fnRegionNext, fnRegionStart);
break;
case FN_GOTO_PREV_REGION :
bRet = rSh.MoveRegion(fnRegionPrev, fnRegionStart);
break;
case FN_NEXT_TOXMARK:
bRet = rSh.GotoNxtPrvTOXMark( true );
break;
case FN_PREV_TOXMARK:
bRet = rSh.GotoNxtPrvTOXMark( false );
break;
case FN_NEXT_TBLFML:
bRet = rSh.GotoNxtPrvTblFormula( true, false );
break;
case FN_PREV_TBLFML:
bRet = rSh.GotoNxtPrvTblFormula( false, false );
break;
case FN_NEXT_TBLFML_ERR:
bRet = rSh.GotoNxtPrvTblFormula( true, true );
break;
case FN_PREV_TBLFML_ERR:
bRet = rSh.GotoNxtPrvTblFormula( false, true );
break;
default:
OSL_FAIL("wrong dispatcher");
return;
}
if( bSetRetVal )
rReq.SetReturnValue(SfxBoolItem( nSlot, bRet ));
rReq.Done();
bool bInHeader = true;
if ( rSh.IsInHeaderFooter( &bInHeader ) )
{
if ( !bInHeader )
{
rSh.SetShowHeaderFooterSeparator( Footer, true );
rSh.SetShowHeaderFooterSeparator( Header, false );
}
else
{
rSh.SetShowHeaderFooterSeparator( Header, true );
rSh.SetShowHeaderFooterSeparator( Footer, false );
}
// Force repaint
rSh.GetWin()->Invalidate();
}
if ( rSh.IsInHeaderFooter() != rSh.IsHeaderFooterEdit() )
rSh.ToggleHeaderFooterEdit();
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <stdlib.h>
#include "Transcoder.hpp"
XERCES_CPP_NAMESPACE_USE
static bool DEBUG_IN = false;
static bool DEBUG_OUT = false;
Transcoder* Transcoder::_instance = NULL;
Transcoder*
Transcoder::getInstance() {
// fprintf(stderr, "getInstance: finding instance\n");
if (_instance == NULL) {
// fprintf(stderr, "getInstance: making new transcoder\n");
_instance = new Transcoder();
}
return _instance;
}
Transcoder::~Transcoder() {
// fprintf(stderr, "Deleting transcoder\n");
}
Transcoder::Transcoder() {
XMLTransService::Codes failReason;
// we assume that the Xerces-C transcoding service is already initialized
// via XMLPlatformUtils::Initialize()
UTF8_TRANSCODER = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(
XMLUni::fgUTF8EncodingString,
failReason,
1024);
if (UTF8_TRANSCODER == NULL) {
croak("ERROR: Transcoder Could not create UTF-8 transcoder");
} else if (failReason == XMLTransService::UnsupportedEncoding) {
croak("ERROR: Transcoder: unsupported encoding");
} else if (failReason == XMLTransService::InternalFailure) {
croak("ERROR: Transcoder: internal failure");
} else if (failReason == XMLTransService::SupportFilesNotFound) {
croak("ERROR: Transcoder: support files not found");
} else if (failReason == XMLTransService::Ok) {
// fprintf(stderr, "Created transcoder ok\n");
}
}
SV*
Transcoder::XMLString2Local(const XMLCh* input) {
if (input == NULL) {
return &PL_sv_undef;
}
SV *output;
unsigned int charsEaten = 0;
int length = XMLString::stringLen(input); // string length
// use +1 to make room for the '\0' at the end of the string
// in the pathological case when each character of the string
// is UTF8_MAXLEN bytes long
XMLByte* res = new XMLByte[(length * UTF8_MAXLEN) + 1]; // output string
unsigned int total_chars =
UTF8_TRANSCODER->transcodeTo((const XMLCh*) input,
(unsigned int) length,
(XMLByte*) res,
(unsigned int) (length*UTF8_MAXLEN),
charsEaten,
XMLTranscoder::UnRep_Throw
);
res[total_chars] = '\0';
#if (0)
if (DEBUG_OUT) {
printf("Xerces out length = %d: ",total_chars);
for (int i=0;i<length;i++){
printf("<0x%.4X>",res[i]);
}
printf("\n");
}
#endif
output = sv_newmortal();
sv_setpv((SV*)output, (char *)res );
SvUTF8_on((SV*)output);
delete[] res;
return output;
}
XMLCh*
Transcoder::Local2XMLString(SV* input){
if (input == &PL_sv_undef) {
return NULL;
}
XMLCh* output;
STRLEN length;
char *ptr = (char *)SvPVutf8(input,length);
#if (0)
if (DEBUG_IN) {
printf("Perl in length = %d: ",length);
for (unsigned int i=0;i<length;i++){
printf("<0x%.4X>",ptr[i]);
}
printf("\n");
}
#endif
if (SvUTF8(input)) {
unsigned int charsEaten = 0;
unsigned char* sizes = new unsigned char[length+1];
output = new XMLCh[length+1];
unsigned int chars_stored =
UTF8_TRANSCODER->transcodeFrom((const XMLByte*) ptr,
(unsigned int) length,
(XMLCh*) output,
(unsigned int) length,
charsEaten,
(unsigned char*)sizes
);
delete [] sizes;
#if (0)
if (DEBUG_IN) {
printf("Xerces in length = %d: ",chars_stored);
for (unsigned int i=0;i<chars_stored;i++){
printf("<0x%.4X>",output[i]);
}
printf("\n");
}
#endif
// indicate the end of the string
output[chars_stored] = '\0';
} else {
output = XMLString::transcode(ptr);
#if (0)
if (DEBUG_IN) {
printf("Xerces: ");
for (int i=0;output[i];i++){
printf("<0x%.4X>",output[i]);
}
printf("\n");
}
#endif
}
return(output);
}
<commit_msg>64 bit compile issues: unsigned int -> XMLSize_t<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 <stdlib.h>
#include "Transcoder.hpp"
XERCES_CPP_NAMESPACE_USE
static bool DEBUG_IN = false;
static bool DEBUG_OUT = false;
Transcoder* Transcoder::_instance = NULL;
Transcoder*
Transcoder::getInstance() {
// fprintf(stderr, "getInstance: finding instance\n");
if (_instance == NULL) {
// fprintf(stderr, "getInstance: making new transcoder\n");
_instance = new Transcoder();
}
return _instance;
}
Transcoder::~Transcoder() {
// fprintf(stderr, "Deleting transcoder\n");
}
Transcoder::Transcoder() {
XMLTransService::Codes failReason;
// we assume that the Xerces-C transcoding service is already initialized
// via XMLPlatformUtils::Initialize()
UTF8_TRANSCODER = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(
XMLUni::fgUTF8EncodingString,
failReason,
1024);
if (UTF8_TRANSCODER == NULL) {
croak("ERROR: Transcoder Could not create UTF-8 transcoder");
} else if (failReason == XMLTransService::UnsupportedEncoding) {
croak("ERROR: Transcoder: unsupported encoding");
} else if (failReason == XMLTransService::InternalFailure) {
croak("ERROR: Transcoder: internal failure");
} else if (failReason == XMLTransService::SupportFilesNotFound) {
croak("ERROR: Transcoder: support files not found");
} else if (failReason == XMLTransService::Ok) {
// fprintf(stderr, "Created transcoder ok\n");
}
}
SV*
Transcoder::XMLString2Local(const XMLCh* input) {
if (input == NULL) {
return &PL_sv_undef;
}
SV *output;
XMLSize_t charsEaten = 0;
int length = XMLString::stringLen(input); // string length
// use +1 to make room for the '\0' at the end of the string
// in the pathological case when each character of the string
// is UTF8_MAXLEN bytes long
XMLByte* res = new XMLByte[(length * UTF8_MAXLEN) + 1]; // output string
XMLSize_t total_chars =
UTF8_TRANSCODER->transcodeTo((const XMLCh*) input,
(XMLSize_t) length,
(XMLByte*) res,
(XMLSize_t) (length*UTF8_MAXLEN),
charsEaten,
XMLTranscoder::UnRep_Throw
);
res[total_chars] = '\0';
#if (0)
if (DEBUG_OUT) {
printf("Xerces out length = %d: ",total_chars);
for (int i=0;i<length;i++){
printf("<0x%.4X>",res[i]);
}
printf("\n");
}
#endif
output = sv_newmortal();
sv_setpv((SV*)output, (char *)res );
SvUTF8_on((SV*)output);
delete[] res;
return output;
}
XMLCh*
Transcoder::Local2XMLString(SV* input){
if (input == &PL_sv_undef) {
return NULL;
}
XMLCh* output;
STRLEN length;
char *ptr = (char *)SvPVutf8(input,length);
#if (0)
if (DEBUG_IN) {
printf("Perl in length = %d: ",length);
for (unsigned int i=0;i<length;i++){
printf("<0x%.4X>",ptr[i]);
}
printf("\n");
}
#endif
if (SvUTF8(input)) {
XMLSize_t charsEaten = 0;
unsigned char* sizes = new unsigned char[length+1];
output = new XMLCh[length+1];
XMLSize_t chars_stored =
UTF8_TRANSCODER->transcodeFrom((const XMLByte*) ptr,
(XMLSize_t) length,
(XMLCh*) output,
(XMLSize_t) length,
charsEaten,
(unsigned char*)sizes
);
delete [] sizes;
#if (0)
if (DEBUG_IN) {
printf("Xerces in length = %d: ",chars_stored);
for (unsigned int i=0;i<chars_stored;i++){
printf("<0x%.4X>",output[i]);
}
printf("\n");
}
#endif
// indicate the end of the string
output[chars_stored] = '\0';
} else {
output = XMLString::transcode(ptr);
#if (0)
if (DEBUG_IN) {
printf("Xerces: ");
for (int i=0;output[i];i++){
printf("<0x%.4X>",output[i]);
}
printf("\n");
}
#endif
}
return(output);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2013 Baxter, Lovell, Mangsingkha, Saeedi
*
* 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 <iostream>
//
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
//
#include "State.h"
#include "utils.h"
#include "constants.h"
//
typedef boost::numeric::ublas::matrix<double> matrixD;
using namespace std;
int n_iterations = 10;
string filename = "dha_small_cont_no_header.csv";
// tail -n +2 ../../www/data/dha_small_cont.csv > dha_small_cont_no_header.csv
// passing in a State is dangerous, if you don't pass in a reference, memory will be deallocated
// and bugs/segfaults will occur
void print_state_summary(const State &s) {
cout << "s.num_views: " << s.get_num_views() << endl;
for(int j=0;j<s.get_num_views(); j++) {
cout << "view " << j;
cout << " row_paritition_model_counts: " << s.get_row_partition_model_counts_i(j) << endl;
}
cout << "s.column_crp_score: " << s.get_column_crp_score();
cout << "; s.data_score: " << s.get_data_score();
cout << "; s.score: " << s.get_marginal_logp();
cout << endl;
return;
}
int main(int argc, char** argv) {
cout << endl << "test_state: Hello World!" << endl;
// load some data
matrixD data;
LoadData(filename, data);
cout << "data is: " << data << endl;
int num_rows = data.size1();
int num_cols = data.size2();
// create the objects to test
vector<int> global_row_indices = create_sequence(data.size1());
vector<int> global_column_indices = create_sequence(data.size2());
vector<string> global_col_types;
vector<int> global_col_multinomial_counts;
for(int i=0; i<global_column_indices.size(); i++) {
global_col_types.push_back(CONTINUOUS_DATATYPE);
global_col_multinomial_counts.push_back(0);
}
State s = State(data, global_col_types,
global_col_multinomial_counts,
global_row_indices,
global_column_indices);
cout << "start X_D" << endl << s.get_X_D() << endl;
cout << "State:" << endl << s << endl;
vector<int> empty_int_v;
for(int i=0; i<n_iterations; i++) {
cout << "transition #: " << i << endl;
s.transition_column_crp_alpha();
s.transition_column_hyperparameters(empty_int_v);
s.transition_row_partition_hyperparameters(empty_int_v);
s.transition_features(data, empty_int_v);
s.transition_row_partition_assignments(data, empty_int_v);
// s.transition(data);
print_state_summary(s);
}
cout << "FINAL STATE" << endl;
cout << s << endl;
cout << "end X_D" << endl << s.get_X_D() << endl;
cout << endl << "test_state: Goodbye World!" << endl;
}
<commit_msg>use different data filename; dont print State at start and end<commit_after>/*
* Copyright 2013 Baxter, Lovell, Mangsingkha, Saeedi
*
* 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 <iostream>
//
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
//
#include "State.h"
#include "utils.h"
#include "constants.h"
//
typedef boost::numeric::ublas::matrix<double> matrixD;
using namespace std;
int n_iterations = 10;
string filename = "T.csv";
// passing in a State is dangerous, if you don't pass in a reference, memory will be deallocated
// and bugs/segfaults will occur
void print_state_summary(const State &s) {
cout << "s.num_views: " << s.get_num_views() << endl;
for(int j=0;j<s.get_num_views(); j++) {
cout << "view " << j;
cout << " row_paritition_model_counts: " << s.get_row_partition_model_counts_i(j) << endl;
}
cout << "s.column_crp_score: " << s.get_column_crp_score();
cout << "; s.data_score: " << s.get_data_score();
cout << "; s.score: " << s.get_marginal_logp();
cout << endl;
return;
}
int main(int argc, char** argv) {
cout << endl << "test_state: Hello World!" << endl;
// load some data
matrixD data;
LoadData(filename, data);
cout << "data is: " << data << endl;
int num_rows = data.size1();
int num_cols = data.size2();
// create the objects to test
vector<int> global_row_indices = create_sequence(data.size1());
vector<int> global_column_indices = create_sequence(data.size2());
vector<string> global_col_types;
vector<int> global_col_multinomial_counts;
for(int i=0; i<global_column_indices.size(); i++) {
global_col_types.push_back(CONTINUOUS_DATATYPE);
global_col_multinomial_counts.push_back(0);
}
State s = State(data, global_col_types,
global_col_multinomial_counts,
global_row_indices,
global_column_indices);
cout << "start X_D" << endl << s.get_X_D() << endl;
// cout << "State:" << endl << s << endl;
vector<int> empty_int_v;
for(int i=0; i<n_iterations; i++) {
cout << "transition #: " << i << endl;
s.transition_column_crp_alpha();
s.transition_column_hyperparameters(empty_int_v);
s.transition_row_partition_hyperparameters(empty_int_v);
s.transition_features(data, empty_int_v);
s.transition_row_partition_assignments(data, empty_int_v);
// s.transition(data);
print_state_summary(s);
}
// cout << "FINAL STATE" << endl;
// cout << s << endl;
cout << "end X_D" << endl << s.get_X_D() << endl;
cout << endl << "test_state: Goodbye World!" << endl;
}
<|endoftext|> |
<commit_before>/* main.cpp, lmu2png main file.
Copyright (C) 2016 EasyRPG Project <https://github.com/EasyRPG/>.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
// Headers
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <SDL_image.h>
#include <ldb_reader.h>
#include <lmu_reader.h>
#include <reader_lcf.h>
#include <rpg_map.h>
#include <data.h>
#include "chipset.h"
#include "sdlxyz.h"
// prevent SDL main rename
#undef main
const std::string usage = R"(Usage: lmu2png map.lmu [options]
Options:
-d database.ldb
-c chipset.png
-e encoding
-o output.png
--no-background
--no-lowertiles
--no-uppertiles
--no-events
)";
std::string GetFileDirectory (const std::string& file) {
size_t found = file.find_last_of("/\\");
return found == std::string::npos ? "./" : file.substr(0,found + 1);
}
bool Exists(const std::string& filename) {
std::ifstream infile(filename.c_str());
return infile.good();
}
std::string path;
std::string FindResource(const std::string& folder, const std::string& base_name) {
static const std::vector<std::string> dirs = [] {
char* rtp2k_ptr = getenv("RPG2K_RTP_PATH");
char* rtp2k3_ptr = getenv("RPG2K3_RTP_PATH");
std::vector<std::string> dirs = {path};
if (rtp2k_ptr)
dirs.emplace_back(rtp2k_ptr);
if (rtp2k3_ptr)
dirs.emplace_back(rtp2k3_ptr);
return dirs;
}();
for (const auto& dir : dirs) {
for (const auto& ext : {".png", ".bmp", ".xyz"}) {
if (Exists(dir + "/" + folder + "/" + base_name + ext))
return dir + "/" + folder + "/" + base_name + ext;
}
}
return "";
}
SDL_Surface* LoadImage(const char* image_path, bool transparent = false) {
// Try XYZ, then IMG_Load
SDL_Surface* image = LoadImageXYZ(image_path);
if (!image) {
image = IMG_Load(image_path);
}
if (!image) {
std::cout << IMG_GetError() << std::endl;
exit(EXIT_FAILURE);
}
if (transparent && image->format->palette) {
// Set as color key the first color in the palette
SDL_SetColorKey(image, SDL_TRUE, 0);
}
return image;
}
void DrawTiles(SDL_Surface* output_img, stChipset * gen, uint8_t * csflag, std::unique_ptr<RPG::Map> & map, int show_lowertiles, int show_uppertiles, int flaglayer) {
for (int y = 0; y < map->height; ++y) {
for (int x = 0; x < map->width; ++x) {
// Different logic between these.
int tindex = x + y * map->width;
if (show_lowertiles) {
uint16_t tid = map->lower_layer[tindex];
int l = (csflag[tid] & 0x30) ? 1 : 0;
if (l == flaglayer)
gen->RenderTile(output_img, x*16, y*16, map->lower_layer[x+y*map->width], 0);
}
if (show_uppertiles) {
uint16_t tid = map->upper_layer[tindex];
int l = (csflag[tid] & 0x10) ? 1 : 0;
if (l == flaglayer)
gen->RenderTile(output_img, x*16, y*16, map->upper_layer[x+y*map->width], 0);
}
}
}
}
void DrawEvents(SDL_Surface* output_img, stChipset * gen, std::unique_ptr<RPG::Map> & map, int layer) {
for (const RPG::Event& ev : map->events) {
const RPG::EventPage* evp = nullptr;
// Find highest page without conditions
for (int i = 0; i < (int)ev.pages.size(); ++i) {
const auto& flg = ev.pages[i].condition.flags;
if (flg.switch_a || flg.switch_b || flg.variable || flg.item || flg.actor || flg.timer || flg.timer2)
continue;
evp = &ev.pages[i];
}
if (!evp)
continue;
// Event layering
if (evp->layer >= 0 && evp->layer < 3 && evp->layer != layer)
continue;
if (evp->character_name.empty())
gen->RenderTile(output_img, (ev.x)*16, (ev.y)*16, 0x2710 + evp->character_index, 0);
else {
std::string charset(FindResource("CharSet", evp->character_name));
if (charset.empty()) {
std::cout << "Can't find charset " << evp->character_name << std::endl;
continue;
}
SDL_Surface* charset_img(LoadImage(charset.c_str(), true));
SDL_Rect src_rect {(evp->character_index % 4) * 72 + evp->character_pattern * 24,
(evp->character_index / 4) * 128 + evp->character_direction * 32, 24, 32};
SDL_Rect dst_rect {ev.x * 16 - 4, ev.y * 16 - 16, 16, 32}; // Why -4 and -16?
SDL_BlitSurface(charset_img, &src_rect, output_img, &dst_rect);
}
}
}
void RenderCore(SDL_Surface* output_img, std::string chipset, uint8_t * csflag, std::unique_ptr<RPG::Map> & map, int show_background, int show_lowertiles, int show_uppertiles, int show_events) {
SDL_Surface* chipset_img = LoadImage(chipset.c_str(), true);
stChipset gen;
gen.GenerateFromSurface(chipset_img);
// Draw parallax background
if (show_background && !map->parallax_name.empty()) {
std::string background(FindResource("Panorama", map->parallax_name));
if (background.empty()) {
std::cout << "Can't find parallax background " << map->parallax_name << std::endl;
} else {
SDL_Surface* background_img(LoadImage(background.c_str()));
SDL_Rect dst_rect = background_img->clip_rect;
// Fill screen with copies of the background
for (dst_rect.x = 0; dst_rect.x < output_img->w; dst_rect.x += background_img->w) {
for (dst_rect.y = 0; dst_rect.y < output_img->h; dst_rect.y += background_img->h) {
SDL_BlitSurface(background_img, nullptr, output_img, &dst_rect);
}
}
}
}
// Draw below tile layer
if (show_lowertiles || show_uppertiles)
DrawTiles(output_img, &gen, csflag, map, show_lowertiles, show_uppertiles, 0);
// Draw below-player & player-level events
if (show_events) {
DrawEvents(output_img, &gen, map, 0);
DrawEvents(output_img, &gen, map, 1);
}
// Draw above tile layer
if (show_lowertiles || show_uppertiles)
DrawTiles(output_img, &gen, csflag, map, show_lowertiles, show_uppertiles, 1);
// Draw events
if (show_events)
DrawEvents(output_img, &gen, map, 2);
}
bool MapEventYSort(const RPG::Event& ev1, const RPG::Event& ev2) {
return ev1.y < ev2.y;
}
int main(int argc, char** argv) {
std::string database;
std::string chipset;
std::string encoding;
std::string output;
std::string input;
bool show_background = true;
bool show_lowertiles = true;
bool show_uppertiles = true;
bool show_events = true;
// ChipSet flags
uint8_t csflag[65536];
memset(csflag, 0, 65536);
// Parse arguments
for (int i = 1; i < argc; ++i) {
std::string arg (argv[i]);
if (arg == "-h" || arg == "--help") {
std::cout << usage << std::endl;
exit(EXIT_SUCCESS);
} else if (arg == "-d") {
if (++i < argc)
database = argv[i];
} else if (arg == "-c") {
if (++i < argc)
chipset = argv[i];
} else if (arg == "-e") {
if (++i < argc)
encoding = argv[i];
} else if (arg == "-o") {
if (++i < argc)
output = argv[i];
} else if (arg == "--no-background") {
show_background = false;
} else if (arg == "--no-lowertiles") {
show_lowertiles = false;
} else if (arg == "--no-uppertiles") {
show_uppertiles = false;
} else if (arg == "--no-events") {
show_events = false;
} else {
input = arg;
}
}
if (input.empty()) {
std::cout << usage << std::endl;
exit(EXIT_FAILURE);
}
if (!Exists(input)) {
std::cout << "Input map file " << input << " can't be found." << std::endl;
exit(EXIT_FAILURE);
}
path = GetFileDirectory(input);
if (encoding.empty())
encoding = ReaderUtil::GetEncoding(path + "RPG_RT.ini");
std::unique_ptr<RPG::Map> map(LMU_Reader::Load(input, encoding));
if (!map) {
std::cout << LcfReader::GetError() << std::endl;
exit(EXIT_FAILURE);
}
if (output.empty()) {
output = input.substr(0, input.length() - 3) + "png";
}
if (chipset.empty()) {
// Get chipset from database
if (database.empty())
database = path + "RPG_RT.ldb";
if (!LDB_Reader::Load(database, encoding)) {
std::cout << LcfReader::GetError() << std::endl;
exit(EXIT_FAILURE);
}
assert(map->chipset_id <= (int)Data::chipsets.size());
RPG::Chipset & cs = Data::chipsets[map->chipset_id - 1];
std::string chipset_base(cs.chipset_name);
chipset = FindResource("ChipSet", chipset_base);
if (chipset.empty()) {
std::cout << "Chipset " << chipset_base << " can't be found." << std::endl;
exit(EXIT_FAILURE);
}
// Load flags.
memset(csflag + 0, cs.passable_data_lower[0], 1000);
memset(csflag + 1000, cs.passable_data_lower[1], 1000);
memset(csflag + 2000, cs.passable_data_lower[2], 1000);
memset(csflag + 3000, cs.passable_data_lower[3], 50);
memset(csflag + 3050, cs.passable_data_lower[4], 50);
memset(csflag + 3100, cs.passable_data_lower[5], 900);
for (int i = 0; i < 12; i++)
memset(csflag + 4000 + (i * 50), cs.passable_data_lower[6 + i], 50);
for (int i = 0; i < 144; i++) {
csflag[5000 + i] = cs.passable_data_lower[18 + i];
csflag[10000 + i] = cs.passable_data_upper[i];
}
} else {
// Not doing chipset search, set defaults compatible with older lmu2png versions
memset(csflag + 10000, 0x10, 144);
}
SDL_Surface* output_img = SDL_CreateRGBSurface(0, map->width * 16, map->height * 16, 32, 0, 0, 0, 0);
if (!output_img) {
std::cout << "Unable to create output image." << std::endl;
exit(EXIT_FAILURE);
}
if (show_events) {
// Just do the Y-sort here. Yes, it modifies the data that's supposed to be rendered.
// Doesn't particularly matter. What does matter is that this has to be a stable_sort,
// so equivalent Y still causes ID order to be prioritized (just in case)
std::stable_sort(map->events.begin(), map->events.end(), MapEventYSort);
}
RenderCore(output_img, chipset, csflag, map, show_background, show_lowertiles, show_uppertiles, show_events);
if (IMG_SavePNG(output_img, output.c_str()) < 0) {
std::cout << IMG_GetError() << std::endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<commit_msg>Clean up lmu2png flag mappings.<commit_after>/* main.cpp, lmu2png main file.
Copyright (C) 2016 EasyRPG Project <https://github.com/EasyRPG/>.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
// Headers
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <SDL_image.h>
#include <ldb_reader.h>
#include <lmu_reader.h>
#include <reader_lcf.h>
#include <rpg_map.h>
#include <data.h>
#include "chipset.h"
#include "sdlxyz.h"
// prevent SDL main rename
#undef main
const std::string usage = R"(Usage: lmu2png map.lmu [options]
Options:
-d database.ldb
-c chipset.png
-e encoding
-o output.png
--no-background
--no-lowertiles
--no-uppertiles
--no-events
)";
std::string GetFileDirectory (const std::string& file) {
size_t found = file.find_last_of("/\\");
return found == std::string::npos ? "./" : file.substr(0,found + 1);
}
bool Exists(const std::string& filename) {
std::ifstream infile(filename.c_str());
return infile.good();
}
std::string path;
std::string FindResource(const std::string& folder, const std::string& base_name) {
static const std::vector<std::string> dirs = [] {
char* rtp2k_ptr = getenv("RPG2K_RTP_PATH");
char* rtp2k3_ptr = getenv("RPG2K3_RTP_PATH");
std::vector<std::string> dirs = {path};
if (rtp2k_ptr)
dirs.emplace_back(rtp2k_ptr);
if (rtp2k3_ptr)
dirs.emplace_back(rtp2k3_ptr);
return dirs;
}();
for (const auto& dir : dirs) {
for (const auto& ext : {".png", ".bmp", ".xyz"}) {
if (Exists(dir + "/" + folder + "/" + base_name + ext))
return dir + "/" + folder + "/" + base_name + ext;
}
}
return "";
}
SDL_Surface* LoadImage(const char* image_path, bool transparent = false) {
// Try XYZ, then IMG_Load
SDL_Surface* image = LoadImageXYZ(image_path);
if (!image) {
image = IMG_Load(image_path);
}
if (!image) {
std::cout << IMG_GetError() << std::endl;
exit(EXIT_FAILURE);
}
if (transparent && image->format->palette) {
// Set as color key the first color in the palette
SDL_SetColorKey(image, SDL_TRUE, 0);
}
return image;
}
void DrawTiles(SDL_Surface* output_img, stChipset * gen, uint8_t * csflag, std::unique_ptr<RPG::Map> & map, int show_lowertiles, int show_uppertiles, int flaglayer) {
for (int y = 0; y < map->height; ++y) {
for (int x = 0; x < map->width; ++x) {
// Different logic between these.
int tindex = x + y * map->width;
if (show_lowertiles) {
uint16_t tid = map->lower_layer[tindex];
int l = (csflag[tid] & 0x30) ? 1 : 0;
if (l == flaglayer)
gen->RenderTile(output_img, x*16, y*16, map->lower_layer[x+y*map->width], 0);
}
if (show_uppertiles) {
uint16_t tid = map->upper_layer[tindex];
int l = (csflag[tid] & 0x10) ? 1 : 0;
if (l == flaglayer)
gen->RenderTile(output_img, x*16, y*16, map->upper_layer[x+y*map->width], 0);
}
}
}
}
void DrawEvents(SDL_Surface* output_img, stChipset * gen, std::unique_ptr<RPG::Map> & map, int layer) {
for (const RPG::Event& ev : map->events) {
const RPG::EventPage* evp = nullptr;
// Find highest page without conditions
for (int i = 0; i < (int)ev.pages.size(); ++i) {
const auto& flg = ev.pages[i].condition.flags;
if (flg.switch_a || flg.switch_b || flg.variable || flg.item || flg.actor || flg.timer || flg.timer2)
continue;
evp = &ev.pages[i];
}
if (!evp)
continue;
// Event layering
if (evp->layer >= 0 && evp->layer < 3 && evp->layer != layer)
continue;
if (evp->character_name.empty())
gen->RenderTile(output_img, (ev.x)*16, (ev.y)*16, 0x2710 + evp->character_index, 0);
else {
std::string charset(FindResource("CharSet", evp->character_name));
if (charset.empty()) {
std::cout << "Can't find charset " << evp->character_name << std::endl;
continue;
}
SDL_Surface* charset_img(LoadImage(charset.c_str(), true));
SDL_Rect src_rect {(evp->character_index % 4) * 72 + evp->character_pattern * 24,
(evp->character_index / 4) * 128 + evp->character_direction * 32, 24, 32};
SDL_Rect dst_rect {ev.x * 16 - 4, ev.y * 16 - 16, 16, 32}; // Why -4 and -16?
SDL_BlitSurface(charset_img, &src_rect, output_img, &dst_rect);
}
}
}
void RenderCore(SDL_Surface* output_img, std::string chipset, uint8_t * csflag, std::unique_ptr<RPG::Map> & map, int show_background, int show_lowertiles, int show_uppertiles, int show_events) {
SDL_Surface* chipset_img = LoadImage(chipset.c_str(), true);
stChipset gen;
gen.GenerateFromSurface(chipset_img);
// Draw parallax background
if (show_background && !map->parallax_name.empty()) {
std::string background(FindResource("Panorama", map->parallax_name));
if (background.empty()) {
std::cout << "Can't find parallax background " << map->parallax_name << std::endl;
} else {
SDL_Surface* background_img(LoadImage(background.c_str()));
SDL_Rect dst_rect = background_img->clip_rect;
// Fill screen with copies of the background
for (dst_rect.x = 0; dst_rect.x < output_img->w; dst_rect.x += background_img->w) {
for (dst_rect.y = 0; dst_rect.y < output_img->h; dst_rect.y += background_img->h) {
SDL_BlitSurface(background_img, nullptr, output_img, &dst_rect);
}
}
}
}
// Draw below tile layer
if (show_lowertiles || show_uppertiles)
DrawTiles(output_img, &gen, csflag, map, show_lowertiles, show_uppertiles, 0);
// Draw below-player & player-level events
if (show_events) {
DrawEvents(output_img, &gen, map, 0);
DrawEvents(output_img, &gen, map, 1);
}
// Draw above tile layer
if (show_lowertiles || show_uppertiles)
DrawTiles(output_img, &gen, csflag, map, show_lowertiles, show_uppertiles, 1);
// Draw events
if (show_events)
DrawEvents(output_img, &gen, map, 2);
}
bool MapEventYSort(const RPG::Event& ev1, const RPG::Event& ev2) {
return ev1.y < ev2.y;
}
int main(int argc, char** argv) {
std::string database;
std::string chipset;
std::string encoding;
std::string output;
std::string input;
bool show_background = true;
bool show_lowertiles = true;
bool show_uppertiles = true;
bool show_events = true;
// ChipSet flags
uint8_t csflag[65536];
memset(csflag, 0, 65536);
// Parse arguments
for (int i = 1; i < argc; ++i) {
std::string arg (argv[i]);
if (arg == "-h" || arg == "--help") {
std::cout << usage << std::endl;
exit(EXIT_SUCCESS);
} else if (arg == "-d") {
if (++i < argc)
database = argv[i];
} else if (arg == "-c") {
if (++i < argc)
chipset = argv[i];
} else if (arg == "-e") {
if (++i < argc)
encoding = argv[i];
} else if (arg == "-o") {
if (++i < argc)
output = argv[i];
} else if (arg == "--no-background") {
show_background = false;
} else if (arg == "--no-lowertiles") {
show_lowertiles = false;
} else if (arg == "--no-uppertiles") {
show_uppertiles = false;
} else if (arg == "--no-events") {
show_events = false;
} else {
input = arg;
}
}
if (input.empty()) {
std::cout << usage << std::endl;
exit(EXIT_FAILURE);
}
if (!Exists(input)) {
std::cout << "Input map file " << input << " can't be found." << std::endl;
exit(EXIT_FAILURE);
}
path = GetFileDirectory(input);
if (encoding.empty())
encoding = ReaderUtil::GetEncoding(path + "RPG_RT.ini");
std::unique_ptr<RPG::Map> map(LMU_Reader::Load(input, encoding));
if (!map) {
std::cout << LcfReader::GetError() << std::endl;
exit(EXIT_FAILURE);
}
if (output.empty()) {
output = input.substr(0, input.length() - 3) + "png";
}
if (chipset.empty()) {
// Get chipset from database
if (database.empty())
database = path + "RPG_RT.ldb";
if (!LDB_Reader::Load(database, encoding)) {
std::cout << LcfReader::GetError() << std::endl;
exit(EXIT_FAILURE);
}
assert(map->chipset_id <= (int)Data::chipsets.size());
RPG::Chipset & cs = Data::chipsets[map->chipset_id - 1];
std::string chipset_base(cs.chipset_name);
chipset = FindResource("ChipSet", chipset_base);
if (chipset.empty()) {
std::cout << "Chipset " << chipset_base << " can't be found." << std::endl;
exit(EXIT_FAILURE);
}
// Load flags.
// The first 18 in lower cover various zones.
// Water A/B/C
for (int i = 0; i < 3; i++)
memset(csflag + (1000 * i), cs.passable_data_lower[i], 1000);
// Animated tiles, made up of 3 sets of 50.
for (int i = 0; i < 3; i++)
memset(csflag + 3000 + (i * 50), cs.passable_data_lower[3 + i], 50);
// Terrain ATs, made up of 12 sets of 50.
for (int i = 0; i < 12; i++)
memset(csflag + 4000 + (i * 50), cs.passable_data_lower[6 + i], 50);
// Lower/upper 144-tile pages, made up of 144 individual flag bytes per page.
for (int i = 0; i < 144; i++) {
csflag[5000 + i] = cs.passable_data_lower[18 + i];
csflag[10000 + i] = cs.passable_data_upper[i];
}
} else {
// Not doing chipset search, set defaults compatible with older lmu2png versions
memset(csflag + 10000, 0x10, 144);
}
SDL_Surface* output_img = SDL_CreateRGBSurface(0, map->width * 16, map->height * 16, 32, 0, 0, 0, 0);
if (!output_img) {
std::cout << "Unable to create output image." << std::endl;
exit(EXIT_FAILURE);
}
if (show_events) {
// Just do the Y-sort here. Yes, it modifies the data that's supposed to be rendered.
// Doesn't particularly matter. What does matter is that this has to be a stable_sort,
// so equivalent Y still causes ID order to be prioritized (just in case)
std::stable_sort(map->events.begin(), map->events.end(), MapEventYSort);
}
RenderCore(output_img, chipset, csflag, map, show_background, show_lowertiles, show_uppertiles, show_events);
if (IMG_SavePNG(output_img, output.c_str()) < 0) {
std::cout << IMG_GetError() << std::endl;
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>/* ============================================================================
* Copyright (c) 2011 Michael A. Jackson (BlueQuartz Software)
* Copyright (c) 2011 Singanallur Venkatakrishnan (Purdue University)
* 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 Singanallur Venkatakrishnan, Michael A. Jackson, the Pudue
* Univeristy, BlueQuartz Software 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.
*
* This code was written under United States Air Force Contract number
* FA8650-07-D-5800
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "MRCSinogramInitializer.h"
#include "TomoEngine/Common/allocate.h"
#include "TomoEngine/IO/MRCHeader.h"
#include "TomoEngine/IO/MRCReader.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MRCSinogramInitializer::MRCSinogramInitializer()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MRCSinogramInitializer::~MRCSinogramInitializer()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void MRCSinogramInitializer::execute()
{
std::stringstream ss;
SinogramPtr sinogram = getSinogram();
TomoInputsPtr inputs = getTomoInputs();
// int16_t i,j,k;
// uint16_t TotalNumMaskedViews;
Real_t sum=0;
MRCReader::Pointer reader = MRCReader::New(true);
MRCHeader header;
int err = reader->readHeader(inputs->sinoFile, &header);
//reader->printHeader(&header, std::cout);
if (err < 0)
{
FREE_FEI_HEADERS( header.feiHeaders )
}
if (header.mode != 1)
{
FREE_FEI_HEADERS( header.feiHeaders )
ss << "16 bit integers are only supported. Error at line " << __LINE__ << " in file " << __FILE__ << std::endl;
setErrorCondition(-1);
notify(ss.str(), 0, Observable::UpdateErrorMessage);
return;
}
int voxelMin[3] = {0, 0, 0};
int voxelMax[3] = {header.nx-1, header.ny-1, header.nz-1};
inputs->fileXSize = header.nx;
inputs->fileYSize = header.ny;
inputs->fileZSize = header.nz;
Real_t CenterOfRot = header.nx/2;
ss.str("");
ss << "Center of rotation in this data set is " << CenterOfRot << std::endl;
if (inputs->useSubvolume == true)
{
voxelMin[0] = inputs->xStart;
voxelMin[1] = inputs->yStart;
voxelMin[2] = inputs->zStart;
voxelMax[0] = inputs->xEnd;
voxelMax[1] = inputs->yEnd;
voxelMax[2] = inputs->zEnd;
//Code to ensure region selected has the "right" dimensions
/************************************************************/
Real_t LeftLength = CenterOfRot - voxelMin[0];
Real_t RightLength = voxelMax[0] - CenterOfRot + 1; //1 is present to account for indexing of subvolume which starts from 0
if(LeftLength < 0)
{
voxelMin[0] = CenterOfRot + LeftLength;
inputs->xStart = voxelMin[0];
LeftLength *= -1;
}
if(RightLength < 0)
{
voxelMax[0] = CenterOfRot - RightLength;
inputs->xEnd = voxelMax[0];
RightLength *= -1;
}
if(LeftLength != RightLength)
{
ss << "The subvolume is not symmetric about the center. Adjusting.." << std::endl;
if(LeftLength < RightLength)
{
Real_t tempx = CenterOfRot + LeftLength - 1;
//Make sure the adjustment does not overrun the size of the data
if(tempx >= header.nx) tempx = header.nx - 1;
voxelMax[0] = tempx;
inputs->xEnd = voxelMax[0];
ss << "New xEnd : " << voxelMax[0] << std::endl;
}
else
{
Real_t tempx = CenterOfRot - RightLength;
//Make sure the adjustment does not overrun the size of the data
if(tempx < 0) tempx = 0;
voxelMin[0] = tempx;
inputs->xStart = voxelMin[0];
ss << "New xStart : " << voxelMin[0] << std::endl;
}
}
//This part of selecting y can be ignored if the user has selected
//single slice mode
//Adjusting the volume along the y-directions so we dont have
// issues with pixelation
ss <<"Current y ROI: "<< "yStart=" << inputs->yStart << " " << "yEnd=" << inputs->yEnd << std::endl;
int16_t disty = inputs->yEnd - inputs->yStart + 1;
ss << "Interpolate Factor=" << inputs->interpolateFactor << std::endl;
//3*iterpFactor is to account for the prior which operates on
//26 point 3-D neighborhood which needs 3 x-z slices at the least
int16_t rem_temp = disty % ((int16_t)inputs->interpolateFactor * 3);
if(rem_temp != 0)
{
ss << "The number of y-pixels is not a proper multiple for multi-res" << std::endl;
int16_t remainder = static_cast<int16_t>((inputs->interpolateFactor * 3) - (rem_temp));
//Make sure the adjustment does not overrun the size of the data
if(inputs->yEnd + remainder < header.ny) inputs->yEnd += remainder;
else
{
inputs->yEnd = header.ny - 1;
}
ss << "New yEnd " << inputs->yEnd << std::endl;
}
voxelMax[1] = inputs->yEnd;
ss << "xStart=" << inputs->xStart << " " << "xEnd=" << inputs->xEnd << std::endl;
ss << "yStart=" << inputs->yStart << " " << "yEnd=" << inputs->yEnd << std::endl;
/************************************************************/
}
else
{
inputs->xStart = 0;
inputs->yStart = 0;
inputs->zStart = 0;
inputs->xEnd = header.nx - 1;
inputs->yEnd = header.ny - 1;
inputs->zEnd = header.nz - 1;
}
sinogram->N_r = voxelMax[0] - voxelMin[0] + 1;
sinogram->N_t = voxelMax[1] - voxelMin[1] + 1;
sinogram->delta_r = 1.0;
sinogram->delta_t = 1.0;
FEIHeader* feiHeaders = header.feiHeaders;
if (feiHeaders != NULL)
{
sinogram->delta_r = feiHeaders[0].pixelsize * 1.0e9;
sinogram->delta_t = feiHeaders[0].pixelsize * 1.0e9;
}
// Clear out the vector as we are going to build it up
inputs->goodViews.resize(0,0);
int jStart = 0;
bool addToGoodView = false;
for (int i = voxelMin[2]; i <= voxelMax[2]; ++i )
{
addToGoodView = true;
for(size_t j = jStart; j < inputs->excludedViews.size(); ++j)
{
if (inputs->excludedViews[j] == i)
{
addToGoodView = false;
}
}
if (addToGoodView == true)
{
// std::cout << "Adding View Index: " << i << " To goodViews vector" << std::endl;
inputs->goodViews.push_back(i);
}
}
// The number of views is the size of the vector
sinogram->N_theta = inputs->goodViews.size();
// Read the subvolume of the MRC file which may contain extra views
err = reader->read(inputs->sinoFile, voxelMin, voxelMax);
if (err < 0)
{
FREE_FEI_HEADERS( header.feiHeaders )
setErrorMessage("Error Code from Reading MRC File");
setErrorCondition(err);
notify(getErrorMessage().c_str(), 0, UpdateErrorMessage);
return;
}
// This data is read as a Z,Y,X array where X is the fastest moving variable and Z is the slowest
int16_t* data = reinterpret_cast<int16_t*>(reader->getDataPointer());
//Allocate a 3-D matrix to store the singoram in the form of a N_y X N_theta X N_x matrix
// Here in the actual data, Z is the slowest, then X, then Y (The Fastest) so we
// will need to "rotate" the data in the XY plane when copying from the MRC read data into our
// own array.
// sinogram->counts=(DATA_TYPE***)get_3D(sinogram->N_theta,
// inputs->xEnd - inputs->xStart+1,
// inputs->yEnd - inputs->yStart+1,
// sizeof(DATA_TYPE));
size_t dims[3] = {sinogram->N_theta,
inputs->xEnd - inputs->xStart+1,
inputs->yEnd - inputs->yStart+1};
sinogram->counts = RealVolumeType::New(dims, "Sinogram.counts");
//If the bright field image is included initialize space for it
/*if(inputs->BrightFieldFile != NULL)
{
size_t dims[3] = {sinogram->N_theta,
inputs->xEnd - inputs->xStart+1,
inputs->yEnd - inputs->yStart+1};
sinogram->counts_BF = RealVolumeType::New(dims);
sinogram->counts_BF->setName("Sinogram.counts_BrightField");
}*/
sinogram->angles.resize(sinogram->N_theta);
FEIHeader* fei = NULL;
for (uint16_t z = 0; z < sinogram->N_theta; z++)
{
int dataZOffset = inputs->goodViews[z] - voxelMin[2];
// Copy the value of the tilt angle into the inputs->angles vector
if (NULL != header.feiHeaders) {
int offset = inputs->goodViews[z];
fei = &(header.feiHeaders[offset]);
if (inputs->tiltSelection == SOC::A_Tilt) {
sinogram->angles[z] = -fei->a_tilt;
}
else if (inputs->tiltSelection == SOC::B_Tilt)
{
sinogram->angles[z] = -fei->b_tilt;
}
}
// std::cout << "data_z_index: " << inputs->goodViews[z] << " dataZOffset: " << dataZOffset << " counts offset: " << z << std::endl;
for (uint16_t y = 0; y < sinogram->N_t; y++)
{
for (uint16_t x = 0; x < sinogram->N_r; x++)
{
size_t index = (dataZOffset * sinogram->N_r * sinogram->N_t) + (y * sinogram->N_r) + x;
sinogram->counts->setValue(data[index], z, x, y);
}
}
}
// Clean up all the memory associated with the MRC Reader
reader->setDeleteMemory(true);
reader = MRCReader::NullPointer();
FREE_FEI_HEADERS( header.feiHeaders )
// sinogram->N_theta = TotalNumMaskedViews;
// sinogram->N_r = (input->xEnd - input->xStart+1);
// sinogram->N_t = (input->yEnd - input->yStart+1);
sinogram->R0 = -(sinogram->N_r*sinogram->delta_r)/2;
sinogram->RMax = (sinogram->N_r*sinogram->delta_r)/2;
sinogram->T0 = -(sinogram->N_t*sinogram->delta_t)/2;
sinogram->TMax = (sinogram->N_t*sinogram->delta_t)/2;
ss << "Size of the Masked Sinogram N_r =" << sinogram->N_r << " N_t = "<< sinogram->N_t
<< " N_theta=" << sinogram->N_theta << std::endl;
if(getVerbose())
{
//display tilt angles
std::cout<<"The tilt angles are"<<std::endl;
for (uint16_t i = 0; i < sinogram->N_theta; i++)
{
std::cout<<sinogram->angles[i]<<std::endl;
}
//check sum calculation
for (uint16_t i = 0; i < sinogram->N_theta; i++)
{
sum = 0;
for (uint16_t j = 0; j < sinogram->N_r; j++)
{
for (uint16_t k = 0; k < sinogram->N_t; k++)
{
sum += sinogram->counts->getValue(i, j, k);
}
}
ss << "Sinogram Checksum " << i << ":" << sum << std::endl;
}
std::cout << ss.str() << std::endl;
}
setErrorCondition(0);
setErrorMessage("");
notify("Done Reading the MRC Input file", 0, UpdateProgressMessage);
}
<commit_msg>Initializing MRCHeader to all Zeros. Correcting formatting of debug statement<commit_after>/* ============================================================================
* Copyright (c) 2011 Michael A. Jackson (BlueQuartz Software)
* Copyright (c) 2011 Singanallur Venkatakrishnan (Purdue University)
* 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 Singanallur Venkatakrishnan, Michael A. Jackson, the Pudue
* Univeristy, BlueQuartz Software 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.
*
* This code was written under United States Air Force Contract number
* FA8650-07-D-5800
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "MRCSinogramInitializer.h"
#include "TomoEngine/Common/allocate.h"
#include "TomoEngine/IO/MRCHeader.h"
#include "TomoEngine/IO/MRCReader.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MRCSinogramInitializer::MRCSinogramInitializer()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
MRCSinogramInitializer::~MRCSinogramInitializer()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void MRCSinogramInitializer::execute()
{
std::stringstream ss;
SinogramPtr sinogram = getSinogram();
TomoInputsPtr inputs = getTomoInputs();
// int16_t i,j,k;
// uint16_t TotalNumMaskedViews;
Real_t sum=0;
MRCReader::Pointer reader = MRCReader::New(true);
MRCHeader header;
::memset(&header, 0, 1024);
header.feiHeaders = NULL;
int err = reader->readHeader(inputs->sinoFile, &header);
//reader->printHeader(&header, std::cout);
if (err < 0)
{
FREE_FEI_HEADERS( header.feiHeaders )
}
if (header.mode != 1)
{
FREE_FEI_HEADERS( header.feiHeaders )
ss << __FILE__ << "(" << __LINE__ << ") - 16 bit integers are only supported. Error at line " << std::endl;
setErrorCondition(-1);
notify(ss.str(), 0, Observable::UpdateErrorMessage);
return;
}
int voxelMin[3] = {0, 0, 0};
int voxelMax[3] = {header.nx-1, header.ny-1, header.nz-1};
inputs->fileXSize = header.nx;
inputs->fileYSize = header.ny;
inputs->fileZSize = header.nz;
Real_t CenterOfRot = header.nx/2;
ss.str("");
ss << "Center of rotation in this data set is " << CenterOfRot << std::endl;
if (inputs->useSubvolume == true)
{
voxelMin[0] = inputs->xStart;
voxelMin[1] = inputs->yStart;
voxelMin[2] = inputs->zStart;
voxelMax[0] = inputs->xEnd;
voxelMax[1] = inputs->yEnd;
voxelMax[2] = inputs->zEnd;
//Code to ensure region selected has the "right" dimensions
/************************************************************/
Real_t LeftLength = CenterOfRot - voxelMin[0];
Real_t RightLength = voxelMax[0] - CenterOfRot + 1; //1 is present to account for indexing of subvolume which starts from 0
if(LeftLength < 0)
{
voxelMin[0] = CenterOfRot + LeftLength;
inputs->xStart = voxelMin[0];
LeftLength *= -1;
}
if(RightLength < 0)
{
voxelMax[0] = CenterOfRot - RightLength;
inputs->xEnd = voxelMax[0];
RightLength *= -1;
}
if(LeftLength != RightLength)
{
ss << "The subvolume is not symmetric about the center. Adjusting.." << std::endl;
if(LeftLength < RightLength)
{
Real_t tempx = CenterOfRot + LeftLength - 1;
//Make sure the adjustment does not overrun the size of the data
if(tempx >= header.nx) tempx = header.nx - 1;
voxelMax[0] = tempx;
inputs->xEnd = voxelMax[0];
ss << "New xEnd : " << voxelMax[0] << std::endl;
}
else
{
Real_t tempx = CenterOfRot - RightLength;
//Make sure the adjustment does not overrun the size of the data
if(tempx < 0) tempx = 0;
voxelMin[0] = tempx;
inputs->xStart = voxelMin[0];
ss << "New xStart : " << voxelMin[0] << std::endl;
}
}
//This part of selecting y can be ignored if the user has selected
//single slice mode
//Adjusting the volume along the y-directions so we dont have
// issues with pixelation
ss <<"Current y ROI: "<< "yStart=" << inputs->yStart << " " << "yEnd=" << inputs->yEnd << std::endl;
int16_t disty = inputs->yEnd - inputs->yStart + 1;
ss << "Interpolate Factor=" << inputs->interpolateFactor << std::endl;
//3*iterpFactor is to account for the prior which operates on
//26 point 3-D neighborhood which needs 3 x-z slices at the least
int16_t rem_temp = disty % ((int16_t)inputs->interpolateFactor * 3);
if(rem_temp != 0)
{
ss << "The number of y-pixels is not a proper multiple for multi-res" << std::endl;
int16_t remainder = static_cast<int16_t>((inputs->interpolateFactor * 3) - (rem_temp));
//Make sure the adjustment does not overrun the size of the data
if(inputs->yEnd + remainder < header.ny) inputs->yEnd += remainder;
else
{
inputs->yEnd = header.ny - 1;
}
ss << "New yEnd " << inputs->yEnd << std::endl;
}
voxelMax[1] = inputs->yEnd;
ss << "xStart=" << inputs->xStart << " " << "xEnd=" << inputs->xEnd << std::endl;
ss << "yStart=" << inputs->yStart << " " << "yEnd=" << inputs->yEnd << std::endl;
/************************************************************/
}
else
{
inputs->xStart = 0;
inputs->yStart = 0;
inputs->zStart = 0;
inputs->xEnd = header.nx - 1;
inputs->yEnd = header.ny - 1;
inputs->zEnd = header.nz - 1;
}
sinogram->N_r = voxelMax[0] - voxelMin[0] + 1;
sinogram->N_t = voxelMax[1] - voxelMin[1] + 1;
sinogram->delta_r = 1.0;
sinogram->delta_t = 1.0;
FEIHeader* feiHeaders = header.feiHeaders;
if (feiHeaders != NULL)
{
sinogram->delta_r = feiHeaders[0].pixelsize * 1.0e9;
sinogram->delta_t = feiHeaders[0].pixelsize * 1.0e9;
}
// Clear out the vector as we are going to build it up
inputs->goodViews.resize(0,0);
int jStart = 0;
bool addToGoodView = false;
for (int i = voxelMin[2]; i <= voxelMax[2]; ++i )
{
addToGoodView = true;
for(size_t j = jStart; j < inputs->excludedViews.size(); ++j)
{
if (inputs->excludedViews[j] == i)
{
addToGoodView = false;
}
}
if (addToGoodView == true)
{
// std::cout << "Adding View Index: " << i << " To goodViews vector" << std::endl;
inputs->goodViews.push_back(i);
}
}
// The number of views is the size of the vector
sinogram->N_theta = inputs->goodViews.size();
// Read the subvolume of the MRC file which may contain extra views
err = reader->read(inputs->sinoFile, voxelMin, voxelMax);
if (err < 0)
{
FREE_FEI_HEADERS( header.feiHeaders )
setErrorMessage("Error Code from Reading MRC File");
setErrorCondition(err);
notify(getErrorMessage().c_str(), 0, UpdateErrorMessage);
return;
}
// This data is read as a Z,Y,X array where X is the fastest moving variable and Z is the slowest
int16_t* data = reinterpret_cast<int16_t*>(reader->getDataPointer());
//Allocate a 3-D matrix to store the singoram in the form of a N_y X N_theta X N_x matrix
// Here in the actual data, Z is the slowest, then X, then Y (The Fastest) so we
// will need to "rotate" the data in the XY plane when copying from the MRC read data into our
// own array.
// sinogram->counts=(DATA_TYPE***)get_3D(sinogram->N_theta,
// inputs->xEnd - inputs->xStart+1,
// inputs->yEnd - inputs->yStart+1,
// sizeof(DATA_TYPE));
size_t dims[3] = {sinogram->N_theta,
inputs->xEnd - inputs->xStart+1,
inputs->yEnd - inputs->yStart+1};
sinogram->counts = RealVolumeType::New(dims, "Sinogram.counts");
//If the bright field image is included initialize space for it
/*if(inputs->BrightFieldFile != NULL)
{
size_t dims[3] = {sinogram->N_theta,
inputs->xEnd - inputs->xStart+1,
inputs->yEnd - inputs->yStart+1};
sinogram->counts_BF = RealVolumeType::New(dims);
sinogram->counts_BF->setName("Sinogram.counts_BrightField");
}*/
sinogram->angles.resize(sinogram->N_theta);
FEIHeader* fei = NULL;
for (uint16_t z = 0; z < sinogram->N_theta; z++)
{
int dataZOffset = inputs->goodViews[z] - voxelMin[2];
// Copy the value of the tilt angle into the inputs->angles vector
if (NULL != header.feiHeaders) {
int offset = inputs->goodViews[z];
fei = &(header.feiHeaders[offset]);
if (inputs->tiltSelection == SOC::A_Tilt) {
sinogram->angles[z] = -fei->a_tilt;
}
else if (inputs->tiltSelection == SOC::B_Tilt)
{
sinogram->angles[z] = -fei->b_tilt;
}
}
// std::cout << "data_z_index: " << inputs->goodViews[z] << " dataZOffset: " << dataZOffset << " counts offset: " << z << std::endl;
for (uint16_t y = 0; y < sinogram->N_t; y++)
{
for (uint16_t x = 0; x < sinogram->N_r; x++)
{
size_t index = (dataZOffset * sinogram->N_r * sinogram->N_t) + (y * sinogram->N_r) + x;
sinogram->counts->setValue(data[index], z, x, y);
}
}
}
// Clean up all the memory associated with the MRC Reader
reader->setDeleteMemory(true);
reader = MRCReader::NullPointer();
FREE_FEI_HEADERS( header.feiHeaders )
// sinogram->N_theta = TotalNumMaskedViews;
// sinogram->N_r = (input->xEnd - input->xStart+1);
// sinogram->N_t = (input->yEnd - input->yStart+1);
sinogram->R0 = -(sinogram->N_r*sinogram->delta_r)/2;
sinogram->RMax = (sinogram->N_r*sinogram->delta_r)/2;
sinogram->T0 = -(sinogram->N_t*sinogram->delta_t)/2;
sinogram->TMax = (sinogram->N_t*sinogram->delta_t)/2;
ss << "Size of the Masked Sinogram N_r =" << sinogram->N_r << " N_t = "<< sinogram->N_t
<< " N_theta=" << sinogram->N_theta << std::endl;
if(getVerbose())
{
//display tilt angles
std::cout<<"The tilt angles are"<<std::endl;
for (uint16_t i = 0; i < sinogram->N_theta; i++)
{
std::cout<<sinogram->angles[i]<<std::endl;
}
//check sum calculation
for (uint16_t i = 0; i < sinogram->N_theta; i++)
{
sum = 0;
for (uint16_t j = 0; j < sinogram->N_r; j++)
{
for (uint16_t k = 0; k < sinogram->N_t; k++)
{
sum += sinogram->counts->getValue(i, j, k);
}
}
ss << "Sinogram Checksum " << i << ":" << sum << std::endl;
}
std::cout << ss.str() << std::endl;
}
setErrorCondition(0);
setErrorMessage("");
notify("Done Reading the MRC Input file", 0, UpdateProgressMessage);
}
<|endoftext|> |
<commit_before>/*
* rpcServer.cpp
*
* Created on: 31. 10. 2017
* Author: ondra
*/
#include "rpcServer.h"
#include <imtjson/serializer.h>
#include <imtjson/parser.h>
#include "../simpleServer/websockets_stream.h"
#include "../simpleServer/asyncProvider.h"
#include "../simpleServer/http_hostmapping.h"
#include "../simpleServer/websockets_stream.h"
#include "../simpleServer/query_parser.h"
#include "../simpleServer/logOutput.h"
#include "resources.h"
namespace simpleServer {
using ondra_shared::LogLevel;
using ondra_shared::SharedLogObject;
using ondra_shared::AbstractLogProvider;
class WSStreamWithContext: public _details::WebSocketStreamImpl {
public:
typedef _details::WebSocketStreamImpl Super;
using Super::WebSocketStreamImpl;
auto getConnContext() const {return ctx;}
protected:
PRpcConnContext ctx = new RpcConnContext;
};
class WebSocketHandlerWithContext: public WebSocketHandler{
public:
using WebSocketHandler::WebSocketHandler ;
virtual WebSocketStream createStream(Stream sx) const {
return new WSStreamWithContext(sx);
}
virtual ~WebSocketHandlerWithContext() {}
};
RpcHandler::RpcHandler(RpcServer& rpcserver)
:rpcserver(rpcserver) {
}
void RpcHandler::operator ()(simpleServer::HTTPRequest req) const {
operator()(req, req.getPath());
}
class RpcServerEnum: public RpcServer {
public:
template<typename Fn>
void forEach(const Fn &fn) {
for(auto &x : mapReg) {
fn(x.second->name);
}
}
};
static void handleLogging(const SharedLogObject logObj, const Value &v, const RpcRequest &req) noexcept {
if (logObj.isLogLevelEnabled(LogLevel::progress)) {
try {
Value diagData = req.getDiagData();
Value args = req.getArgs();
Value method = req.getMethodName();
Value context = req.getContext();
if (!diagData.defined() && req.isErrorSent()) {
diagData = v["error"];
}
if (!diagData.defined()) diagData = nullptr;
if (!context.defined()) context = nullptr;
Value output = {method,args,context,diagData};
logObj.progress("$1", output.toString());
} catch (...) {
}
}
}
bool RpcHandler::operator ()(simpleServer::HTTPRequest req, const StrViewA &vpath) const {
StrViewA method = req.getMethod();
if (method == "POST") {
RpcServer &srv(rpcserver);
req.readBodyAsync(maxReqSize, [&srv](HTTPRequest httpreq){
auto x = httpreq.getUserBuffer();
if (x.empty()) {
RpcServerEnum &enm = static_cast<RpcServerEnum &>(srv);
Array methods;
enm.forEach([&methods](Value v){methods.push_back(v);});
Stream out = httpreq.sendResponse("application/json");
Value(methods).serialize(out);
out.flush();
} else {
Value rdata = Value::fromString(StrViewA(BinaryView(x)));
SharedLogObject logObj(*httpreq->log, "RPC");
RpcRequest rrq = RpcRequest::create(rdata,[httpreq,logObj](const Value &v, const RpcRequest &req){
handleLogging(logObj,v,req);
try {
Stream out = httpreq.sendResponse("application/json");
v.serialize(out);
out.flush();
return true;
} catch (...) {
return false;
}
}, RpcFlags::preResponseNotify);
srv(rrq);
}
});
} else if (vpath.empty()) {
req.redirectToFolderRoot();
} else {
Resource *selRes = nullptr;
StrViewA fname;
QueryParser qp(vpath);
auto splt = qp.getPath().split("/");
while (splt) fname = splt();
if (fname.empty()) fname="index.html";
if (fname == "index.html") selRes = consoleEnabled?&client_index_html:nullptr;
else if (fname == "styles.css") selRes = consoleEnabled?&client_styles_css:nullptr;
else if (fname == "rpc.js") selRes = &client_rpc_js;
if (selRes == nullptr) {
req.sendErrorPage(404);
} else {
req.sendResponse(selRes->contentType, selRes->data);
}
}
return true;
}
void RpcHttpServer::addRPCPath(String path) {
Config cfg;
addRPCPath(path,cfg);
}
void RpcHttpServer::addRPCPath(String path, const Config &cfg) {
RpcHandler h(*this);
if (cfg.maxReqSize) h.setMaxReqSize(cfg.maxReqSize);
enableDirect = cfg.enableDirect;
h.enableConsole(cfg.enableConsole);
if (cfg.enableWS) {
WebSocketHandlerWithContext ws(h);
auto h2 = [=](HTTPRequest req, StrViewA vpath) mutable {
if (!ws(req,vpath)) return h(req,vpath);
else return true;
};
mapRecords.push_back(Item(path,HTTPMappedHandler(h2)));
} else {
mapRecords.push_back(Item(path,HTTPMappedHandler(h)));
}
}
void RpcHttpServer::addPath(String path, simpleServer::HTTPMappedHandler hndl) {
mapRecords.push_back(std::make_pair(path, hndl));
}
void RpcHttpServer::setHostMapping(const String &mapping) {
hostMapping = mapping;
}
void RpcHttpServer::directRpcAsync(Stream s) {
directRpcAsync2(s,new RpcConnContext);
}
void RpcHttpServer::directRpcAsync2(simpleServer::Stream s, PRpcConnContext ctx) {
auto sendFn =[=](Value v) {
try {
v.serialize(s);
s << "\n";
s.flush();
return true;
} catch (...) {
return false;
}
};
try {
BinaryView b = s.read(true);
while (!b.empty() && isspace(b[0])) b = b.substr(1);
if (!b.empty()) {
s.putBack(b);
Value jsonReq = Value::parse(s);
RpcRequest req = RpcRequest::create(jsonReq,sendFn, RpcFlags::notify, ctx);
ctx->store("__last_jsonrpc_ver",req.getVersionField());
this->operator ()(req);
}
s.readAsync([=](simpleServer::AsyncState st, const ondra_shared::BinaryView &b) {
if (st == asyncTimeout) {
Value ver = ctx->retrieve("__last_jsonrpc_ver");
RpcRequest req = RpcRequest::create({Value(),Value(),Value(),Value(),ver},sendFn,RpcFlags::notify);
req.sendNotify("ping",Value());
s.readAsync([=](simpleServer::AsyncState st, const ondra_shared::BinaryView &b) {
if (st == asyncOK) {
s.putBack(b);
directRpcAsync2(s,ctx);
}
});
} else if (st == asyncOK) {
s.putBack(b);
directRpcAsync2(s,ctx);
}
});
} catch (...) {
}
}
void RpcHttpServer::start() {
std::vector<HttpStaticPathMapper::MapRecord> reglist;
reglist.reserve(mapRecords.size());
for (auto &&x: mapRecords) {
HttpStaticPathMapper::MapRecord k;
k.path = x.first;
k.handler = x.second;
reglist.push_back(k);
}
HttpStaticPathMapper hndl(std::move(reglist));
if (enableDirect) {
this->preHandler = [=](Stream s) {
try {
int b = s.peek();
if (b == '{') {//starting with RPC protocol
directRpcAsync(s);
return true;
} else {
return false;
}
} catch (...) {
return true;
}
};
}
HostMappingHandler hostMap;
hostMap.setMapping(hostMapping);
HttpStaticPathMapperHandler stHandler(hndl);
(*this)>>(hostMap>>HTTPMappedHandler(stHandler));
}
void RpcHandler::operator ()(simpleServer::HTTPRequest httpreq, WebSocketStream wsstream) const {
if (wsstream.getFrameType() == WSFrameType::text) {
Value jreq;
try {
jreq = Value::fromString(wsstream.getText());
} catch (std::exception &e) {
Value genError = Object("error",rpcserver.formatError(-32700,"Parse error",Value()));
wsstream.postText(genError.stringify());
return;
}
WSStreamWithContext::Super *wsx = wsstream;
WSStreamWithContext *wswc = static_cast<WSStreamWithContext *>(wsx);
PRpcConnContext connctx;
if (wswc) connctx = wswc->getConnContext();
SharedLogObject logObj(*httpreq->log, "RPC");
RpcRequest rrq = RpcRequest::create(jreq,[wsstream,logObj](const Value &v, const RpcRequest &req){
WebSocketStream ws(wsstream);
if (!v.defined()) {
if (ws.isClosed()) return false;
try {
ws.ping(BinaryView());
return true;
} catch (...) {
return false;
}
}
handleLogging(logObj,v,req);
try {
ws.postText(v.stringify());
return true;
} catch (...) {
return false;
}
},RpcFlags::notify, connctx);
rpcserver(rrq);
}
}
} /* namespace hflib */
<commit_msg>improve RPC HTTP notify<commit_after>/*
* rpcServer.cpp
*
* Created on: 31. 10. 2017
* Author: ondra
*/
#include "rpcServer.h"
#include <imtjson/serializer.h>
#include <imtjson/parser.h>
#include "../simpleServer/websockets_stream.h"
#include "../simpleServer/asyncProvider.h"
#include "../simpleServer/http_hostmapping.h"
#include "../simpleServer/websockets_stream.h"
#include "../simpleServer/query_parser.h"
#include "../simpleServer/logOutput.h"
#include "resources.h"
namespace simpleServer {
using ondra_shared::LogLevel;
using ondra_shared::SharedLogObject;
using ondra_shared::AbstractLogProvider;
class WSStreamWithContext: public _details::WebSocketStreamImpl {
public:
typedef _details::WebSocketStreamImpl Super;
using Super::WebSocketStreamImpl;
auto getConnContext() const {return ctx;}
protected:
PRpcConnContext ctx = new RpcConnContext;
};
class WebSocketHandlerWithContext: public WebSocketHandler{
public:
using WebSocketHandler::WebSocketHandler ;
virtual WebSocketStream createStream(Stream sx) const {
return new WSStreamWithContext(sx);
}
virtual ~WebSocketHandlerWithContext() {}
};
RpcHandler::RpcHandler(RpcServer& rpcserver)
:rpcserver(rpcserver) {
}
void RpcHandler::operator ()(simpleServer::HTTPRequest req) const {
operator()(req, req.getPath());
}
class RpcServerEnum: public RpcServer {
public:
template<typename Fn>
void forEach(const Fn &fn) {
for(auto &x : mapReg) {
fn(x.second->name);
}
}
};
static void handleLogging(const SharedLogObject logObj, const Value &v, const RpcRequest &req) noexcept {
if (logObj.isLogLevelEnabled(LogLevel::progress)) {
try {
Value diagData = req.getDiagData();
Value args = req.getArgs();
Value method = req.getMethodName();
Value context = req.getContext();
if (!diagData.defined() && req.isErrorSent()) {
diagData = v["error"];
}
if (!diagData.defined()) diagData = nullptr;
if (!context.defined()) context = nullptr;
Value output = {method,args,context,diagData};
logObj.progress("$1", output.toString());
} catch (...) {
}
}
}
bool RpcHandler::operator ()(simpleServer::HTTPRequest req, const StrViewA &vpath) const {
StrViewA method = req.getMethod();
if (method == "POST") {
RpcServer &srv(rpcserver);
req.readBodyAsync(maxReqSize, [&srv](HTTPRequest httpreq){
auto x = httpreq.getUserBuffer();
if (x.empty()) {
RpcServerEnum &enm = static_cast<RpcServerEnum &>(srv);
Array methods;
enm.forEach([&methods](Value v){methods.push_back(v);});
Stream out = httpreq.sendResponse("application/json");
Value(methods).serialize(out);
out.flush();
} else {
Value rdata = Value::fromString(StrViewA(BinaryView(x)));
SharedLogObject logObj(*httpreq->log, "RPC");
Stream out = httpreq.sendResponse("application/json");
RpcRequest rrq = RpcRequest::create(rdata,[httpreq,logObj,out](const Value &v, const RpcRequest &req){
handleLogging(logObj,v,req);
try {
v.serialize(out);
out << "\r\n";
return out.flush();
} catch (...) {
return false;
}
}, RpcFlags::preResponseNotify);
srv(rrq);
}
});
} else if (vpath.empty()) {
req.redirectToFolderRoot();
} else {
Resource *selRes = nullptr;
StrViewA fname;
QueryParser qp(vpath);
auto splt = qp.getPath().split("/");
while (splt) fname = splt();
if (fname.empty()) fname="index.html";
if (fname == "index.html") selRes = consoleEnabled?&client_index_html:nullptr;
else if (fname == "styles.css") selRes = consoleEnabled?&client_styles_css:nullptr;
else if (fname == "rpc.js") selRes = &client_rpc_js;
if (selRes == nullptr) {
req.sendErrorPage(404);
} else {
req.sendResponse(selRes->contentType, selRes->data);
}
}
return true;
}
void RpcHttpServer::addRPCPath(String path) {
Config cfg;
addRPCPath(path,cfg);
}
void RpcHttpServer::addRPCPath(String path, const Config &cfg) {
RpcHandler h(*this);
if (cfg.maxReqSize) h.setMaxReqSize(cfg.maxReqSize);
enableDirect = cfg.enableDirect;
h.enableConsole(cfg.enableConsole);
if (cfg.enableWS) {
WebSocketHandlerWithContext ws(h);
auto h2 = [=](HTTPRequest req, StrViewA vpath) mutable {
if (!ws(req,vpath)) return h(req,vpath);
else return true;
};
mapRecords.push_back(Item(path,HTTPMappedHandler(h2)));
} else {
mapRecords.push_back(Item(path,HTTPMappedHandler(h)));
}
}
void RpcHttpServer::addPath(String path, simpleServer::HTTPMappedHandler hndl) {
mapRecords.push_back(std::make_pair(path, hndl));
}
void RpcHttpServer::setHostMapping(const String &mapping) {
hostMapping = mapping;
}
void RpcHttpServer::directRpcAsync(Stream s) {
directRpcAsync2(s,new RpcConnContext);
}
void RpcHttpServer::directRpcAsync2(simpleServer::Stream s, PRpcConnContext ctx) {
auto sendFn =[=](Value v) {
try {
v.serialize(s);
s << "\n";
s.flush();
return true;
} catch (...) {
return false;
}
};
try {
BinaryView b = s.read(true);
while (!b.empty() && isspace(b[0])) b = b.substr(1);
if (!b.empty()) {
s.putBack(b);
Value jsonReq = Value::parse(s);
RpcRequest req = RpcRequest::create(jsonReq,sendFn, RpcFlags::notify, ctx);
ctx->store("__last_jsonrpc_ver",req.getVersionField());
this->operator ()(req);
}
s.readAsync([=](simpleServer::AsyncState st, const ondra_shared::BinaryView &b) {
if (st == asyncTimeout) {
Value ver = ctx->retrieve("__last_jsonrpc_ver");
RpcRequest req = RpcRequest::create({Value(),Value(),Value(),Value(),ver},sendFn,RpcFlags::notify);
req.sendNotify("ping",Value());
s.readAsync([=](simpleServer::AsyncState st, const ondra_shared::BinaryView &b) {
if (st == asyncOK) {
s.putBack(b);
directRpcAsync2(s,ctx);
}
});
} else if (st == asyncOK) {
s.putBack(b);
directRpcAsync2(s,ctx);
}
});
} catch (...) {
}
}
void RpcHttpServer::start() {
std::vector<HttpStaticPathMapper::MapRecord> reglist;
reglist.reserve(mapRecords.size());
for (auto &&x: mapRecords) {
HttpStaticPathMapper::MapRecord k;
k.path = x.first;
k.handler = x.second;
reglist.push_back(k);
}
HttpStaticPathMapper hndl(std::move(reglist));
if (enableDirect) {
this->preHandler = [=](Stream s) {
try {
int b = s.peek();
if (b == '{') {//starting with RPC protocol
directRpcAsync(s);
return true;
} else {
return false;
}
} catch (...) {
return true;
}
};
}
HostMappingHandler hostMap;
hostMap.setMapping(hostMapping);
HttpStaticPathMapperHandler stHandler(hndl);
(*this)>>(hostMap>>HTTPMappedHandler(stHandler));
}
void RpcHandler::operator ()(simpleServer::HTTPRequest httpreq, WebSocketStream wsstream) const {
if (wsstream.getFrameType() == WSFrameType::text) {
Value jreq;
try {
jreq = Value::fromString(wsstream.getText());
} catch (std::exception &e) {
Value genError = Object("error",rpcserver.formatError(-32700,"Parse error",Value()));
wsstream.postText(genError.stringify());
return;
}
WSStreamWithContext::Super *wsx = wsstream;
WSStreamWithContext *wswc = static_cast<WSStreamWithContext *>(wsx);
PRpcConnContext connctx;
if (wswc) connctx = wswc->getConnContext();
SharedLogObject logObj(*httpreq->log, "RPC");
RpcRequest rrq = RpcRequest::create(jreq,[wsstream,logObj](const Value &v, const RpcRequest &req){
WebSocketStream ws(wsstream);
if (!v.defined()) {
if (ws.isClosed()) return false;
try {
ws.ping(BinaryView());
return true;
} catch (...) {
return false;
}
}
handleLogging(logObj,v,req);
try {
ws.postText(v.stringify());
return true;
} catch (...) {
return false;
}
},RpcFlags::notify, connctx);
rpcserver(rrq);
}
}
} /* namespace hflib */
<|endoftext|> |
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Nathan Osman
*
* 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 <QJsonDocument>
#include "../util/json.h"
#include "../util/settings.h"
#include "transferreceiver.h"
TransferReceiver::TransferReceiver(qintptr socketDescriptor)
: Transfer(TransferModel::Receive),
mRoot(Settings::get<QString>(Settings::TransferDirectory))
{
mSocket.setSocketDescriptor(socketDescriptor);
}
void TransferReceiver::start()
{
// The socket is already connected at this point
}
void TransferReceiver::processPacket(const QByteArray &data)
{
// Depending on the state of the transfer, process the packet accordingly
switch(mProtocolState){
case TransferHeader:
processTransferHeader(data);
break;
case ItemHeader:
processItemHeader(data);
break;
case ItemData:
processItemData(data);
break;
case Finished:
break;
}
}
void TransferReceiver::writeNextPacket()
{
// This is only ever invoked after success
finish();
}
void TransferReceiver::processTransferHeader(const QByteArray &data)
{
QJsonDocument document = QJsonDocument::fromJson(data);
QJsonObject object;
if(Json::isObject(document, object) &&
Json::objectContains(object, "name", mDeviceName) &&
Json::objectContains(object, "size", mTransferBytesTotal) &&
Json::objectContains(object, "count", mTransferItemsRemaining)) {
emit dataChanged({TransferModel::DeviceNameRole});
// The next packet will be the first file header
mProtocolState = ItemHeader;
} else {
abortWithError(tr("Unable to read transfer header"));
}
}
void TransferReceiver::processItemHeader(const QByteArray &data)
{
QJsonDocument document = QJsonDocument::fromJson(data);
QJsonObject object;
QString name;
bool directory;
qint64 created;
qint64 lastModified;
qint64 lastRead;
// Read the contents of the header
if(Json::isObject(document, object) &&
Json::objectContains(object, "name", name) &&
Json::objectContains(object, "directory", directory) &&
Json::objectContains(object, "created", created) &&
Json::objectContains(object, "last_modified", lastModified) &&
Json::objectContains(object, "last_read", lastRead)) {
// TODO: created, lastModified, and lastRead are unused
// Determine the absolute filename of the item
QString filename = mRoot.absoluteFilePath(name);
// If the item is a directory, attempt to create it
// Otherwise, open the file for writing since the directory should exist
if(directory) {
if(!QDir(filename).mkpath(".")) {
abortWithError(tr("Unable to create %1").arg(filename));
return;
}
// Move to the next item
nextItem();
} else {
// Ensure that the size was included
if(!Json::objectContains(object, "size", mFileBytesRemaining)) {
abortWithError(tr("File size is missing from header"));
return;
}
// Abort if the file can't be opened
mFile.setFileName(filename);
if(!mFile.open(QIODevice::WriteOnly)) {
abortWithError(tr("Unable to open %1").arg(filename));
return;
}
// If the file is non-empty, switch states
// Otherwise close the file and move to the next item
if(mFileBytesRemaining) {
mProtocolState = ItemData;
} else {
mFile.close();
nextItem();
}
}
} else {
abortWithError(tr("Unable to read file header"));
}
}
void TransferReceiver::processItemData(const QByteArray &data)
{
// Write the data to the file
mFile.write(data);
// Update the number of bytes remaining for the file and the total transferred
mFileBytesRemaining -= data.size();
mTransferBytes += data.size();
// Provide a progress update
calculateProgress();
// If there are no more bytes to write to the file, move on the
// next file or indicate that the transfer has completed
if(mFileBytesRemaining <= 0) {
mFile.close();
nextItem();
}
}
void TransferReceiver::nextItem()
{
// Decrement the number of items remaining
mTransferItemsRemaining -= 1;
// Check to see if there are any more items remaining
if(!mTransferItemsRemaining) {
// Write the "success" packet
writePacket({
{ "success", true }
});
mProtocolState = Finished;
} else {
mProtocolState = ItemHeader;
}
}
<commit_msg>Fixed ambiguous overload error in MS VC++.<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Nathan Osman
*
* 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 <QJsonDocument>
#include "../util/json.h"
#include "../util/settings.h"
#include "transferreceiver.h"
TransferReceiver::TransferReceiver(qintptr socketDescriptor)
: Transfer(TransferModel::Receive),
mRoot(Settings::get<QString>(Settings::TransferDirectory))
{
mSocket.setSocketDescriptor(socketDescriptor);
}
void TransferReceiver::start()
{
// The socket is already connected at this point
}
void TransferReceiver::processPacket(const QByteArray &data)
{
// Depending on the state of the transfer, process the packet accordingly
switch(mProtocolState){
case TransferHeader:
processTransferHeader(data);
break;
case ItemHeader:
processItemHeader(data);
break;
case ItemData:
processItemData(data);
break;
case Finished:
break;
}
}
void TransferReceiver::writeNextPacket()
{
// This is only ever invoked after success
finish();
}
void TransferReceiver::processTransferHeader(const QByteArray &data)
{
QJsonDocument document = QJsonDocument::fromJson(data);
QJsonObject object;
if(Json::isObject(document, object) &&
Json::objectContains(object, "name", mDeviceName) &&
Json::objectContains(object, "size", mTransferBytesTotal) &&
Json::objectContains(object, "count", mTransferItemsRemaining)) {
emit dataChanged({TransferModel::DeviceNameRole});
// The next packet will be the first file header
mProtocolState = ItemHeader;
} else {
abortWithError(tr("Unable to read transfer header"));
}
}
void TransferReceiver::processItemHeader(const QByteArray &data)
{
QJsonDocument document = QJsonDocument::fromJson(data);
QJsonObject object;
QString name;
bool directory;
qint64 created;
qint64 lastModified;
qint64 lastRead;
// Read the contents of the header
if(Json::isObject(document, object) &&
Json::objectContains(object, "name", name) &&
Json::objectContains(object, "directory", directory) &&
Json::objectContains(object, "created", created) &&
Json::objectContains(object, "last_modified", lastModified) &&
Json::objectContains(object, "last_read", lastRead)) {
// TODO: created, lastModified, and lastRead are unused
// Determine the absolute filename of the item
QString filename = mRoot.absoluteFilePath(name);
// If the item is a directory, attempt to create it
// Otherwise, open the file for writing since the directory should exist
if(directory) {
if(!QDir(filename).mkpath(".")) {
abortWithError(tr("Unable to create %1").arg(filename));
return;
}
// Move to the next item
nextItem();
} else {
// Ensure that the size was included
if(!Json::objectContains(object, "size", mFileBytesRemaining)) {
abortWithError(tr("File size is missing from header"));
return;
}
// Abort if the file can't be opened
mFile.setFileName(filename);
if(!mFile.open(QIODevice::WriteOnly)) {
abortWithError(tr("Unable to open %1").arg(filename));
return;
}
// If the file is non-empty, switch states
// Otherwise close the file and move to the next item
if(mFileBytesRemaining) {
mProtocolState = ItemData;
} else {
mFile.close();
nextItem();
}
}
} else {
abortWithError(tr("Unable to read file header"));
}
}
void TransferReceiver::processItemData(const QByteArray &data)
{
// Write the data to the file
mFile.write(data);
// Update the number of bytes remaining for the file and the total transferred
mFileBytesRemaining -= data.size();
mTransferBytes += data.size();
// Provide a progress update
calculateProgress();
// If there are no more bytes to write to the file, move on the
// next file or indicate that the transfer has completed
if(mFileBytesRemaining <= 0) {
mFile.close();
nextItem();
}
}
void TransferReceiver::nextItem()
{
// Decrement the number of items remaining
mTransferItemsRemaining -= 1;
// Check to see if there are any more items remaining
if(!mTransferItemsRemaining) {
// Write the "success" packet
QVariantMap packet = {
{ "success", true }
};
writePacket(packet);
mProtocolState = Finished;
} else {
mProtocolState = ItemHeader;
}
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS supdremove (1.37.82); FILE MERGED 2007/11/16 10:24:11 vg 1.37.82.1: #i83674# cleanup: remove obsolete SUPD macro use<commit_after><|endoftext|> |
<commit_before>#include "ShaderManager.h"
#include "GlShaderProgram.h"
using namespace std;
static string defaultVertexShaderSrc =
#ifdef __EMSCRIPTEN__
"precision highp float;\n"
"precision highp int;\n"
#else
"#version 120\n"
#endif
"uniform mat4 u_modelviewMatrix;"
"uniform mat4 u_projectionMatrix;"
"uniform vec4 u_color;"
"uniform bool u_globalColor;"
"uniform bool u_globalTexture;"
"uniform bool u_textureActivated;"
"uniform bool u_pointsRendering;"
"uniform bool u_globalPointSize;"
"uniform float u_pointSize;"
"uniform vec4 u_texCoordOffsets;"
"attribute vec3 a_position;"
"attribute vec4 a_color;"
"attribute vec2 a_texCoord;"
"attribute float a_pointSize;"
"attribute vec4 a_texCoordOffsets;"
"varying vec4 v_color;"
"varying vec2 v_texCoord;"
"varying vec4 v_texCoordOffsets;"
"void main() {"
" gl_Position = u_projectionMatrix * u_modelviewMatrix * vec4(a_position, 1.0);"
" if (u_globalColor) {"
" v_color = u_color;"
" } else {"
" v_color = a_color;"
" }"
" if (u_textureActivated) {"
" v_texCoord = a_texCoord;"
" if (u_globalTexture) {"
" v_texCoordOffsets = u_texCoordOffsets;"
" } else {"
" v_texCoordOffsets = a_texCoordOffsets;"
" }"
" }"
" if (u_pointsRendering) {"
" if (u_globalPointSize) {"
" gl_PointSize = u_pointSize;"
" } else {"
" gl_PointSize = a_pointSize;"
" }"
" }"
"}"
;
static string defaultFragmentShaderSrc =
#ifdef __EMSCRIPTEN__
"precision highp float;\n"
"precision highp int;\n"
#else
"#version 120\n"
#endif
"uniform bool u_textureActivated;"
"uniform sampler2D u_texture;"
"varying vec4 v_color;"
"varying vec2 v_texCoord;"
"varying vec4 v_texCoordOffsets;"
"void main() {"
" if (!u_textureActivated) {"
" gl_FragColor = v_color;"
" } else {"
" vec2 texCoord = vec2(v_texCoordOffsets.x + v_texCoord.x * (v_texCoordOffsets.z - v_texCoordOffsets.x),"
" v_texCoordOffsets.y + v_texCoord.y * (v_texCoordOffsets.w - v_texCoordOffsets.y));"
" gl_FragColor = v_color * texture2D(u_texture, texCoord);"
" }"
"}"
;
static string blinnPhongVertexShaderSrc =
#ifdef __EMSCRIPTEN__
"precision highp float;\n"
"precision highp int;\n"
#else
"#version 120\n"
#endif
"uniform mat4 u_modelviewMatrix;"
"uniform mat4 u_projectionMatrix;"
"uniform mat4 u_normalMatrix;"
"uniform bool u_globalColor;"
"uniform bool u_textureActivated;"
"uniform vec3 u_eyePosition;"
"uniform vec4 u_lightPosition;"
"uniform float u_lightConstantAttenuation;"
"uniform float u_lightLinearAttenuation;"
"uniform float u_lightQuadraticAttenuation;"
"uniform vec4 u_lightModelAmbientColor;"
"uniform vec4 u_lightAmbientColor;"
"uniform vec4 u_lightDiffuseColor;"
"uniform vec4 u_materialAmbientColor;"
"uniform vec4 u_materialDiffuseColor;"
"attribute vec3 a_position;"
"attribute vec4 a_color;"
"attribute vec2 a_texCoord;"
"attribute vec3 a_normal;"
"varying vec4 v_diffuseColor;"
"varying vec4 v_ambientGlobalColor;"
"varying vec4 v_ambientColor;"
"varying vec3 v_normal;"
"varying vec3 v_lightDir;"
"varying vec3 v_halfVector;"
"varying float v_attenuation;"
"varying vec2 v_texCoord;"
"void main(){"
" v_normal = normalize(mat3(u_normalMatrix) * a_normal);"
" vec4 pos = u_modelviewMatrix * vec4(a_position, 1.0);"
" vec3 lightVec = u_lightPosition.xyz-pos.xyz;"
" if (u_lightPosition.w == 0.0) {"
" lightVec = -u_lightPosition.xyz;"
" }"
" v_lightDir = normalize(lightVec);"
" float dist = length(lightVec);"
" v_attenuation = 1.0 / (u_lightConstantAttenuation +"
" u_lightLinearAttenuation * dist +"
" u_lightQuadraticAttenuation * dist * dist);"
" v_halfVector = u_eyePosition + u_lightPosition.xyz;"
" v_halfVector = normalize(v_halfVector);"
" if (u_globalColor) {"
" v_diffuseColor = u_lightDiffuseColor * u_materialDiffuseColor;"
" } else {"
" v_diffuseColor = u_lightDiffuseColor * a_color;"
" }"
" v_ambientColor = u_lightAmbientColor * u_materialAmbientColor;"
" v_ambientGlobalColor = u_lightModelAmbientColor * u_materialAmbientColor;"
" gl_Position = u_projectionMatrix * pos;"
" if (u_textureActivated) {"
" v_texCoord = a_texCoord;"
" }"
"}"
;
static string blinnPhongFragmentShaderSrc =
#ifdef __EMSCRIPTEN__
"precision highp float;\n"
"precision highp int;\n"
#else
"#version 120\n"
#endif
"uniform bool u_flatShading;"
"uniform bool u_textureActivated;"
"uniform sampler2D u_texture;"
"uniform vec4 u_lightSpecularColor;"
"uniform vec4 u_materialSpecularColor;"
"uniform float u_materialShininess;"
"varying vec4 v_diffuseColor;"
"varying vec4 v_ambientGlobalColor;"
"varying vec4 v_ambientColor;"
"varying vec3 v_normal;"
"varying vec3 v_lightDir;"
"varying vec3 v_halfVector;"
"varying float v_attenuation;"
"varying vec2 v_texCoord;"
"void main() {"
" if (u_flatShading) {"
" gl_FragColor = v_diffuseColor;"
" if (u_textureActivated) {"
" gl_FragColor *= texture2D(u_texture, v_texCoord);"
" }"
" return;"
" }"
" vec3 normal = normalize(v_normal);"
" vec4 color = v_ambientGlobalColor + v_ambientColor;"
" float NdotL = max(dot(normal,normalize(v_lightDir)),0.0);"
" if (NdotL > 0.0) {"
" color += v_attenuation * v_diffuseColor * NdotL;"
" vec3 halfV = normalize(v_halfVector);"
" float NdotHV = max(dot(normal, halfV), 0.0);"
" color += v_attenuation * u_materialSpecularColor * u_lightSpecularColor * pow(NdotHV, u_materialShininess);"
" }"
" if (u_textureActivated) {"
" color *= texture2D(u_texture, v_texCoord);"
" }"
" gl_FragColor = color;"
"}"
;
/**
https://github.com/mattdesl/glsl-fxaa
The MIT License (MIT) Copyright (c) 2014 Matt DesLauriers
Basic FXAA implementation based on the code on geeks3d.com with the
modification that the texture2DLod stuff was removed since it's
unsupported by WebGL.
--
From:
https://github.com/mitsuhiko/webgl-meincraft
Copyright (c) 2011 by Armin Ronacher.
Some 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.
* The names of the contributors may not 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.
*/
static string fxaaFunctionsSrc =
"\n#ifndef FXAA_REDUCE_MIN\n"
" #define FXAA_REDUCE_MIN (1.0/ 128.0)\n"
"#endif\n"
"#ifndef FXAA_REDUCE_MUL\n"
" #define FXAA_REDUCE_MUL (1.0 / 8.0)\n"
"#endif\n"
"#ifndef FXAA_SPAN_MAX\n"
" #define FXAA_SPAN_MAX 8.0\n"
"#endif\n"
//optimized version for mobile, where dependent
//texture reads can be a bottleneck
"vec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,"
" vec2 v_rgbNW, vec2 v_rgbNE,"
" vec2 v_rgbSW, vec2 v_rgbSE,"
" vec2 v_rgbM) {"
" vec4 color;"
" mediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);"
" vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;"
" vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;"
" vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;"
" vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;"
" vec4 texColor = texture2D(tex, v_rgbM);"
" vec3 rgbM = texColor.xyz;"
" vec3 luma = vec3(0.299, 0.587, 0.114);"
" float lumaNW = dot(rgbNW, luma);"
" float lumaNE = dot(rgbNE, luma);"
" float lumaSW = dot(rgbSW, luma);"
" float lumaSE = dot(rgbSE, luma);"
" float lumaM = dot(rgbM, luma);"
" float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));"
" float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));"
" mediump vec2 dir;"
" dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));"
" dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));"
" float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *"
" (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);"
" float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);"
" dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),"
" max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),"
" dir * rcpDirMin)) * inverseVP;"
" vec3 rgbA = 0.5 * ("
" texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +"
" texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);"
" vec3 rgbB = rgbA * 0.5 + 0.25 * ("
" texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +"
" texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);"
" float lumaB = dot(rgbB, luma);"
" if ((lumaB < lumaMin) || (lumaB > lumaMax)) {"
" color = vec4(rgbA, texColor.a);"
" } else {"
" color = vec4(rgbB, texColor.a);"
" }"
" return color;"
"}"
"void texcoords(vec2 fragCoord, vec2 resolution,"
" out vec2 v_rgbNW, out vec2 v_rgbNE,"
" out vec2 v_rgbSW, out vec2 v_rgbSE,"
" out vec2 v_rgbM) {"
" vec2 inverseVP = 1.0 / resolution.xy;"
" v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;"
" v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;"
" v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;"
" v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;"
" v_rgbM = vec2(fragCoord * inverseVP);"
"}"
"vec4 applyFXAA(sampler2D tex, vec2 fragCoord, vec2 resolution) {"
" mediump vec2 v_rgbNW;"
" mediump vec2 v_rgbNE;"
" mediump vec2 v_rgbSW;"
" mediump vec2 v_rgbSE;"
" mediump vec2 v_rgbM;"
//compute the texture coords
" texcoords(fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);"
//compute FXAA
" return fxaa(tex, fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);"
"}"
;
map<string, ShaderManager *> ShaderManager::_instances;
string ShaderManager::_currentCanvasId("");
ShaderManager *ShaderManager::getInstance(const string &canvasId) {
if (_instances.find(canvasId) == _instances.end()) {
_instances[canvasId] = new ShaderManager();
}
return _instances[canvasId];
}
ShaderManager *ShaderManager::getInstance() {
return getInstance(_currentCanvasId);
}
ShaderManager::ShaderManager() {
_flatRenderingShader = new GlShaderProgram();
_flatRenderingShader->addShaderFromSourceCode(GlShader::Vertex, defaultVertexShaderSrc);
_flatRenderingShader->addShaderFromSourceCode(GlShader::Fragment, defaultFragmentShaderSrc);
_flatRenderingShader->link();
if (!_flatRenderingShader->isLinked()) {
_flatRenderingShader->printInfoLog();
}
_blinnPhongRenderingShader = new GlShaderProgram();
_blinnPhongRenderingShader->addShaderFromSourceCode(GlShader::Vertex, blinnPhongVertexShaderSrc);
_blinnPhongRenderingShader->addShaderFromSourceCode(GlShader::Fragment, blinnPhongFragmentShaderSrc);
_blinnPhongRenderingShader->link();
if (!_blinnPhongRenderingShader->isLinked()) {
_blinnPhongRenderingShader->printInfoLog();
}
}
string ShaderManager::getFXAAFunctionsSource() {
return fxaaFunctionsSrc;
}
<commit_msg>fix shader compilation on Desktop OpenGL<commit_after>#include "ShaderManager.h"
#include "GlShaderProgram.h"
using namespace std;
static string defaultVertexShaderSrc =
#ifdef __EMSCRIPTEN__
"precision highp float;\n"
"precision highp int;\n"
#else
"#version 120\n"
#endif
"uniform mat4 u_modelviewMatrix;"
"uniform mat4 u_projectionMatrix;"
"uniform vec4 u_color;"
"uniform bool u_globalColor;"
"uniform bool u_globalTexture;"
"uniform bool u_textureActivated;"
"uniform bool u_pointsRendering;"
"uniform bool u_globalPointSize;"
"uniform float u_pointSize;"
"uniform vec4 u_texCoordOffsets;"
"attribute vec3 a_position;"
"attribute vec4 a_color;"
"attribute vec2 a_texCoord;"
"attribute float a_pointSize;"
"attribute vec4 a_texCoordOffsets;"
"varying vec4 v_color;"
"varying vec2 v_texCoord;"
"varying vec4 v_texCoordOffsets;"
"void main() {"
" gl_Position = u_projectionMatrix * u_modelviewMatrix * vec4(a_position, 1.0);"
" if (u_globalColor) {"
" v_color = u_color;"
" } else {"
" v_color = a_color;"
" }"
" if (u_textureActivated) {"
" v_texCoord = a_texCoord;"
" if (u_globalTexture) {"
" v_texCoordOffsets = u_texCoordOffsets;"
" } else {"
" v_texCoordOffsets = a_texCoordOffsets;"
" }"
" }"
" if (u_pointsRendering) {"
" if (u_globalPointSize) {"
" gl_PointSize = u_pointSize;"
" } else {"
" gl_PointSize = a_pointSize;"
" }"
" }"
"}"
;
static string defaultFragmentShaderSrc =
#ifdef __EMSCRIPTEN__
"precision highp float;\n"
"precision highp int;\n"
#else
"#version 120\n"
#endif
"uniform bool u_textureActivated;"
"uniform sampler2D u_texture;"
"varying vec4 v_color;"
"varying vec2 v_texCoord;"
"varying vec4 v_texCoordOffsets;"
"void main() {"
" if (!u_textureActivated) {"
" gl_FragColor = v_color;"
" } else {"
" vec2 texCoord = vec2(v_texCoordOffsets.x + v_texCoord.x * (v_texCoordOffsets.z - v_texCoordOffsets.x),"
" v_texCoordOffsets.y + v_texCoord.y * (v_texCoordOffsets.w - v_texCoordOffsets.y));"
" gl_FragColor = v_color * texture2D(u_texture, texCoord);"
" }"
"}"
;
static string blinnPhongVertexShaderSrc =
#ifdef __EMSCRIPTEN__
"precision highp float;\n"
"precision highp int;\n"
#else
"#version 120\n"
#endif
"uniform mat4 u_modelviewMatrix;"
"uniform mat4 u_projectionMatrix;"
"uniform mat4 u_normalMatrix;"
"uniform bool u_globalColor;"
"uniform bool u_textureActivated;"
"uniform vec3 u_eyePosition;"
"uniform vec4 u_lightPosition;"
"uniform float u_lightConstantAttenuation;"
"uniform float u_lightLinearAttenuation;"
"uniform float u_lightQuadraticAttenuation;"
"uniform vec4 u_lightModelAmbientColor;"
"uniform vec4 u_lightAmbientColor;"
"uniform vec4 u_lightDiffuseColor;"
"uniform vec4 u_materialAmbientColor;"
"uniform vec4 u_materialDiffuseColor;"
"attribute vec3 a_position;"
"attribute vec4 a_color;"
"attribute vec2 a_texCoord;"
"attribute vec3 a_normal;"
"varying vec4 v_diffuseColor;"
"varying vec4 v_ambientGlobalColor;"
"varying vec4 v_ambientColor;"
"varying vec3 v_normal;"
"varying vec3 v_lightDir;"
"varying vec3 v_halfVector;"
"varying float v_attenuation;"
"varying vec2 v_texCoord;"
"void main(){"
" v_normal = normalize(mat3(u_normalMatrix) * a_normal);"
" vec4 pos = u_modelviewMatrix * vec4(a_position, 1.0);"
" vec3 lightVec = u_lightPosition.xyz-pos.xyz;"
" if (u_lightPosition.w == 0.0) {"
" lightVec = -u_lightPosition.xyz;"
" }"
" v_lightDir = normalize(lightVec);"
" float dist = length(lightVec);"
" v_attenuation = 1.0 / (u_lightConstantAttenuation +"
" u_lightLinearAttenuation * dist +"
" u_lightQuadraticAttenuation * dist * dist);"
" v_halfVector = u_eyePosition + u_lightPosition.xyz;"
" v_halfVector = normalize(v_halfVector);"
" if (u_globalColor) {"
" v_diffuseColor = u_lightDiffuseColor * u_materialDiffuseColor;"
" } else {"
" v_diffuseColor = u_lightDiffuseColor * a_color;"
" }"
" v_ambientColor = u_lightAmbientColor * u_materialAmbientColor;"
" v_ambientGlobalColor = u_lightModelAmbientColor * u_materialAmbientColor;"
" gl_Position = u_projectionMatrix * pos;"
" if (u_textureActivated) {"
" v_texCoord = a_texCoord;"
" }"
"}"
;
static string blinnPhongFragmentShaderSrc =
#ifdef __EMSCRIPTEN__
"precision highp float;\n"
"precision highp int;\n"
#else
"#version 120\n"
#endif
"uniform bool u_flatShading;"
"uniform bool u_textureActivated;"
"uniform sampler2D u_texture;"
"uniform vec4 u_lightSpecularColor;"
"uniform vec4 u_materialSpecularColor;"
"uniform float u_materialShininess;"
"varying vec4 v_diffuseColor;"
"varying vec4 v_ambientGlobalColor;"
"varying vec4 v_ambientColor;"
"varying vec3 v_normal;"
"varying vec3 v_lightDir;"
"varying vec3 v_halfVector;"
"varying float v_attenuation;"
"varying vec2 v_texCoord;"
"void main() {"
" if (u_flatShading) {"
" gl_FragColor = v_diffuseColor;"
" if (u_textureActivated) {"
" gl_FragColor *= texture2D(u_texture, v_texCoord);"
" }"
" return;"
" }"
" vec3 normal = normalize(v_normal);"
" vec4 color = v_ambientGlobalColor + v_ambientColor;"
" float NdotL = max(dot(normal,normalize(v_lightDir)),0.0);"
" if (NdotL > 0.0) {"
" color += v_attenuation * v_diffuseColor * NdotL;"
" vec3 halfV = normalize(v_halfVector);"
" float NdotHV = max(dot(normal, halfV), 0.0);"
" color += v_attenuation * u_materialSpecularColor * u_lightSpecularColor * pow(NdotHV, u_materialShininess);"
" }"
" if (u_textureActivated) {"
" color *= texture2D(u_texture, v_texCoord);"
" }"
" gl_FragColor = color;"
"}"
;
/**
https://github.com/mattdesl/glsl-fxaa
The MIT License (MIT) Copyright (c) 2014 Matt DesLauriers
Basic FXAA implementation based on the code on geeks3d.com with the
modification that the texture2DLod stuff was removed since it's
unsupported by WebGL.
--
From:
https://github.com/mitsuhiko/webgl-meincraft
Copyright (c) 2011 by Armin Ronacher.
Some 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.
* The names of the contributors may not 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.
*/
static string fxaaFunctionsSrc =
"\n#ifndef FXAA_REDUCE_MIN\n"
" #define FXAA_REDUCE_MIN (1.0/ 128.0)\n"
"#endif\n"
"#ifndef FXAA_REDUCE_MUL\n"
" #define FXAA_REDUCE_MUL (1.0 / 8.0)\n"
"#endif\n"
"#ifndef FXAA_SPAN_MAX\n"
" #define FXAA_SPAN_MAX 8.0\n"
"#endif\n"
//optimized version for mobile, where dependent
//texture reads can be a bottleneck
"vec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,"
" vec2 v_rgbNW, vec2 v_rgbNE,"
" vec2 v_rgbSW, vec2 v_rgbSE,"
" vec2 v_rgbM) {"
" vec4 color;"
" vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);"
" vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;"
" vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;"
" vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;"
" vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;"
" vec4 texColor = texture2D(tex, v_rgbM);"
" vec3 rgbM = texColor.xyz;"
" vec3 luma = vec3(0.299, 0.587, 0.114);"
" float lumaNW = dot(rgbNW, luma);"
" float lumaNE = dot(rgbNE, luma);"
" float lumaSW = dot(rgbSW, luma);"
" float lumaSE = dot(rgbSE, luma);"
" float lumaM = dot(rgbM, luma);"
" float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));"
" float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));"
" vec2 dir;"
" dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));"
" dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));"
" float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *"
" (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);"
" float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);"
" dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),"
" max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),"
" dir * rcpDirMin)) * inverseVP;"
" vec3 rgbA = 0.5 * ("
" texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +"
" texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);"
" vec3 rgbB = rgbA * 0.5 + 0.25 * ("
" texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +"
" texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);"
" float lumaB = dot(rgbB, luma);"
" if ((lumaB < lumaMin) || (lumaB > lumaMax)) {"
" color = vec4(rgbA, texColor.a);"
" } else {"
" color = vec4(rgbB, texColor.a);"
" }"
" return color;"
"}"
"void texcoords(vec2 fragCoord, vec2 resolution,"
" out vec2 v_rgbNW, out vec2 v_rgbNE,"
" out vec2 v_rgbSW, out vec2 v_rgbSE,"
" out vec2 v_rgbM) {"
" vec2 inverseVP = 1.0 / resolution.xy;"
" v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;"
" v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;"
" v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;"
" v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;"
" v_rgbM = vec2(fragCoord * inverseVP);"
"}"
"vec4 applyFXAA(sampler2D tex, vec2 fragCoord, vec2 resolution) {"
" vec2 v_rgbNW;"
" vec2 v_rgbNE;"
" vec2 v_rgbSW;"
" vec2 v_rgbSE;"
" vec2 v_rgbM;"
//compute the texture coords
" texcoords(fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);"
//compute FXAA
" return fxaa(tex, fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);"
"}"
;
map<string, ShaderManager *> ShaderManager::_instances;
string ShaderManager::_currentCanvasId("");
ShaderManager *ShaderManager::getInstance(const string &canvasId) {
if (_instances.find(canvasId) == _instances.end()) {
_instances[canvasId] = new ShaderManager();
}
return _instances[canvasId];
}
ShaderManager *ShaderManager::getInstance() {
return getInstance(_currentCanvasId);
}
ShaderManager::ShaderManager() {
_flatRenderingShader = new GlShaderProgram();
_flatRenderingShader->addShaderFromSourceCode(GlShader::Vertex, defaultVertexShaderSrc);
_flatRenderingShader->addShaderFromSourceCode(GlShader::Fragment, defaultFragmentShaderSrc);
_flatRenderingShader->link();
if (!_flatRenderingShader->isLinked()) {
_flatRenderingShader->printInfoLog();
}
_blinnPhongRenderingShader = new GlShaderProgram();
_blinnPhongRenderingShader->addShaderFromSourceCode(GlShader::Vertex, blinnPhongVertexShaderSrc);
_blinnPhongRenderingShader->addShaderFromSourceCode(GlShader::Fragment, blinnPhongFragmentShaderSrc);
_blinnPhongRenderingShader->link();
if (!_blinnPhongRenderingShader->isLinked()) {
_blinnPhongRenderingShader->printInfoLog();
}
}
string ShaderManager::getFXAAFunctionsSource() {
return fxaaFunctionsSrc;
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <sstream>
#include <stdlib.h>
#include <Examples/BouncingBalls/AddRandomSphereBehavior.h>
#include <SurgSim/Framework/Behavior.h>
#include <SurgSim/Framework/Scene.h>
#include <SurgSim/Framework/SceneElement.h>
#include <SurgSim/Blocks/SphereElement.h>
#include <SurgSim/Math/Vector.h>
using SurgSim::Blocks::SphereElement;
using SurgSim::Framework::Behavior;
using SurgSim::Framework::SceneElement;
using SurgSim::Math::Vector3d;
/// \file
/// A Behavior that creates randomly positioned SphereElements at a fixed rate.
/// \sa SurgSim::Blocks::SphereElement
namespace SurgSim
{
namespace Blocks
{
AddRandomSphereBehavior::AddRandomSphereBehavior():
Behavior("DynamicallyAddSphereElement"), m_totalTime(0.0), m_numElements(0), m_distribution_xz(0.0, 1.0), m_distribution_y(1.0, 2.0)
{
}
AddRandomSphereBehavior::~AddRandomSphereBehavior()
{
}
bool AddRandomSphereBehavior::doInitialize()
{
return true;
}
bool AddRandomSphereBehavior::doWakeUp()
{
return true;
}
void AddRandomSphereBehavior::update(double dt)
{
// Accumulate the time steps since the previous sphere was created.
m_totalTime += dt;
if (m_totalTime > 3.0)
{
m_totalTime = 0.0;
std::stringstream ss;
ss << ++ m_numElements;
// Generate a random position.
double m_x = m_distribution_xz(m_generator);
double m_y = m_distribution_y(m_generator);
double m_z = m_distribution_xz(m_generator);
std::string name = "sphereId_" + ss.str();
// Create the pose, with no rotation and the previously determined position.
SurgSim::Math::RigidTransform3d pose = SurgSim::Math::makeRigidTransform
(SurgSim::Math::Quaterniond::Identity(), Vector3d(m_x, m_y, m_z));
// Create the SphereElement.
std::shared_ptr<SceneElement> m_element = std::make_shared<SphereElement>(name, pose);
// Add the SphereElement to the Scene.
getScene()->addSceneElement(m_element);
}
}
}; // namespace Blocks
}; // namespace SurgSim<commit_msg>Fix too-long line.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include <sstream>
#include <stdlib.h>
#include <Examples/BouncingBalls/AddRandomSphereBehavior.h>
#include <SurgSim/Framework/Behavior.h>
#include <SurgSim/Framework/Scene.h>
#include <SurgSim/Framework/SceneElement.h>
#include <SurgSim/Blocks/SphereElement.h>
#include <SurgSim/Math/Vector.h>
using SurgSim::Blocks::SphereElement;
using SurgSim::Framework::Behavior;
using SurgSim::Framework::SceneElement;
using SurgSim::Math::Vector3d;
/// \file
/// A Behavior that creates randomly positioned SphereElements at a fixed rate.
/// \sa SurgSim::Blocks::SphereElement
namespace SurgSim
{
namespace Blocks
{
AddRandomSphereBehavior::AddRandomSphereBehavior():
Behavior("DynamicallyAddSphereElement"), m_totalTime(0.0), m_numElements(0),
m_distribution_xz(0.0, 1.0), m_distribution_y(1.0, 2.0)
{
}
AddRandomSphereBehavior::~AddRandomSphereBehavior()
{
}
bool AddRandomSphereBehavior::doInitialize()
{
return true;
}
bool AddRandomSphereBehavior::doWakeUp()
{
return true;
}
void AddRandomSphereBehavior::update(double dt)
{
// Accumulate the time steps since the previous sphere was created.
m_totalTime += dt;
if (m_totalTime > 3.0)
{
m_totalTime = 0.0;
std::stringstream ss;
ss << ++ m_numElements;
// Generate a random position.
double m_x = m_distribution_xz(m_generator);
double m_y = m_distribution_y(m_generator);
double m_z = m_distribution_xz(m_generator);
std::string name = "sphereId_" + ss.str();
// Create the pose, with no rotation and the previously determined position.
SurgSim::Math::RigidTransform3d pose = SurgSim::Math::makeRigidTransform
(SurgSim::Math::Quaterniond::Identity(), Vector3d(m_x, m_y, m_z));
// Create the SphereElement.
std::shared_ptr<SceneElement> m_element = std::make_shared<SphereElement>(name, pose);
// Add the SphereElement to the Scene.
getScene()->addSceneElement(m_element);
}
}
}; // namespace Blocks
}; // namespace SurgSim<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRotationFilter.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.
=========================================================================*/
#include "vtkRotationFilter.h"
#include "vtkCellData.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnstructuredGrid.h"
#include "vtkMath.h"
vtkCxxRevisionMacro(vtkRotationFilter, "1.5");
vtkStandardNewMacro(vtkRotationFilter);
//---------------------------------------------------------------------------
vtkRotationFilter::vtkRotationFilter()
{
this->Axis = 0;
this->CopyInput = 0;
this->Center[0] = this->Center[1] = this->Center[2] = 0;
this->NumberOfCopies = 0;
this->Angle = 0;
}
//---------------------------------------------------------------------------
vtkRotationFilter::~vtkRotationFilter()
{
}
//---------------------------------------------------------------------------
void vtkRotationFilter::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Axis: " << this->Axis << endl;
os << indent << "CopyInput: " << this->CopyInput << endl;
os << indent << "Center: (" << this->Center[0] << "," << this->Center[1]
<< "," << this->Center[2] << ")" << endl;
os << indent << "NumberOfCopies: " << this->NumberOfCopies << endl;
os << indent << "Angle: " << this->Angle << endl;
}
//---------------------------------------------------------------------------
int vtkRotationFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType i;
vtkPointData *inPD = input->GetPointData();
vtkPointData *outPD = output->GetPointData();
vtkCellData *inCD = input->GetCellData();
vtkCellData *outCD = output->GetCellData();
double tuple[3];
vtkPoints *outPoints;
double point[3], center[3];
int ptId, cellId, j, k;
vtkGenericCell *cell = vtkGenericCell::New();
vtkIdList *ptIds = vtkIdList::New();
outPoints = vtkPoints::New();
vtkIdType numPts = input->GetNumberOfPoints();
vtkIdType numCells = input->GetNumberOfCells();
if (!this->GetNumberOfCopies())
{
vtkErrorMacro("No number of copy set!");
return 1;
}
if (this->CopyInput)
{
outPoints->Allocate((this->CopyInput + this->GetNumberOfCopies()) * numPts);
output->Allocate((this->CopyInput + this->GetNumberOfCopies()) * numPts);
}
else
{
outPoints->Allocate( this->GetNumberOfCopies() * numPts);
output->Allocate( this->GetNumberOfCopies() * numPts);
}
outPD->CopyAllocate(inPD);
outCD->CopyAllocate(inCD);
vtkDataArray *inPtVectors, *outPtVectors, *inPtNormals, *outPtNormals;
vtkDataArray *inCellVectors, *outCellVectors, *inCellNormals;
vtkDataArray *outCellNormals;
inPtVectors = inPD->GetVectors();
outPtVectors = outPD->GetVectors();
inPtNormals = inPD->GetNormals();
outPtNormals = outPD->GetNormals();
inCellVectors = inCD->GetVectors();
outCellVectors = outCD->GetVectors();
inCellNormals = inCD->GetNormals();
outCellNormals = outCD->GetNormals();
// Copy first points.
if (this->CopyInput)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId = outPoints->InsertNextPoint(point);
outPD->CopyData(inPD, i, ptId);
}
}
// Rotate points.
double angle = this->GetAngle()*vtkMath::DegreesToRadians();
this->GetCenter(center);
switch (this->Axis)
{
case USE_X:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint((point[0]-center[0]),
(point[1]-center[1])*cos(angle*(1+k)) - (point[2]-center[2])*sin(angle*(1+k)),
(point[1]-center[1])*sin(angle*(1+k)) + (point[2]-center[2])*cos(angle*(1+k)));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
case USE_Y:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint((point[0]-center[0])*cos(angle*(1+k)) + (point[2]-center[2])*sin(angle*(1+k)),
(point[1]-center[1]),
-(point[0]-center[0])*sin(angle*(1+k)) + (point[2]-center[2])*cos(angle*(1+k)));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
case USE_Z:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint( (point[0]-center[0])*cos(angle*(1+k)) - (point[1]-center[1])*sin(angle*(1+k)),
(point[0]-center[0])*sin(angle*(1+k)) + (point[1]-center[1])*cos(angle*(1+k)),
(point[2]-center[2]));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
}
int numCellPts, cellType;
vtkIdType *newCellPts;
vtkIdList *cellPts;
// Copy original cells.
if (this->CopyInput)
{
for (i = 0; i < numCells; i++)
{
input->GetCellPoints(i, ptIds);
output->InsertNextCell(input->GetCellType(i), ptIds);
outCD->CopyData(inCD, i, i);
}
}
// Generate rotated cells.
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numCells; i++)
{
input->GetCellPoints(i, ptIds);
input->GetCell(i, cell);
numCellPts = cell->GetNumberOfPoints();
cellType = cell->GetCellType();
cellPts = cell->GetPointIds();
// Triangle strips with even number of triangles have
// to be handled specially. A degenerate triangle is
// introduce to flip all the triangles properly.
if (cellType == VTK_TRIANGLE_STRIP && numCellPts % 2 == 0)
{
numCellPts++;
newCellPts = new vtkIdType[numCellPts];
newCellPts[0] = cellPts->GetId(0) + numPts;
newCellPts[1] = cellPts->GetId(2) + numPts;
newCellPts[2] = cellPts->GetId(1) + numPts;
newCellPts[3] = cellPts->GetId(2) + numPts;
for (j = 4; j < numCellPts; j++)
{
newCellPts[j] = cellPts->GetId(j-1) + numPts*k;
if (this->CopyInput)
{
newCellPts[j] += numPts;
}
}
}
else
{
newCellPts = new vtkIdType[numCellPts];
for (j = numCellPts-1; j >= 0; j--)
{
newCellPts[numCellPts-1-j] = cellPts->GetId(j) + numPts*k;
if (this->CopyInput)
{
newCellPts[numCellPts-1-j] += numPts;
}
}
}
cellId = output->InsertNextCell(cellType, numCellPts, newCellPts);
delete [] newCellPts;
outCD->CopyData(inCD, i, cellId);
if (inCellVectors)
{
inCellVectors->GetTuple(i, tuple);
outCellVectors->SetTuple(cellId, tuple);
}
if (inCellNormals)
{
inCellNormals->GetTuple(i, tuple);
outCellNormals->SetTuple(cellId, tuple);
}
}
}
cell->Delete();
ptIds->Delete();
output->SetPoints(outPoints);
outPoints->Delete();
output->CheckAttributes();
return 1;
}
int vtkRotationFilter::FillInputPortInformation(int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
return 1;
}
<commit_msg>BUG: remove leaks when NumberOfCopies is 0<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRotationFilter.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.
=========================================================================*/
#include "vtkRotationFilter.h"
#include "vtkCellData.h"
#include "vtkGenericCell.h"
#include "vtkIdList.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnstructuredGrid.h"
#include "vtkMath.h"
vtkCxxRevisionMacro(vtkRotationFilter, "1.6");
vtkStandardNewMacro(vtkRotationFilter);
//---------------------------------------------------------------------------
vtkRotationFilter::vtkRotationFilter()
{
this->Axis = 0;
this->CopyInput = 0;
this->Center[0] = this->Center[1] = this->Center[2] = 0;
this->NumberOfCopies = 0;
this->Angle = 0;
}
//---------------------------------------------------------------------------
vtkRotationFilter::~vtkRotationFilter()
{
}
//---------------------------------------------------------------------------
void vtkRotationFilter::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Axis: " << this->Axis << endl;
os << indent << "CopyInput: " << this->CopyInput << endl;
os << indent << "Center: (" << this->Center[0] << "," << this->Center[1]
<< "," << this->Center[2] << ")" << endl;
os << indent << "NumberOfCopies: " << this->NumberOfCopies << endl;
os << indent << "Angle: " << this->Angle << endl;
}
//---------------------------------------------------------------------------
int vtkRotationFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and ouptut
vtkDataSet *input = vtkDataSet::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkIdType i;
vtkPointData *inPD = input->GetPointData();
vtkPointData *outPD = output->GetPointData();
vtkCellData *inCD = input->GetCellData();
vtkCellData *outCD = output->GetCellData();
if (!this->GetNumberOfCopies())
{
vtkErrorMacro("No number of copy set!");
return 1;
}
double tuple[3];
vtkPoints *outPoints;
double point[3], center[3];
int ptId, cellId, j, k;
vtkGenericCell *cell = vtkGenericCell::New();
vtkIdList *ptIds = vtkIdList::New();
outPoints = vtkPoints::New();
vtkIdType numPts = input->GetNumberOfPoints();
vtkIdType numCells = input->GetNumberOfCells();
if (this->CopyInput)
{
outPoints->Allocate((this->CopyInput + this->GetNumberOfCopies()) * numPts);
output->Allocate((this->CopyInput + this->GetNumberOfCopies()) * numPts);
}
else
{
outPoints->Allocate( this->GetNumberOfCopies() * numPts);
output->Allocate( this->GetNumberOfCopies() * numPts);
}
outPD->CopyAllocate(inPD);
outCD->CopyAllocate(inCD);
vtkDataArray *inPtVectors, *outPtVectors, *inPtNormals, *outPtNormals;
vtkDataArray *inCellVectors, *outCellVectors, *inCellNormals;
vtkDataArray *outCellNormals;
inPtVectors = inPD->GetVectors();
outPtVectors = outPD->GetVectors();
inPtNormals = inPD->GetNormals();
outPtNormals = outPD->GetNormals();
inCellVectors = inCD->GetVectors();
outCellVectors = outCD->GetVectors();
inCellNormals = inCD->GetNormals();
outCellNormals = outCD->GetNormals();
// Copy first points.
if (this->CopyInput)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId = outPoints->InsertNextPoint(point);
outPD->CopyData(inPD, i, ptId);
}
}
// Rotate points.
double angle = this->GetAngle()*vtkMath::DegreesToRadians();
this->GetCenter(center);
switch (this->Axis)
{
case USE_X:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint((point[0]-center[0]),
(point[1]-center[1])*cos(angle*(1+k)) - (point[2]-center[2])*sin(angle*(1+k)),
(point[1]-center[1])*sin(angle*(1+k)) + (point[2]-center[2])*cos(angle*(1+k)));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
case USE_Y:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint((point[0]-center[0])*cos(angle*(1+k)) + (point[2]-center[2])*sin(angle*(1+k)),
(point[1]-center[1]),
-(point[0]-center[0])*sin(angle*(1+k)) + (point[2]-center[2])*cos(angle*(1+k)));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
case USE_Z:
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numPts; i++)
{
input->GetPoint(i, point);
ptId =
outPoints->InsertNextPoint( (point[0]-center[0])*cos(angle*(1+k)) - (point[1]-center[1])*sin(angle*(1+k)),
(point[0]-center[0])*sin(angle*(1+k)) + (point[1]-center[1])*cos(angle*(1+k)),
(point[2]-center[2]));
outPD->CopyData(inPD, i, ptId);
if (inPtVectors)
{
inPtVectors->GetTuple(i, tuple);
outPtVectors->SetTuple(ptId, tuple);
}
if (inPtNormals)
{
inPtNormals->GetTuple(i, tuple);
outPtNormals->SetTuple(ptId, tuple);
}
}
}
break;
}
int numCellPts, cellType;
vtkIdType *newCellPts;
vtkIdList *cellPts;
// Copy original cells.
if (this->CopyInput)
{
for (i = 0; i < numCells; i++)
{
input->GetCellPoints(i, ptIds);
output->InsertNextCell(input->GetCellType(i), ptIds);
outCD->CopyData(inCD, i, i);
}
}
// Generate rotated cells.
for (k = 0; k < this->GetNumberOfCopies(); k++)
{
for (i = 0; i < numCells; i++)
{
input->GetCellPoints(i, ptIds);
input->GetCell(i, cell);
numCellPts = cell->GetNumberOfPoints();
cellType = cell->GetCellType();
cellPts = cell->GetPointIds();
// Triangle strips with even number of triangles have
// to be handled specially. A degenerate triangle is
// introduce to flip all the triangles properly.
if (cellType == VTK_TRIANGLE_STRIP && numCellPts % 2 == 0)
{
numCellPts++;
newCellPts = new vtkIdType[numCellPts];
newCellPts[0] = cellPts->GetId(0) + numPts;
newCellPts[1] = cellPts->GetId(2) + numPts;
newCellPts[2] = cellPts->GetId(1) + numPts;
newCellPts[3] = cellPts->GetId(2) + numPts;
for (j = 4; j < numCellPts; j++)
{
newCellPts[j] = cellPts->GetId(j-1) + numPts*k;
if (this->CopyInput)
{
newCellPts[j] += numPts;
}
}
}
else
{
newCellPts = new vtkIdType[numCellPts];
for (j = numCellPts-1; j >= 0; j--)
{
newCellPts[numCellPts-1-j] = cellPts->GetId(j) + numPts*k;
if (this->CopyInput)
{
newCellPts[numCellPts-1-j] += numPts;
}
}
}
cellId = output->InsertNextCell(cellType, numCellPts, newCellPts);
delete [] newCellPts;
outCD->CopyData(inCD, i, cellId);
if (inCellVectors)
{
inCellVectors->GetTuple(i, tuple);
outCellVectors->SetTuple(cellId, tuple);
}
if (inCellNormals)
{
inCellNormals->GetTuple(i, tuple);
outCellNormals->SetTuple(cellId, tuple);
}
}
}
cell->Delete();
ptIds->Delete();
output->SetPoints(outPoints);
outPoints->Delete();
output->CheckAttributes();
return 1;
}
int vtkRotationFilter::FillInputPortInformation(int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet");
return 1;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbPerBandVectorImageFilter.h"
// Software Guide : BeginLatex
//
// This example demonstrates the use of the
// \doxygen{otb}{OrthoRectificationFilter}. This filter is intended to
// orthorectify images which are in a distributor format with the
// appropriate meta-data describing the sensor model. In this example,
// we will choose to use an UTM projection for the output image.
//
// The first step toward the use of these filters is to include the
// proper header files: the one for the ortho-rectification filter and
// the one defining the different projections available in OTB.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbOrthoRectificationFilter.h"
#include "otbMapProjections.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[])
{
if (argc != 11)
{
std::cout << argv[0] <<
" <input_filename> <output_filename> <utm zone> <hemisphere N/S> <x_ground_upper_left_corner> <y_ground_upper_left_corner> <x_Size> <y_Size> <x_groundSamplingDistance> <y_groundSamplingDistance> (should be negative since origin is upper left)>"
<< std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// We will start by defining the types for the images, the image file
// reader and the image file writer. The writer will be a
// \doxygen{otb}{StreamingImageFileWriter} which will allow us to set
// the number of stream divisions we want to apply when writing the
// output image, which can be very large.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::Image<int, 2> ImageType;
typedef otb::VectorImage<int, 2> VectorImageType;
typedef otb::ImageFileReader<VectorImageType> ReaderType;
typedef otb::StreamingImageFileWriter<VectorImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName(argv[1]);
writer->SetFileName(argv[2]);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now proceed to declare the type for the ortho-rectification
// filter. The class \doxygen{otb}{OrthoRectificationFilter} is
// templated over the input and the output image types as well as over
// the cartographic projection. We define therefore the
// type of the projection we want, which is an UTM projection for this case.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::UtmInverseProjection utmMapProjectionType;
typedef otb::OrthoRectificationFilter<ImageType, ImageType,
utmMapProjectionType>
OrthoRectifFilterType;
OrthoRectifFilterType::Pointer orthoRectifFilter =
OrthoRectifFilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we need to
// instanciate the map projection, set the {\em zone} and {\em hemisphere}
// parameters and pass this projection to the orthorectification filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
utmMapProjectionType::Pointer utmMapProjection =
utmMapProjectionType::New();
utmMapProjection->SetZone(atoi(argv[3]));
utmMapProjection->SetHemisphere(*(argv[4]));
orthoRectifFilter->SetMapProjection(utmMapProjection);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Wiring the orthorectification filter into a PerBandImageFilter allows
// to orthrectify images with multiple bands seamlesly.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::PerBandVectorImageFilter<VectorImageType,
VectorImageType,
OrthoRectifFilterType>
PerBandFilterType;
PerBandFilterType::Pointer perBandFilter = PerBandFilterType::New();
perBandFilter->SetFilter(orthoRectifFilter);
perBandFilter->SetInput(reader->GetOutput());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Using the user-provided information, we define the output region
// for the image generated by the orthorectification filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::IndexType start;
start[0] = 0;
start[1] = 0;
orthoRectifFilter->SetOutputStartIndex(start);
ImageType::SizeType size;
size[0] = atoi(argv[7]);
size[1] = atoi(argv[8]);
orthoRectifFilter->SetSize(size);
ImageType::SpacingType spacing;
spacing[0] = atof(argv[9]);
spacing[1] = atof(argv[10]);
orthoRectifFilter->SetOutputSpacing(spacing);
ImageType::PointType origin;
origin[0] = strtod(argv[5], NULL);
origin[1] = strtod(argv[6], NULL);
orthoRectifFilter->SetOutputOrigin(origin);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now set plug the ortho-rectification filter to the writer
// and set the number of tiles we want to split the output image in
// for the writing step.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->SetInput(perBandFilter->GetOutput());
writer->SetTilingStreamDivisions();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we trigger the pipeline execution by calling the
// \code{Update()} method on the writer. Please note that the
// ortho-rectification filter is derived from the
// \doxygen{otb}{StreamingResampleImageFilter} in order to be able to
// compute the input image regions which are needed to build the
// output image. Since the resampler applies a geometric
// transformation (scale, rotation, etc.), this region computation is
// not trivial.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->Update();
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<commit_msg>ENH : update the method name due to StreamingResampleImageFilter changes<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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 notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbStreamingImageFileWriter.h"
#include "otbPerBandVectorImageFilter.h"
// Software Guide : BeginLatex
//
// This example demonstrates the use of the
// \doxygen{otb}{OrthoRectificationFilter}. This filter is intended to
// orthorectify images which are in a distributor format with the
// appropriate meta-data describing the sensor model. In this example,
// we will choose to use an UTM projection for the output image.
//
// The first step toward the use of these filters is to include the
// proper header files: the one for the ortho-rectification filter and
// the one defining the different projections available in OTB.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbOrthoRectificationFilter.h"
#include "otbMapProjections.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[])
{
if (argc != 11)
{
std::cout << argv[0] <<
" <input_filename> <output_filename> <utm zone> <hemisphere N/S> <x_ground_upper_left_corner> <y_ground_upper_left_corner> <x_Size> <y_Size> <x_groundSamplingDistance> <y_groundSamplingDistance> (should be negative since origin is upper left)>"
<< std::endl;
return EXIT_FAILURE;
}
// Software Guide : BeginLatex
//
// We will start by defining the types for the images, the image file
// reader and the image file writer. The writer will be a
// \doxygen{otb}{StreamingImageFileWriter} which will allow us to set
// the number of stream divisions we want to apply when writing the
// output image, which can be very large.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::Image<int, 2> ImageType;
typedef otb::VectorImage<int, 2> VectorImageType;
typedef otb::ImageFileReader<VectorImageType> ReaderType;
typedef otb::StreamingImageFileWriter<VectorImageType> WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName(argv[1]);
writer->SetFileName(argv[2]);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now proceed to declare the type for the ortho-rectification
// filter. The class \doxygen{otb}{OrthoRectificationFilter} is
// templated over the input and the output image types as well as over
// the cartographic projection. We define therefore the
// type of the projection we want, which is an UTM projection for this case.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::UtmInverseProjection utmMapProjectionType;
typedef otb::OrthoRectificationFilter<ImageType, ImageType,
utmMapProjectionType>
OrthoRectifFilterType;
OrthoRectifFilterType::Pointer orthoRectifFilter =
OrthoRectifFilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Now we need to
// instanciate the map projection, set the {\em zone} and {\em hemisphere}
// parameters and pass this projection to the orthorectification filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
utmMapProjectionType::Pointer utmMapProjection =
utmMapProjectionType::New();
utmMapProjection->SetZone(atoi(argv[3]));
utmMapProjection->SetHemisphere(*(argv[4]));
orthoRectifFilter->SetMapProjection(utmMapProjection);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Wiring the orthorectification filter into a PerBandImageFilter allows
// to orthrectify images with multiple bands seamlesly.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::PerBandVectorImageFilter<VectorImageType,
VectorImageType,
OrthoRectifFilterType>
PerBandFilterType;
PerBandFilterType::Pointer perBandFilter = PerBandFilterType::New();
perBandFilter->SetFilter(orthoRectifFilter);
perBandFilter->SetInput(reader->GetOutput());
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Using the user-provided information, we define the output region
// for the image generated by the orthorectification filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
ImageType::IndexType start;
start[0] = 0;
start[1] = 0;
orthoRectifFilter->SetOutputStartIndex(start);
ImageType::SizeType size;
size[0] = atoi(argv[7]);
size[1] = atoi(argv[8]);
orthoRectifFilter->SetOutputSize(size);
ImageType::SpacingType spacing;
spacing[0] = atof(argv[9]);
spacing[1] = atof(argv[10]);
orthoRectifFilter->SetOutputSpacing(spacing);
ImageType::PointType origin;
origin[0] = strtod(argv[5], NULL);
origin[1] = strtod(argv[6], NULL);
orthoRectifFilter->SetOutputOrigin(origin);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We can now set plug the ortho-rectification filter to the writer
// and set the number of tiles we want to split the output image in
// for the writing step.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->SetInput(perBandFilter->GetOutput());
writer->SetTilingStreamDivisions();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we trigger the pipeline execution by calling the
// \code{Update()} method on the writer. Please note that the
// ortho-rectification filter is derived from the
// \doxygen{otb}{StreamingResampleImageFilter} in order to be able to
// compute the input image regions which are needed to build the
// output image. Since the resampler applies a geometric
// transformation (scale, rotation, etc.), this region computation is
// not trivial.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->Update();
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// $Id$
///**************************************************************************
///* This file is property of and copyright by the *
///* ALICE Experiment at CERN, All rights reserved. *
///* *
///* Primary Authors: Mikolaj Krzewicki, [email protected] *
///* *
///* Permission to use, copy, modify and distribute this software and its *
///* documentation strictly for non-commercial purposes is hereby granted *
///* without fee, provided that the above copyright notice appears in all *
///* copies and that both the copyright notice and this permission notice *
///* appear in the supporting documentation. The authors make no claims *
///* about the suitability of this software for any purpose. It is *
///* provided "as is" without express or implied warranty. *
///**************************************************************************
/// @file AliHLTZMQsource.cxx
/// @author Mikolaj Krzewicki
/// @date
/// @brief HLT ZMQ component implementation. */
///
#include "AliHLTZMQsource.h"
#include "AliHLTErrorGuard.h"
#include "AliLog.h"
#include <TPRegexp.h>
#include "zmq.h"
#include "AliZMQhelpers.h"
using namespace std;
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTZMQsource)
//______________________________________________________________________________
AliHLTZMQsource::AliHLTZMQsource()
: AliHLTComponent()
, fOutputDataTypes()
, fZMQcontext(NULL)
, fZMQin(NULL)
, fZMQsocketType(-1)
, fZMQinConfig("SUB")
, fMessageFilter("")
, fZMQrequestTimeout(1000)
, fZMQneverBlock(kTRUE)
{
}
//______________________________________________________________________________
AliHLTZMQsource::~AliHLTZMQsource()
{
//dtor
zmq_close(fZMQin);
zmq_ctx_destroy(fZMQcontext);
}
//______________________________________________________________________________
const char* AliHLTZMQsource::GetComponentID()
{
// overloaded from AliHLTComponent
return "ZMQsource";
}
//______________________________________________________________________________
void AliHLTZMQsource::GetInputDataTypes(AliHLTComponentDataTypeList& list)
{
// overloaded from AliHLTComponent
list.clear();
list.push_back(kAliHLTAllDataTypes);
}
//______________________________________________________________________________
AliHLTComponentDataType AliHLTZMQsource::GetOutputDataType()
{
// overloaded from AliHLTComponent
return kAliHLTAllDataTypes;
}
////______________________________________________________________________________
//int AliHLTZMQsource::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList)
//{
// // overloaded from AliHLTComponent
// tgtList.assign(fOutputDataTypes.begin(), fOutputDataTypes.end());
// HLTMessage("%s %p provides %d output data types", GetComponentID(), this, fOutputDataTypes.size());
// return fOutputDataTypes.size();
//}
//______________________________________________________________________________
void AliHLTZMQsource::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// overloaded from AliHLTComponent
constBase=1000000;
inputMultiplier=1.0;
}
//______________________________________________________________________________
AliHLTComponent* AliHLTZMQsource::Spawn()
{
// overloaded from AliHLTComponent
return new AliHLTZMQsource;
}
//______________________________________________________________________________
int AliHLTZMQsource::DoInit( int argc, const char** argv )
{
// overloaded from AliHLTComponent: initialization
int retCode=0;
//process arguments
if (ProcessOptionString(GetComponentArgs())<0)
{
HLTFatal("wrong options %s", GetComponentArgs().c_str());
return -1;
}
int rc = 0;
//init ZMQ stuff
fZMQcontext = zmq_ctx_new();
HLTMessage(Form("ctx create rc %i errno %i",rc,errno));
//init ZMQ socket
rc = alizmq_socket_init(fZMQin, fZMQcontext, fZMQinConfig.Data(), 0, 10 );
if (!fZMQin || rc<0)
{
HLTError("cannot initialize ZMQ socket %s, %s",fZMQinConfig.Data(),zmq_strerror(errno));
return -1;
}
//subscribe
rc = zmq_setsockopt(fZMQin, ZMQ_SUBSCRIBE, fMessageFilter.Data(), fMessageFilter.Length());
HLTMessage(Form("socket create ptr %p %s",fZMQin,(rc<0)?zmq_strerror(errno):""));
HLTImportant(Form("ZMQ connected to: %s rc %i %s",fZMQinConfig.Data(),rc,(rc<0)?zmq_strerror(errno):""));
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsource::DoDeinit()
{
// overloaded from AliHLTComponent: cleanup
int retCode=0;
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsource::DoProcessing( const AliHLTComponentEventData& evtData,
const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* outputBuffer,
AliHLTUInt32_t& outputBufferSize,
AliHLTComponentBlockDataList& outputBlocks,
AliHLTComponentEventDoneData*& edd )
{
// overloaded from AliHLTComponent: event processing
int retCode=0;
// process data events only
//if (!IsDataEvent()) return 0;
//init internal
AliHLTUInt32_t outputBufferCapacity = outputBufferSize;
outputBufferSize=0;
int blockSize = 0;
void* block = NULL;
int blockTopicSize=-1;
AliHLTDataTopic blockTopic;
int rc = -1;
//in case we do requests: request first and poll for replies
//if no reply arrives after a timeout period, reset the connection
if (fZMQsocketType==ZMQ_REQ)
{
//send request (header + an empty body for good measure)
HLTMessage("sending request");
zmq_send(fZMQin, fMessageFilter.Data(), fMessageFilter.Length(), ZMQ_SNDMORE);
zmq_send(fZMQin, 0, 0, 0);
//wait for reply
zmq_pollitem_t sockets[] = { {fZMQin, 0, ZMQ_POLLIN, 0} };
rc = zmq_poll( sockets, 1, fZMQrequestTimeout );
if (rc==-1)
{
HLTImportant("request interrupted");
//interrupted, stop processing
return 0;
}
if (! (sockets[0].revents & ZMQ_POLLIN))
{
//if we got no reply reset the connection, probably source died
HLTImportant("request timed out after %i us",fZMQrequestTimeout);
rc = alizmq_socket_init(fZMQin, fZMQcontext, fZMQinConfig.Data(), 0, 10 );
if (rc<0)
{
HLTError("cannot reinitialize ZMQ socket %s, %s",fZMQinConfig.Data(),zmq_strerror(errno));
return -1;
}
//just return normally
return 0;
}
}
int64_t more=0;
size_t moreSize=sizeof(more);
int frameNumber=0;
do //multipart, get all parts
{
frameNumber++;
outputBufferCapacity -= blockSize;
outputBufferSize += blockSize;
block = outputBuffer + outputBufferSize;
//get (fill) the block topic
blockTopicSize = zmq_recv (fZMQin, &blockTopic, sizeof(blockTopic), (fZMQneverBlock)?ZMQ_DONTWAIT:0);
if (blockTopicSize<0 && errno==EAGAIN) break; //nothing on the socket
zmq_getsockopt(fZMQin, ZMQ_RCVMORE, &more, &moreSize);
if (more) {
//get (fill) the block data
blockSize = zmq_recv(fZMQin, block, outputBufferCapacity, (fZMQneverBlock)?ZMQ_DONTWAIT:0);
if (blockSize < 0 && errno == EAGAIN) break; //nothing on the socket
if (blockSize > outputBufferCapacity) {retCode = ENOSPC; break;}//no space for message
zmq_getsockopt(fZMQin, ZMQ_RCVMORE, &more, &moreSize);
}
//if we subscribe AND the body is empty skip the first frame as it is just a subscription topic
//TODO: rethink this logic
if (frameNumber==1 &&
fZMQsocketType==ZMQ_SUB &&
!fMessageFilter.IsNull() &&
blockSize <= 0 ) continue;
if (blockTopicSize <= 0) continue; //empty header, dont push back
HLTMessage(Form("pushing back %s, %i bytes", blockTopic.Description().c_str(), blockSize));
//prepare the component block data descriptor
AliHLTComponentBlockData blockHeader; FillBlockData(blockHeader);
blockHeader.fPtr = outputBuffer;
blockHeader.fOffset = outputBufferSize;
blockHeader.fSize = blockSize;
blockHeader.fDataType = blockTopic.fTopic;
blockHeader.fSpecification = blockTopic.fSpecification;
//register the block in the output buffer list
outputBlocks.push_back(blockHeader);
} while (more==1);
edd=NULL;
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsource::ProcessOption(TString option, TString value)
{
//process option
//to be implemented by the user
if (option.EqualTo("in"))
{
fZMQinConfig = value;
fZMQsocketType = alizmq_socket_type(value.Data());
switch (fZMQsocketType)
{
case ZMQ_REQ:
break;
case ZMQ_PULL:
break;
case ZMQ_SUB:
break;
default:
HLTWarning("use of socket type %s for a source is currently unsupported! (config: %s)", alizmq_socket_name(fZMQsocketType), fZMQinConfig.Data());
return -EINVAL;
}
}
if (option.EqualTo("MessageFilter") || option.EqualTo("subscription"))
{
fMessageFilter = value;
}
if (option.EqualTo("ZMQrequestTimeout"))
{
fZMQrequestTimeout = value.Atoi();
}
if (option.EqualTo("ZMQneverBlock"))
{
if (value.EqualTo("0") || value.EqualTo("no") || value.Contains("false",TString::kIgnoreCase))
fZMQneverBlock = kFALSE;
else if (value.EqualTo("1") || value.EqualTo("yes") || value.Contains("true",TString::kIgnoreCase) )
fZMQneverBlock = kTRUE;
}
return 1;
}
<commit_msg>initialize the default topic with any|any<commit_after>// $Id$
///**************************************************************************
///* This file is property of and copyright by the *
///* ALICE Experiment at CERN, All rights reserved. *
///* *
///* Primary Authors: Mikolaj Krzewicki, [email protected] *
///* *
///* Permission to use, copy, modify and distribute this software and its *
///* documentation strictly for non-commercial purposes is hereby granted *
///* without fee, provided that the above copyright notice appears in all *
///* copies and that both the copyright notice and this permission notice *
///* appear in the supporting documentation. The authors make no claims *
///* about the suitability of this software for any purpose. It is *
///* provided "as is" without express or implied warranty. *
///**************************************************************************
/// @file AliHLTZMQsource.cxx
/// @author Mikolaj Krzewicki
/// @date
/// @brief HLT ZMQ component implementation. */
///
#include "AliHLTZMQsource.h"
#include "AliHLTErrorGuard.h"
#include "AliLog.h"
#include <TPRegexp.h>
#include "zmq.h"
#include "AliZMQhelpers.h"
using namespace std;
/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTZMQsource)
//______________________________________________________________________________
AliHLTZMQsource::AliHLTZMQsource()
: AliHLTComponent()
, fOutputDataTypes()
, fZMQcontext(NULL)
, fZMQin(NULL)
, fZMQsocketType(-1)
, fZMQinConfig("SUB")
, fMessageFilter("")
, fZMQrequestTimeout(1000)
, fZMQneverBlock(kTRUE)
{
}
//______________________________________________________________________________
AliHLTZMQsource::~AliHLTZMQsource()
{
//dtor
zmq_close(fZMQin);
zmq_ctx_destroy(fZMQcontext);
}
//______________________________________________________________________________
const char* AliHLTZMQsource::GetComponentID()
{
// overloaded from AliHLTComponent
return "ZMQsource";
}
//______________________________________________________________________________
void AliHLTZMQsource::GetInputDataTypes(AliHLTComponentDataTypeList& list)
{
// overloaded from AliHLTComponent
list.clear();
list.push_back(kAliHLTAllDataTypes);
}
//______________________________________________________________________________
AliHLTComponentDataType AliHLTZMQsource::GetOutputDataType()
{
// overloaded from AliHLTComponent
return kAliHLTAllDataTypes;
}
////______________________________________________________________________________
//int AliHLTZMQsource::GetOutputDataTypes(AliHLTComponentDataTypeList& tgtList)
//{
// // overloaded from AliHLTComponent
// tgtList.assign(fOutputDataTypes.begin(), fOutputDataTypes.end());
// HLTMessage("%s %p provides %d output data types", GetComponentID(), this, fOutputDataTypes.size());
// return fOutputDataTypes.size();
//}
//______________________________________________________________________________
void AliHLTZMQsource::GetOutputDataSize( unsigned long& constBase, double& inputMultiplier )
{
// overloaded from AliHLTComponent
constBase=1000000;
inputMultiplier=1.0;
}
//______________________________________________________________________________
AliHLTComponent* AliHLTZMQsource::Spawn()
{
// overloaded from AliHLTComponent
return new AliHLTZMQsource;
}
//______________________________________________________________________________
int AliHLTZMQsource::DoInit( int argc, const char** argv )
{
// overloaded from AliHLTComponent: initialization
int retCode=0;
//process arguments
if (ProcessOptionString(GetComponentArgs())<0)
{
HLTFatal("wrong options %s", GetComponentArgs().c_str());
return -1;
}
int rc = 0;
//init ZMQ stuff
fZMQcontext = zmq_ctx_new();
HLTMessage(Form("ctx create rc %i errno %i",rc,errno));
//init ZMQ socket
rc = alizmq_socket_init(fZMQin, fZMQcontext, fZMQinConfig.Data(), 0, 10 );
if (!fZMQin || rc<0)
{
HLTError("cannot initialize ZMQ socket %s, %s",fZMQinConfig.Data(),zmq_strerror(errno));
return -1;
}
//subscribe
rc = zmq_setsockopt(fZMQin, ZMQ_SUBSCRIBE, fMessageFilter.Data(), fMessageFilter.Length());
HLTMessage(Form("socket create ptr %p %s",fZMQin,(rc<0)?zmq_strerror(errno):""));
HLTImportant(Form("ZMQ connected to: %s rc %i %s",fZMQinConfig.Data(),rc,(rc<0)?zmq_strerror(errno):""));
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsource::DoDeinit()
{
// overloaded from AliHLTComponent: cleanup
int retCode=0;
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsource::DoProcessing( const AliHLTComponentEventData& evtData,
const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& /*trigData*/,
AliHLTUInt8_t* outputBuffer,
AliHLTUInt32_t& outputBufferSize,
AliHLTComponentBlockDataList& outputBlocks,
AliHLTComponentEventDoneData*& edd )
{
// overloaded from AliHLTComponent: event processing
int retCode=0;
// process data events only
//if (!IsDataEvent()) return 0;
//init internal
AliHLTUInt32_t outputBufferCapacity = outputBufferSize;
outputBufferSize=0;
int blockSize = 0;
void* block = NULL;
int blockTopicSize=-1;
AliHLTDataTopic blockTopic = kAliHLTAnyDataType | kAliHLTDataOriginAny;
int rc = -1;
//in case we do requests: request first and poll for replies
//if no reply arrives after a timeout period, reset the connection
if (fZMQsocketType==ZMQ_REQ)
{
//send request (header + an empty body for good measure)
HLTMessage("sending request");
zmq_send(fZMQin, fMessageFilter.Data(), fMessageFilter.Length(), ZMQ_SNDMORE);
zmq_send(fZMQin, 0, 0, 0);
//wait for reply
zmq_pollitem_t sockets[] = { {fZMQin, 0, ZMQ_POLLIN, 0} };
rc = zmq_poll( sockets, 1, fZMQrequestTimeout );
if (rc==-1)
{
HLTImportant("request interrupted");
//interrupted, stop processing
return 0;
}
if (! (sockets[0].revents & ZMQ_POLLIN))
{
//if we got no reply reset the connection, probably source died
HLTImportant("request timed out after %i us",fZMQrequestTimeout);
rc = alizmq_socket_init(fZMQin, fZMQcontext, fZMQinConfig.Data(), 0, 10 );
if (rc<0)
{
HLTError("cannot reinitialize ZMQ socket %s, %s",fZMQinConfig.Data(),zmq_strerror(errno));
return -1;
}
//just return normally
return 0;
}
}
int64_t more=0;
size_t moreSize=sizeof(more);
int frameNumber=0;
do //multipart, get all parts
{
frameNumber++;
outputBufferCapacity -= blockSize;
outputBufferSize += blockSize;
block = outputBuffer + outputBufferSize;
//get (fill) the block topic
blockTopicSize = zmq_recv (fZMQin, &blockTopic, sizeof(blockTopic), (fZMQneverBlock)?ZMQ_DONTWAIT:0);
if (blockTopicSize<0 && errno==EAGAIN) break; //nothing on the socket
zmq_getsockopt(fZMQin, ZMQ_RCVMORE, &more, &moreSize);
if (more) {
//get (fill) the block data
blockSize = zmq_recv(fZMQin, block, outputBufferCapacity, (fZMQneverBlock)?ZMQ_DONTWAIT:0);
if (blockSize < 0 && errno == EAGAIN) break; //nothing on the socket
if (blockSize > outputBufferCapacity) {retCode = ENOSPC; break;}//no space for message
zmq_getsockopt(fZMQin, ZMQ_RCVMORE, &more, &moreSize);
}
//if we subscribe AND the body is empty skip the first frame as it is just a subscription topic
//TODO: rethink this logic
if (frameNumber==1 &&
fZMQsocketType==ZMQ_SUB &&
!fMessageFilter.IsNull() &&
blockSize <= 0 ) continue;
if (blockTopicSize <= 0) continue; //empty header, dont push back
HLTMessage(Form("pushing back %s, %i bytes", blockTopic.Description().c_str(), blockSize));
//prepare the component block data descriptor
AliHLTComponentBlockData blockHeader; FillBlockData(blockHeader);
blockHeader.fPtr = outputBuffer;
blockHeader.fOffset = outputBufferSize;
blockHeader.fSize = blockSize;
blockHeader.fDataType = blockTopic.fTopic;
blockHeader.fSpecification = blockTopic.fSpecification;
//register the block in the output buffer list
outputBlocks.push_back(blockHeader);
} while (more==1);
edd=NULL;
return retCode;
}
//______________________________________________________________________________
int AliHLTZMQsource::ProcessOption(TString option, TString value)
{
//process option
//to be implemented by the user
if (option.EqualTo("in"))
{
fZMQinConfig = value;
fZMQsocketType = alizmq_socket_type(value.Data());
switch (fZMQsocketType)
{
case ZMQ_REQ:
break;
case ZMQ_PULL:
break;
case ZMQ_SUB:
break;
default:
HLTWarning("use of socket type %s for a source is currently unsupported! (config: %s)", alizmq_socket_name(fZMQsocketType), fZMQinConfig.Data());
return -EINVAL;
}
}
if (option.EqualTo("MessageFilter") || option.EqualTo("subscription"))
{
fMessageFilter = value;
}
if (option.EqualTo("ZMQrequestTimeout"))
{
fZMQrequestTimeout = value.Atoi();
}
if (option.EqualTo("ZMQneverBlock"))
{
if (value.EqualTo("0") || value.EqualTo("no") || value.Contains("false",TString::kIgnoreCase))
fZMQneverBlock = kFALSE;
else if (value.EqualTo("1") || value.EqualTo("yes") || value.Contains("true",TString::kIgnoreCase) )
fZMQneverBlock = kTRUE;
}
return 1;
}
<|endoftext|> |
<commit_before>//
// C++ Implementation: PresetLoader
//
// Description:
//
//
// Author: Carmelo Piccione <[email protected]>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "PresetLoader.hpp"
#include "Preset.hpp"
#include <iostream>
#include <sstream>
extern "C" {
#include <errno.h>
#include <dirent.h>
}
#include <cassert>
#include "projectM.h"
PresetLoader::PresetLoader(std::string dirname) :m_dirname(dirname)
{
// Do one scan
rescan();
}
void PresetLoader::setScanDirectory(std::string dirname) {
m_dirname = dirname;
}
void PresetLoader::rescan() {
// Clear the directory entry collection
m_entries.clear();
// If directory already opened, close it first
if (m_dir) {
closedir(m_dir);
}
// Allocate a new a stream given the current directory name
if ((m_dir = opendir(m_dirname.c_str())) == NULL) {
handleDirectoryError();
}
std::ostringstream out;
struct dirent * dir_entry;
while ((dir_entry = readdir(m_dir)) != NULL) {
// Convert char * to friendly string
std::string filename(dir_entry->d_name);
// Verify extension is projectm or milkdrop
if (filename.rfind(PROJECTM_FILE_EXTENSION) <= 0
|| filename.rfind(MILKDROP_FILE_EXTENSION) <= 0)
continue;
// Create full path name
out << m_dirname << PATH_SEPARATOR << filename;
// Add to our directory entry collection
m_entries.push_back(out.str());
// We can now toss out the directory entry struct
free(dir_entry);
}
}
std::auto_ptr<Preset> PresetLoader::loadPreset(unsigned int index, const PresetInputs & presetInputs, PresetOutputs & presetOutputs) const {
// Check that index isn't insane
assert(index >= 0);
assert(index < m_entries.size());
// Return a new auto pointer to a present
return std::auto_ptr<Preset>(new Preset(m_entries[index], presetInputs, presetOutputs));
}
void PresetLoader::handleDirectoryError() {
switch (errno) {
case ENOENT:
break;
case ENOMEM:
abort();
case ENOTDIR:
break;
case ENFILE:
std::cerr << "[PresetLoader] Your system has reached its open file limit. Giving up..." << std::endl;
abort();
case EMFILE:
std::cerr << "[PresetLoader] too many files in use by projectM! Bailing!" << std::endl;
abort();
case EACCES:
break;
default:
break;
}
}
<commit_msg>got rid of PROJECTM_FILE_EXTENSION reference error<commit_after>//
// C++ Implementation: PresetLoader
//
// Description:
//
//
// Author: Carmelo Piccione <[email protected]>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "PresetLoader.hpp"
#include "Preset.hpp"
#include <iostream>
#include <sstream>
extern "C" {
#include <errno.h>
#include <dirent.h>
}
#include <cassert>
#include "projectM.h"
const std::string PresetLoader::PROJECTM_FILE_EXTENSION(".prjm");
const std::string PresetLoader::MILKDROP_FILE_EXTENSION(".milk");
PresetLoader::PresetLoader(std::string dirname) :m_dirname(dirname)
{
// Do one scan
rescan();
}
void PresetLoader::setScanDirectory(std::string dirname) {
m_dirname = dirname;
}
void PresetLoader::rescan() {
// Clear the directory entry collection
m_entries.clear();
// If directory already opened, close it first
if (m_dir) {
closedir(m_dir);
}
// Allocate a new a stream given the current directory name
if ((m_dir = opendir(m_dirname.c_str())) == NULL) {
handleDirectoryError();
}
std::ostringstream out;
struct dirent * dir_entry;
while ((dir_entry = readdir(m_dir)) != NULL) {
// Convert char * to friendly string
std::string filename(dir_entry->d_name);
// Verify extension is projectm or milkdrop
if (filename.rfind(PROJECTM_FILE_EXTENSION) <= 0
|| filename.rfind(MILKDROP_FILE_EXTENSION) <= 0)
continue;
// Create full path name
out << m_dirname << PATH_SEPARATOR << filename;
// Add to our directory entry collection
m_entries.push_back(out.str());
// We can now toss out the directory entry struct
free(dir_entry);
}
}
std::auto_ptr<Preset> PresetLoader::loadPreset(unsigned int index, const PresetInputs & presetInputs, PresetOutputs & presetOutputs) const {
// Check that index isn't insane
assert(index >= 0);
assert(index < m_entries.size());
// Return a new auto pointer to a present
return std::auto_ptr<Preset>(new Preset(m_entries[index], presetInputs, presetOutputs));
}
void PresetLoader::handleDirectoryError() {
switch (errno) {
case ENOENT:
break;
case ENOMEM:
abort();
case ENOTDIR:
break;
case ENFILE:
std::cerr << "[PresetLoader] Your system has reached its open file limit. Giving up..." << std::endl;
abort();
case EMFILE:
std::cerr << "[PresetLoader] too many files in use by projectM! Bailing!" << std::endl;
abort();
case EACCES:
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xuser_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
X_STATUS xeExGetXConfigSetting(uint16_t category, uint16_t setting,
void* buffer, uint16_t buffer_size,
uint16_t* required_size) {
uint16_t setting_size = 0;
uint32_t value = 0;
// TODO(benvanik): have real structs here that just get copied from.
// http://free60.org/XConfig
// http://freestyledash.googlecode.com/svn/trunk/Freestyle/Tools/Generic/ExConfig.h
switch (category) {
case 0x0002:
// XCONFIG_SECURED_CATEGORY
switch (setting) {
case 0x0002: // XCONFIG_SECURED_AV_REGION
setting_size = 4;
value = 0x00001000; // USA/Canada
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
case 0x0003:
// XCONFIG_USER_CATEGORY
switch (setting) {
case 0x0001: // XCONFIG_USER_TIME_ZONE_BIAS
case 0x0002: // XCONFIG_USER_TIME_ZONE_STD_NAME
case 0x0003: // XCONFIG_USER_TIME_ZONE_DLT_NAME
case 0x0004: // XCONFIG_USER_TIME_ZONE_STD_DATE
case 0x0005: // XCONFIG_USER_TIME_ZONE_DLT_DATE
case 0x0006: // XCONFIG_USER_TIME_ZONE_STD_BIAS
case 0x0007: // XCONFIG_USER_TIME_ZONE_DLT_BIAS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x0009: // XCONFIG_USER_LANGUAGE
setting_size = 4;
value = 0x00000001; // English
break;
case 0x000A: // XCONFIG_USER_VIDEO_FLAGS
setting_size = 4;
value = 0x00040000;
break;
case 0x000C: // XCONFIG_USER_RETAIL_FLAGS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x000E: // XCONFIG_USER_COUNTRY
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
default:
assert_unhandled_case(category);
return X_STATUS_INVALID_PARAMETER_1;
}
if (buffer_size < setting_size) {
return X_STATUS_BUFFER_TOO_SMALL;
}
if (!buffer && buffer_size) {
return X_STATUS_INVALID_PARAMETER_3;
}
if (buffer) {
xe::store_and_swap<uint32_t>(buffer, value);
}
if (required_size) {
*required_size = setting_size;
}
return X_STATUS_SUCCESS;
}
SHIM_CALL ExGetXConfigSetting_shim(PPCContext* ppc_state, KernelState* state) {
uint16_t category = SHIM_GET_ARG_16(0);
uint16_t setting = SHIM_GET_ARG_16(1);
uint32_t buffer_ptr = SHIM_GET_ARG_32(2);
uint16_t buffer_size = SHIM_GET_ARG_16(3);
uint32_t required_size_ptr = SHIM_GET_ARG_32(4);
XELOGD("ExGetXConfigSetting(%.4X, %.4X, %.8X, %.4X, %.8X)", category, setting,
buffer_ptr, buffer_size, required_size_ptr);
void* buffer = buffer_ptr ? SHIM_MEM_ADDR(buffer_ptr) : NULL;
uint16_t required_size = 0;
X_STATUS result = xeExGetXConfigSetting(category, setting, buffer,
buffer_size, &required_size);
if (required_size_ptr) {
SHIM_SET_MEM_16(required_size_ptr, required_size);
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexCheckExecutablePrivilege_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t privilege = SHIM_GET_ARG_32(0);
XELOGD("XexCheckExecutablePrivilege(%.8X)", privilege);
// BOOL
// DWORD Privilege
// Privilege is bit position in xe_xex2_system_flags enum - so:
// Privilege=6 -> 0x00000040 -> XEX_SYSTEM_INSECURE_SOCKETS
uint32_t mask = 1 << privilege;
XUserModule* module = state->GetExecutableModule();
if (!module) {
SHIM_SET_RETURN_32(0);
return;
}
xe_xex2_ref xex = module->xex();
const xe_xex2_header_t* header = xe_xex2_get_header(xex);
uint32_t result = (header->system_flags & mask) > 0;
module->Release();
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexGetModuleHandle_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_handle_ptr = SHIM_GET_ARG_32(1);
XModule* module = nullptr;
if (!module_name) {
module = state->GetExecutableModule();
} else {
module = state->GetModule(module_name);
}
if (!module) {
SHIM_SET_MEM_32(module_handle_ptr, 0);
SHIM_SET_RETURN_32(X_ERROR_NOT_FOUND);
return;
}
// NOTE: we don't retain the handle for return.
SHIM_SET_MEM_32(module_handle_ptr, module->handle());
XELOGD("%.8X = XexGetModuleHandle(%s, %.8X)", module->handle(), module_name, module_handle_ptr);
module->Release();
SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}
SHIM_CALL XexGetModuleSection_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t handle = SHIM_GET_ARG_32(0);
uint32_t name_ptr = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
uint32_t data_ptr = SHIM_GET_ARG_32(2);
uint32_t size_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexGetModuleSection(%.8X, %s, %.8X, %.8X)", handle, name, data_ptr,
size_ptr);
XModule* module = NULL;
X_STATUS result =
state->object_table()->GetObject(handle, (XObject**)&module);
if (XSUCCEEDED(result)) {
uint32_t section_data = 0;
uint32_t section_size = 0;
result = module->GetSection(name, §ion_data, §ion_size);
if (XSUCCEEDED(result)) {
SHIM_SET_MEM_32(data_ptr, section_data);
SHIM_SET_MEM_32(size_ptr, section_size);
}
module->Release();
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexLoadImage_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_flags = SHIM_GET_ARG_32(1);
uint32_t min_version = SHIM_GET_ARG_32(2);
uint32_t handle_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexLoadImage(%s, %.8X, %.8X, %.8X)", module_name, module_flags,
min_version, handle_ptr);
X_STATUS result = X_STATUS_NO_SUCH_FILE;
XModule* module = state->GetModule(module_name);
if (module) {
module->RetainHandle();
SHIM_SET_MEM_32(handle_ptr, module->handle());
module->Release();
result = X_STATUS_SUCCESS;
} else {
XUserModule* usermod = state->LoadUserModule(module_name);
if (usermod) {
result = X_STATUS_SUCCESS;
usermod->RetainHandle();
SHIM_SET_MEM_32(handle_ptr, usermod->handle());
usermod->Release();
}
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexUnloadImage_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t handle = SHIM_GET_ARG_32(0);
XELOGD("XexUnloadImage(%.8X)", handle);
X_STATUS result = X_STATUS_INVALID_HANDLE;
result = state->object_table()->RemoveHandle(handle);
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexGetProcedureAddress_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t module_handle = SHIM_GET_ARG_32(0);
uint32_t ordinal = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(ordinal);
uint32_t out_function_ptr = SHIM_GET_ARG_32(2);
X_STATUS result = X_STATUS_INVALID_HANDLE;
SHIM_SET_MEM_32(out_function_ptr, 0xDEADF00D);
XModule* module = NULL;
if (!module_handle) {
module = state->GetExecutableModule();
} else {
result =
state->object_table()->GetObject(module_handle, (XObject**)&module);
}
uint32_t ptr = 0;
if (XSUCCEEDED(result)) {
if (ordinal < 0x10000) {
// Ordinal.
ptr = module->GetProcAddressByOrdinal(ordinal);
} else {
// It's a name pointer instead.
ptr = module->GetProcAddressByName(name);
}
}
// FYI: We don't need to generate this function now. It'll
// be done automatically by xenia when it gets called.
if (ptr) {
SHIM_SET_MEM_32(out_function_ptr, ptr);
result = X_STATUS_SUCCESS;
} else {
result = X_STATUS_UNSUCCESSFUL;
}
if (ordinal < 0x10000) {
XELOGD("%.8X = XexGetProcedureAddress(%.8X, %.8X, %.8X)", ptr,
module_handle, ordinal, out_function_ptr);
} else {
XELOGD("%.8X = XexGetProcedureAddress(%.8X, %.8X(%s), %.8X)", ptr,
module_handle, ordinal, name, out_function_ptr);
}
if (module) {
module->Release();
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL ExRegisterTitleTerminateNotification_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t registration_ptr = SHIM_GET_ARG_32(0);
uint32_t create = SHIM_GET_ARG_32(1);
uint32_t routine = SHIM_MEM_32(registration_ptr + 0);
uint32_t priority = SHIM_MEM_32(registration_ptr + 4);
// list entry flink
// list entry blink
XELOGD("ExRegisterTitleTerminateNotification(%.8X(%.8X), %.1X)",
registration_ptr, routine, create);
if (create) {
// Adding.
// TODO(benvanik): add to master list (kernel?).
} else {
// Removing.
// TODO(benvanik): remove from master list.
}
}
} // namespace kernel
} // namespace xe
void xe::kernel::xboxkrnl::RegisterModuleExports(
xe::cpu::ExportResolver* export_resolver, KernelState* state) {
SHIM_SET_MAPPING("xboxkrnl.exe", ExGetXConfigSetting, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexCheckExecutablePrivilege, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleHandle, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleSection, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexLoadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexUnloadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetProcedureAddress, state);
SHIM_SET_MAPPING("xboxkrnl.exe", ExRegisterTitleTerminateNotification, state);
}
<commit_msg>Execute module entry-point function if it has one.<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xuser_module.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/util/xex2.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"
#include "xenia/cpu/processor.h"
namespace xe {
namespace kernel {
X_STATUS xeExGetXConfigSetting(uint16_t category, uint16_t setting,
void* buffer, uint16_t buffer_size,
uint16_t* required_size) {
uint16_t setting_size = 0;
uint32_t value = 0;
// TODO(benvanik): have real structs here that just get copied from.
// http://free60.org/XConfig
// http://freestyledash.googlecode.com/svn/trunk/Freestyle/Tools/Generic/ExConfig.h
switch (category) {
case 0x0002:
// XCONFIG_SECURED_CATEGORY
switch (setting) {
case 0x0002: // XCONFIG_SECURED_AV_REGION
setting_size = 4;
value = 0x00001000; // USA/Canada
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
case 0x0003:
// XCONFIG_USER_CATEGORY
switch (setting) {
case 0x0001: // XCONFIG_USER_TIME_ZONE_BIAS
case 0x0002: // XCONFIG_USER_TIME_ZONE_STD_NAME
case 0x0003: // XCONFIG_USER_TIME_ZONE_DLT_NAME
case 0x0004: // XCONFIG_USER_TIME_ZONE_STD_DATE
case 0x0005: // XCONFIG_USER_TIME_ZONE_DLT_DATE
case 0x0006: // XCONFIG_USER_TIME_ZONE_STD_BIAS
case 0x0007: // XCONFIG_USER_TIME_ZONE_DLT_BIAS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x0009: // XCONFIG_USER_LANGUAGE
setting_size = 4;
value = 0x00000001; // English
break;
case 0x000A: // XCONFIG_USER_VIDEO_FLAGS
setting_size = 4;
value = 0x00040000;
break;
case 0x000C: // XCONFIG_USER_RETAIL_FLAGS
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
case 0x000E: // XCONFIG_USER_COUNTRY
setting_size = 4;
// TODO(benvanik): get this value.
value = 0;
break;
default:
assert_unhandled_case(setting);
return X_STATUS_INVALID_PARAMETER_2;
}
break;
default:
assert_unhandled_case(category);
return X_STATUS_INVALID_PARAMETER_1;
}
if (buffer_size < setting_size) {
return X_STATUS_BUFFER_TOO_SMALL;
}
if (!buffer && buffer_size) {
return X_STATUS_INVALID_PARAMETER_3;
}
if (buffer) {
xe::store_and_swap<uint32_t>(buffer, value);
}
if (required_size) {
*required_size = setting_size;
}
return X_STATUS_SUCCESS;
}
SHIM_CALL ExGetXConfigSetting_shim(PPCContext* ppc_state, KernelState* state) {
uint16_t category = SHIM_GET_ARG_16(0);
uint16_t setting = SHIM_GET_ARG_16(1);
uint32_t buffer_ptr = SHIM_GET_ARG_32(2);
uint16_t buffer_size = SHIM_GET_ARG_16(3);
uint32_t required_size_ptr = SHIM_GET_ARG_32(4);
XELOGD("ExGetXConfigSetting(%.4X, %.4X, %.8X, %.4X, %.8X)", category, setting,
buffer_ptr, buffer_size, required_size_ptr);
void* buffer = buffer_ptr ? SHIM_MEM_ADDR(buffer_ptr) : NULL;
uint16_t required_size = 0;
X_STATUS result = xeExGetXConfigSetting(category, setting, buffer,
buffer_size, &required_size);
if (required_size_ptr) {
SHIM_SET_MEM_16(required_size_ptr, required_size);
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexCheckExecutablePrivilege_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t privilege = SHIM_GET_ARG_32(0);
XELOGD("XexCheckExecutablePrivilege(%.8X)", privilege);
// BOOL
// DWORD Privilege
// Privilege is bit position in xe_xex2_system_flags enum - so:
// Privilege=6 -> 0x00000040 -> XEX_SYSTEM_INSECURE_SOCKETS
uint32_t mask = 1 << privilege;
XUserModule* module = state->GetExecutableModule();
if (!module) {
SHIM_SET_RETURN_32(0);
return;
}
xe_xex2_ref xex = module->xex();
const xe_xex2_header_t* header = xe_xex2_get_header(xex);
uint32_t result = (header->system_flags & mask) > 0;
module->Release();
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexGetModuleHandle_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_handle_ptr = SHIM_GET_ARG_32(1);
XModule* module = nullptr;
if (!module_name) {
module = state->GetExecutableModule();
} else {
module = state->GetModule(module_name);
}
if (!module) {
SHIM_SET_MEM_32(module_handle_ptr, 0);
SHIM_SET_RETURN_32(X_ERROR_NOT_FOUND);
return;
}
// NOTE: we don't retain the handle for return.
SHIM_SET_MEM_32(module_handle_ptr, module->handle());
XELOGD("%.8X = XexGetModuleHandle(%s, %.8X)", module->handle(), module_name, module_handle_ptr);
module->Release();
SHIM_SET_RETURN_32(X_ERROR_SUCCESS);
}
SHIM_CALL XexGetModuleSection_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t handle = SHIM_GET_ARG_32(0);
uint32_t name_ptr = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
uint32_t data_ptr = SHIM_GET_ARG_32(2);
uint32_t size_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexGetModuleSection(%.8X, %s, %.8X, %.8X)", handle, name, data_ptr,
size_ptr);
XModule* module = NULL;
X_STATUS result =
state->object_table()->GetObject(handle, (XObject**)&module);
if (XSUCCEEDED(result)) {
uint32_t section_data = 0;
uint32_t section_size = 0;
result = module->GetSection(name, §ion_data, §ion_size);
if (XSUCCEEDED(result)) {
SHIM_SET_MEM_32(data_ptr, section_data);
SHIM_SET_MEM_32(size_ptr, section_size);
}
module->Release();
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexLoadImage_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t module_name_ptr = SHIM_GET_ARG_32(0);
const char* module_name = (const char*)SHIM_MEM_ADDR(module_name_ptr);
uint32_t module_flags = SHIM_GET_ARG_32(1);
uint32_t min_version = SHIM_GET_ARG_32(2);
uint32_t handle_ptr = SHIM_GET_ARG_32(3);
XELOGD("XexLoadImage(%s, %.8X, %.8X, %.8X)", module_name, module_flags,
min_version, handle_ptr);
X_STATUS result = X_STATUS_NO_SUCH_FILE;
XModule* module = state->GetModule(module_name);
if (module) {
module->RetainHandle();
SHIM_SET_MEM_32(handle_ptr, module->handle());
module->Release();
result = X_STATUS_SUCCESS;
} else {
XUserModule* usermod = state->LoadUserModule(module_name);
if (usermod) {
// If the module has an entry point function, we have to call it.
const xe_xex2_header_t* header = usermod->xex_header();
if (header->exe_entry_point) {
state->processor()->Execute(ppc_state->thread_state,
header->exe_entry_point);
}
result = X_STATUS_SUCCESS;
usermod->RetainHandle();
SHIM_SET_MEM_32(handle_ptr, usermod->handle());
usermod->Release();
}
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexUnloadImage_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t handle = SHIM_GET_ARG_32(0);
XELOGD("XexUnloadImage(%.8X)", handle);
X_STATUS result = X_STATUS_INVALID_HANDLE;
result = state->object_table()->RemoveHandle(handle);
SHIM_SET_RETURN_32(result);
}
SHIM_CALL XexGetProcedureAddress_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t module_handle = SHIM_GET_ARG_32(0);
uint32_t ordinal = SHIM_GET_ARG_32(1);
const char* name = (const char*)SHIM_MEM_ADDR(ordinal);
uint32_t out_function_ptr = SHIM_GET_ARG_32(2);
X_STATUS result = X_STATUS_INVALID_HANDLE;
SHIM_SET_MEM_32(out_function_ptr, 0xDEADF00D);
XModule* module = NULL;
if (!module_handle) {
module = state->GetExecutableModule();
} else {
result =
state->object_table()->GetObject(module_handle, (XObject**)&module);
}
uint32_t ptr = 0;
if (XSUCCEEDED(result)) {
if (ordinal < 0x10000) {
// Ordinal.
ptr = module->GetProcAddressByOrdinal(ordinal);
} else {
// It's a name pointer instead.
ptr = module->GetProcAddressByName(name);
}
}
// FYI: We don't need to generate this function now. It'll
// be done automatically by xenia when it gets called.
if (ptr) {
SHIM_SET_MEM_32(out_function_ptr, ptr);
result = X_STATUS_SUCCESS;
} else {
result = X_STATUS_UNSUCCESSFUL;
}
if (ordinal < 0x10000) {
XELOGD("%.8X = XexGetProcedureAddress(%.8X, %.8X, %.8X)", ptr,
module_handle, ordinal, out_function_ptr);
} else {
XELOGD("%.8X = XexGetProcedureAddress(%.8X, %.8X(%s), %.8X)", ptr,
module_handle, ordinal, name, out_function_ptr);
}
if (module) {
module->Release();
}
SHIM_SET_RETURN_32(result);
}
SHIM_CALL ExRegisterTitleTerminateNotification_shim(PPCContext* ppc_state,
KernelState* state) {
uint32_t registration_ptr = SHIM_GET_ARG_32(0);
uint32_t create = SHIM_GET_ARG_32(1);
uint32_t routine = SHIM_MEM_32(registration_ptr + 0);
uint32_t priority = SHIM_MEM_32(registration_ptr + 4);
// list entry flink
// list entry blink
XELOGD("ExRegisterTitleTerminateNotification(%.8X(%.8X), %.1X)",
registration_ptr, routine, create);
if (create) {
// Adding.
// TODO(benvanik): add to master list (kernel?).
} else {
// Removing.
// TODO(benvanik): remove from master list.
}
}
} // namespace kernel
} // namespace xe
void xe::kernel::xboxkrnl::RegisterModuleExports(
xe::cpu::ExportResolver* export_resolver, KernelState* state) {
SHIM_SET_MAPPING("xboxkrnl.exe", ExGetXConfigSetting, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexCheckExecutablePrivilege, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleHandle, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetModuleSection, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexLoadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexUnloadImage, state);
SHIM_SET_MAPPING("xboxkrnl.exe", XexGetProcedureAddress, state);
SHIM_SET_MAPPING("xboxkrnl.exe", ExRegisterTitleTerminateNotification, state);
}
<|endoftext|> |
<commit_before>#include "elm/core/graph/base_GraphVertexOp.h"
#include "gtest/gtest.h"
#include <opencv2/core/core.hpp>
#include "elm/ts/mat_assertions.h"
using namespace cv;
using namespace elm;
namespace {
/** Derive from Graph operator interface to test
*/
class DummyOp : public base_GraphVertexOp
{
public:
DummyOp()
: base_GraphVertexOp(),
call_count_(0)
{
}
cv::Mat1f operator ()(const cv::Mat1f& img, const cv::Mat1b &mask)
{
call_count_++;
return img.clone().setTo(0.f, mask);
}
int CallCount() const
{
return call_count_;
}
protected:
int call_count_; ///< increments with every operator call
};
class GraphVertexOpTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
to_ = DummyOp();
}
DummyOp to_; ///< test object
};
TEST_F(GraphVertexOpTest, op)
{
Mat1f img(2, 2);
for(size_t i=0; i<img.total(); i++) {
img(i) = static_cast<float>(i);
}
Mat1f result;
for(size_t i=0; i<img.total(); i++) {
result = to_(img, img == static_cast<float>(i));
EXPECT_FLOAT_EQ(0.f, result(i));
Mat1f expected = img.clone();
expected(i) = 0.f;
EXPECT_MAT_EQ(expected, result);
}
}
TEST_F(GraphVertexOpTest, op_input_empty)
{
EXPECT_TRUE(to_(Mat1f(), Mat1b()).empty());
}
TEST_F(GraphVertexOpTest, op_dims)
{
for(int r=1; r<11; r++) {
for(int c=1; c<11; c++) {
Mat1f img(r, c, 123.f);
Mat1f result = to_(img, img > 0);
EXPECT_MAT_DIMS_EQ(result, cv::Size2i(c, r));
}
}
}
TEST_F(GraphVertexOpTest, op_mask)
{
Mat1f img(2, 2);
for(size_t i=0; i<img.total(); i++) {
img(i) = static_cast<float>(i);
}
Mat1f result;
for(size_t i=0; i<img.total(); i++) {
result = to_(img, img == static_cast<float>(i));
EXPECT_FLOAT_EQ(0.f, result(i));
Mat1f expected = img.clone();
expected(i) = 0.f;
EXPECT_MAT_EQ(expected, result);
}
}
TEST_F(GraphVertexOpTest, op_call_count)
{
Mat1f img(2, 2, 1.f);
Mat1f result;
for(size_t i=0; i<img.total(); i++) {
result = to_(img, img == static_cast<float>(i));
EXPECT_EQ(static_cast<int>(i+1), to_.CallCount());
}
}
} // annonymous namespace for tests
<commit_msg>pass operator object to applyVertexToMap()<commit_after>#include "elm/core/graph/base_GraphVertexOp.h"
#include "gtest/gtest.h"
#include <opencv2/core/core.hpp>
#include "elm/core/graph/graphattr.h"
#include "elm/ts/mat_assertions.h"
using namespace cv;
using namespace elm;
namespace {
/** Derive from Graph operator interface to test
*/
class DummyOp : public base_GraphVertexOp
{
public:
DummyOp()
: base_GraphVertexOp(),
call_count_(0)
{
}
cv::Mat1f operator ()(const cv::Mat1f& img, const cv::Mat1b &mask)
{
call_count_++;
return img.clone().setTo(0.f, mask);
}
int CallCount() const
{
return call_count_;
}
protected:
int call_count_; ///< increments with every operator call
};
class GraphVertexOpTest : public ::testing::Test
{
protected:
virtual void SetUp()
{
to_ = DummyOp();
}
DummyOp to_; ///< test object
};
TEST_F(GraphVertexOpTest, op)
{
Mat1f img(2, 2);
for(size_t i=0; i<img.total(); i++) {
img(i) = static_cast<float>(i);
}
Mat1f result;
for(size_t i=0; i<img.total(); i++) {
result = to_(img, img == static_cast<float>(i));
EXPECT_FLOAT_EQ(0.f, result(i));
Mat1f expected = img.clone();
expected(i) = 0.f;
EXPECT_MAT_EQ(expected, result);
}
}
TEST_F(GraphVertexOpTest, op_input_empty)
{
EXPECT_TRUE(to_(Mat1f(), Mat1b()).empty());
}
TEST_F(GraphVertexOpTest, op_dims)
{
for(int r=1; r<11; r++) {
for(int c=1; c<11; c++) {
Mat1f img(r, c, 123.f);
Mat1f result = to_(img, img > 0);
EXPECT_MAT_DIMS_EQ(result, cv::Size2i(c, r));
}
}
}
TEST_F(GraphVertexOpTest, op_mask)
{
Mat1f img(2, 2);
for(size_t i=0; i<img.total(); i++) {
img(i) = static_cast<float>(i);
}
Mat1f result;
for(size_t i=0; i<img.total(); i++) {
result = to_(img, img == static_cast<float>(i));
EXPECT_FLOAT_EQ(0.f, result(i));
Mat1f expected = img.clone();
expected(i) = 0.f;
EXPECT_MAT_EQ(expected, result);
}
}
TEST_F(GraphVertexOpTest, op_call_count)
{
Mat1f img(2, 2, 1.f);
Mat1f result;
for(size_t i=0; i<img.total(); i++) {
result = to_(img, img == static_cast<float>(i));
EXPECT_EQ(static_cast<int>(i+1), to_.CallCount());
}
}
TEST_F(GraphVertexOpTest, op_applied_to_graph_vertex)
{
const int ROWS=3;
const int COLS=3;
float data[ROWS*COLS] = {1.f, 7.0f, 2.2f,
3.f, 6.0f, 6.0f,
9.f, 9.5f, 11.f};
Mat1f map = Mat1f(ROWS, COLS, data).clone();
Mat1b exclude, mask;
cv::bitwise_or(map < 2.f, map == 9.f, exclude);
cv::bitwise_not(exclude, mask);
GraphAttr graph(map, mask);
ASSERT_GT(graph.num_vertices(), static_cast<size_t>(0)) << "this test requires a non-empty graph";
Mat1f result_graph = graph.applyVertexToMap(6.f, to_);
Mat1f result_op = to_(map, map == 6.f);
EXPECT_MAT_EQ(result_op, result_graph);
}
} // annonymous namespace for tests
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
using namespace std;
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expanson
case OP_NOP1 : return "OP_NOP1";
case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
case OP_NOP4 : return "OP_NOP4";
case OP_NOP5 : return "OP_NOP5";
case OP_NOP6 : return "OP_NOP6";
case OP_NOP7 : return "OP_NOP7";
case OP_NOP8 : return "OP_NOP8";
case OP_NOP9 : return "OP_NOP9";
case OP_NOP10 : return "OP_NOP10";
case OP_CFUND : return "OP_CFUND";
case OP_PROP : return "OP_PROP";
case OP_PREQ : return "OP_PREQ";
case OP_YES : return "OP_YES";
case OP_NO : return "OP_NO";
case OP_COINSTAKE : return "OP_COINSTAKE";
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
// Note:
// The template matching params OP_SMALLDATA/etc are defined in opcodetype enum
// as kind of implementation hack, they are *NOT* real opcodes. If found in real
// Script, just let the default: case deal with them.
default:
return "OP_UNKNOWN";
}
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += MAX_PUBKEYS_PER_MULTISIG;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, data))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(data.begin(), data.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsColdStake() const
{
return (this->size() == 1+1+25+1+25+1 &&
(*this)[0] == OP_COINSTAKE &&
(*this)[1] == OP_IF &&
(*this)[0] == OP_DUP &&
(*this)[3] == OP_HASH160 &&
(*this)[4] == 0x14 &&
(*this)[25] == OP_EQUALVERIFY &&
(*this)[26] == OP_CHECKSIG) &&
(*this)[27] == OP_ELSE &&
(*this)[28] == OP_DUP &&
(*this)[29] == OP_HASH160 &&
(*this)[30] == 0x14 &&
(*this)[51] == OP_EQUALVERIFY &&
(*this)[52] == OP_CHECKSIG) &&
(*this)[53] == OP_ENDIF);
}
bool CScript::IsPayToPublicKeyHash() const
{
// Extra-fast test for pay-to-pubkey-hash CScripts:
return (this->size() == 25 &&
(*this)[0] == OP_DUP &&
(*this)[1] == OP_HASH160 &&
(*this)[2] == 0x14 &&
(*this)[23] == OP_EQUALVERIFY &&
(*this)[24] == OP_CHECKSIG);
}
bool CScript::IsCommunityFundContribution() const
{
return (this->size() == 2 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND);
}
bool CScript::IsProposalVote() const
{
return IsProposalVoteYes() || IsProposalVoteNo();
}
bool CScript::IsProposalVoteYes() const
{
return (this->size() == 36 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND &&
(*this)[2] == OP_PROP &&
(*this)[3] == OP_YES);
}
bool CScript::IsProposalVoteNo() const
{
return (this->size() == 36 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND &&
(*this)[2] == OP_PROP &&
(*this)[3] == OP_NO);
}
bool CScript::IsPaymentRequestVote() const
{
return IsPaymentRequestVoteYes() || IsPaymentRequestVoteNo();
}
bool CScript::IsPaymentRequestVoteYes() const
{
return (this->size() == 36 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND &&
(*this)[2] == OP_PREQ &&
(*this)[3] == OP_YES);
}
bool CScript::IsPaymentRequestVoteNo() const
{
return (this->size() == 36 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND &&
(*this)[2] == OP_PREQ &&
(*this)[3] == OP_NO);
}
bool CScript::ExtractVote(uint256 &hash, bool &vote) const
{
if(!IsPaymentRequestVoteNo() && !IsPaymentRequestVoteYes() && !IsProposalVoteYes()
&& !IsProposalVoteNo())
return false;
vector<unsigned char> vHash(this->begin()+4, this->begin()+36);
hash = uint256(vHash);
vote = (*this)[3] == OP_YES ? true : false;
return true;
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
(*this)[0] == OP_HASH160 &&
(*this)[1] == 0x14 &&
(*this)[22] == OP_EQUAL);
}
bool CScript::IsPayToWitnessScriptHash() const
{
// Extra-fast test for pay-to-witness-script-hash CScripts:
return (this->size() == 34 &&
(*this)[0] == OP_0 &&
(*this)[1] == 0x20);
}
// A witness program is any valid CScript that consists of a 1-byte push opcode
// followed by a data push between 2 and 40 bytes.
bool CScript::IsWitnessProgram(int& version, std::vector<unsigned char>& program) const
{
if (this->size() < 4 || this->size() > 42) {
return false;
}
if ((*this)[0] != OP_0 && ((*this)[0] < OP_1 || (*this)[0] > OP_16)) {
return false;
}
if ((size_t)((*this)[1] + 2) == this->size()) {
version = DecodeOP_N((opcodetype)(*this)[0]);
program = std::vector<unsigned char>(this->begin() + 2, this->end());
return true;
}
return false;
}
bool CScript::IsPushOnly(const_iterator pc) const
{
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
// Note that IsPushOnly() *does* consider OP_RESERVED to be a
// push-type opcode, however execution of OP_RESERVED fails, so
// it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
// the P2SH special validation code being executed.
if (opcode > OP_16)
return false;
}
return true;
}
bool CScript::IsPushOnly() const
{
return this->IsPushOnly(begin());
}
std::string CScriptWitness::ToString() const
{
std::string ret = "CScriptWitness(";
for (unsigned int i = 0; i < stack.size(); i++) {
if (i) {
ret += ", ";
}
ret += HexStr(stack[i]);
}
return ret + ")";
}
<commit_msg>fix parenthesis<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
using namespace std;
const char* GetOpName(opcodetype opcode)
{
switch (opcode)
{
// push value
case OP_0 : return "0";
case OP_PUSHDATA1 : return "OP_PUSHDATA1";
case OP_PUSHDATA2 : return "OP_PUSHDATA2";
case OP_PUSHDATA4 : return "OP_PUSHDATA4";
case OP_1NEGATE : return "-1";
case OP_RESERVED : return "OP_RESERVED";
case OP_1 : return "1";
case OP_2 : return "2";
case OP_3 : return "3";
case OP_4 : return "4";
case OP_5 : return "5";
case OP_6 : return "6";
case OP_7 : return "7";
case OP_8 : return "8";
case OP_9 : return "9";
case OP_10 : return "10";
case OP_11 : return "11";
case OP_12 : return "12";
case OP_13 : return "13";
case OP_14 : return "14";
case OP_15 : return "15";
case OP_16 : return "16";
// control
case OP_NOP : return "OP_NOP";
case OP_VER : return "OP_VER";
case OP_IF : return "OP_IF";
case OP_NOTIF : return "OP_NOTIF";
case OP_VERIF : return "OP_VERIF";
case OP_VERNOTIF : return "OP_VERNOTIF";
case OP_ELSE : return "OP_ELSE";
case OP_ENDIF : return "OP_ENDIF";
case OP_VERIFY : return "OP_VERIFY";
case OP_RETURN : return "OP_RETURN";
// stack ops
case OP_TOALTSTACK : return "OP_TOALTSTACK";
case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
case OP_2DROP : return "OP_2DROP";
case OP_2DUP : return "OP_2DUP";
case OP_3DUP : return "OP_3DUP";
case OP_2OVER : return "OP_2OVER";
case OP_2ROT : return "OP_2ROT";
case OP_2SWAP : return "OP_2SWAP";
case OP_IFDUP : return "OP_IFDUP";
case OP_DEPTH : return "OP_DEPTH";
case OP_DROP : return "OP_DROP";
case OP_DUP : return "OP_DUP";
case OP_NIP : return "OP_NIP";
case OP_OVER : return "OP_OVER";
case OP_PICK : return "OP_PICK";
case OP_ROLL : return "OP_ROLL";
case OP_ROT : return "OP_ROT";
case OP_SWAP : return "OP_SWAP";
case OP_TUCK : return "OP_TUCK";
// splice ops
case OP_CAT : return "OP_CAT";
case OP_SUBSTR : return "OP_SUBSTR";
case OP_LEFT : return "OP_LEFT";
case OP_RIGHT : return "OP_RIGHT";
case OP_SIZE : return "OP_SIZE";
// bit logic
case OP_INVERT : return "OP_INVERT";
case OP_AND : return "OP_AND";
case OP_OR : return "OP_OR";
case OP_XOR : return "OP_XOR";
case OP_EQUAL : return "OP_EQUAL";
case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
case OP_RESERVED1 : return "OP_RESERVED1";
case OP_RESERVED2 : return "OP_RESERVED2";
// numeric
case OP_1ADD : return "OP_1ADD";
case OP_1SUB : return "OP_1SUB";
case OP_2MUL : return "OP_2MUL";
case OP_2DIV : return "OP_2DIV";
case OP_NEGATE : return "OP_NEGATE";
case OP_ABS : return "OP_ABS";
case OP_NOT : return "OP_NOT";
case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
case OP_ADD : return "OP_ADD";
case OP_SUB : return "OP_SUB";
case OP_MUL : return "OP_MUL";
case OP_DIV : return "OP_DIV";
case OP_MOD : return "OP_MOD";
case OP_LSHIFT : return "OP_LSHIFT";
case OP_RSHIFT : return "OP_RSHIFT";
case OP_BOOLAND : return "OP_BOOLAND";
case OP_BOOLOR : return "OP_BOOLOR";
case OP_NUMEQUAL : return "OP_NUMEQUAL";
case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
case OP_LESSTHAN : return "OP_LESSTHAN";
case OP_GREATERTHAN : return "OP_GREATERTHAN";
case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
case OP_MIN : return "OP_MIN";
case OP_MAX : return "OP_MAX";
case OP_WITHIN : return "OP_WITHIN";
// crypto
case OP_RIPEMD160 : return "OP_RIPEMD160";
case OP_SHA1 : return "OP_SHA1";
case OP_SHA256 : return "OP_SHA256";
case OP_HASH160 : return "OP_HASH160";
case OP_HASH256 : return "OP_HASH256";
case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
case OP_CHECKSIG : return "OP_CHECKSIG";
case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
// expanson
case OP_NOP1 : return "OP_NOP1";
case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
case OP_NOP4 : return "OP_NOP4";
case OP_NOP5 : return "OP_NOP5";
case OP_NOP6 : return "OP_NOP6";
case OP_NOP7 : return "OP_NOP7";
case OP_NOP8 : return "OP_NOP8";
case OP_NOP9 : return "OP_NOP9";
case OP_NOP10 : return "OP_NOP10";
case OP_CFUND : return "OP_CFUND";
case OP_PROP : return "OP_PROP";
case OP_PREQ : return "OP_PREQ";
case OP_YES : return "OP_YES";
case OP_NO : return "OP_NO";
case OP_COINSTAKE : return "OP_COINSTAKE";
case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
// Note:
// The template matching params OP_SMALLDATA/etc are defined in opcodetype enum
// as kind of implementation hack, they are *NOT* real opcodes. If found in real
// Script, just let the default: case deal with them.
default:
return "OP_UNKNOWN";
}
}
unsigned int CScript::GetSigOpCount(bool fAccurate) const
{
unsigned int n = 0;
const_iterator pc = begin();
opcodetype lastOpcode = OP_INVALIDOPCODE;
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
break;
if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
n++;
else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
{
if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
n += DecodeOP_N(lastOpcode);
else
n += MAX_PUBKEYS_PER_MULTISIG;
}
lastOpcode = opcode;
}
return n;
}
unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
{
if (!IsPayToScriptHash())
return GetSigOpCount(true);
// This is a pay-to-script-hash scriptPubKey;
// get the last item that the scriptSig
// pushes onto the stack:
const_iterator pc = scriptSig.begin();
vector<unsigned char> data;
while (pc < scriptSig.end())
{
opcodetype opcode;
if (!scriptSig.GetOp(pc, opcode, data))
return 0;
if (opcode > OP_16)
return 0;
}
/// ... and return its opcount:
CScript subscript(data.begin(), data.end());
return subscript.GetSigOpCount(true);
}
bool CScript::IsColdStake() const
{
return (this->size() == 1+1+25+1+25+1 &&
(*this)[0] == OP_COINSTAKE &&
(*this)[1] == OP_IF &&
(*this)[0] == OP_DUP &&
(*this)[3] == OP_HASH160 &&
(*this)[4] == 0x14 &&
(*this)[25] == OP_EQUALVERIFY &&
(*this)[26] == OP_CHECKSIG &&
(*this)[27] == OP_ELSE &&
(*this)[28] == OP_DUP &&
(*this)[29] == OP_HASH160 &&
(*this)[30] == 0x14 &&
(*this)[51] == OP_EQUALVERIFY &&
(*this)[52] == OP_CHECKSIG &&
(*this)[53] == OP_ENDIF);
}
bool CScript::IsPayToPublicKeyHash() const
{
// Extra-fast test for pay-to-pubkey-hash CScripts:
return (this->size() == 25 &&
(*this)[0] == OP_DUP &&
(*this)[1] == OP_HASH160 &&
(*this)[2] == 0x14 &&
(*this)[23] == OP_EQUALVERIFY &&
(*this)[24] == OP_CHECKSIG);
}
bool CScript::IsCommunityFundContribution() const
{
return (this->size() == 2 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND);
}
bool CScript::IsProposalVote() const
{
return IsProposalVoteYes() || IsProposalVoteNo();
}
bool CScript::IsProposalVoteYes() const
{
return (this->size() == 36 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND &&
(*this)[2] == OP_PROP &&
(*this)[3] == OP_YES);
}
bool CScript::IsProposalVoteNo() const
{
return (this->size() == 36 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND &&
(*this)[2] == OP_PROP &&
(*this)[3] == OP_NO);
}
bool CScript::IsPaymentRequestVote() const
{
return IsPaymentRequestVoteYes() || IsPaymentRequestVoteNo();
}
bool CScript::IsPaymentRequestVoteYes() const
{
return (this->size() == 36 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND &&
(*this)[2] == OP_PREQ &&
(*this)[3] == OP_YES);
}
bool CScript::IsPaymentRequestVoteNo() const
{
return (this->size() == 36 &&
(*this)[0] == OP_RETURN &&
(*this)[1] == OP_CFUND &&
(*this)[2] == OP_PREQ &&
(*this)[3] == OP_NO);
}
bool CScript::ExtractVote(uint256 &hash, bool &vote) const
{
if(!IsPaymentRequestVoteNo() && !IsPaymentRequestVoteYes() && !IsProposalVoteYes()
&& !IsProposalVoteNo())
return false;
vector<unsigned char> vHash(this->begin()+4, this->begin()+36);
hash = uint256(vHash);
vote = (*this)[3] == OP_YES ? true : false;
return true;
}
bool CScript::IsPayToScriptHash() const
{
// Extra-fast test for pay-to-script-hash CScripts:
return (this->size() == 23 &&
(*this)[0] == OP_HASH160 &&
(*this)[1] == 0x14 &&
(*this)[22] == OP_EQUAL);
}
bool CScript::IsPayToWitnessScriptHash() const
{
// Extra-fast test for pay-to-witness-script-hash CScripts:
return (this->size() == 34 &&
(*this)[0] == OP_0 &&
(*this)[1] == 0x20);
}
// A witness program is any valid CScript that consists of a 1-byte push opcode
// followed by a data push between 2 and 40 bytes.
bool CScript::IsWitnessProgram(int& version, std::vector<unsigned char>& program) const
{
if (this->size() < 4 || this->size() > 42) {
return false;
}
if ((*this)[0] != OP_0 && ((*this)[0] < OP_1 || (*this)[0] > OP_16)) {
return false;
}
if ((size_t)((*this)[1] + 2) == this->size()) {
version = DecodeOP_N((opcodetype)(*this)[0]);
program = std::vector<unsigned char>(this->begin() + 2, this->end());
return true;
}
return false;
}
bool CScript::IsPushOnly(const_iterator pc) const
{
while (pc < end())
{
opcodetype opcode;
if (!GetOp(pc, opcode))
return false;
// Note that IsPushOnly() *does* consider OP_RESERVED to be a
// push-type opcode, however execution of OP_RESERVED fails, so
// it's not relevant to P2SH/BIP62 as the scriptSig would fail prior to
// the P2SH special validation code being executed.
if (opcode > OP_16)
return false;
}
return true;
}
bool CScript::IsPushOnly() const
{
return this->IsPushOnly(begin());
}
std::string CScriptWitness::ToString() const
{
std::string ret = "CScriptWitness(";
for (unsigned int i = 0; i < stack.size(); i++) {
if (i) {
ret += ", ";
}
ret += HexStr(stack[i]);
}
return ret + ")";
}
<|endoftext|> |
<commit_before>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2019 David Shah <[email protected]>
* Copyright (C) 2021 William D. Jones <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "cells.h"
#include "design_utils.h"
#include "log.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
void add_port(const Context *ctx, CellInfo *cell, std::string name, PortType dir)
{
IdString id = ctx->id(name);
NPNR_ASSERT(cell->ports.count(id) == 0);
cell->ports[id] = PortInfo{id, nullptr, dir};
}
void add_port(const Context *ctx, CellInfo *cell, IdString id, PortType dir)
{
NPNR_ASSERT(cell->ports.count(id) == 0);
cell->ports[id] = PortInfo{id, nullptr, dir};
}
std::unique_ptr<CellInfo> create_machxo2_cell(Context *ctx, IdString type, std::string name)
{
static int auto_idx = 0;
std::unique_ptr<CellInfo> new_cell = std::unique_ptr<CellInfo>(new CellInfo());
if (name.empty()) {
new_cell->name = ctx->id("$nextpnr_" + type.str(ctx) + "_" + std::to_string(auto_idx++));
} else {
new_cell->name = ctx->id(name);
}
new_cell->type = type;
if (type == id_FACADE_SLICE) {
new_cell->params[id_MODE] = std::string("LOGIC");
new_cell->params[id_GSR] = std::string("ENABLED");
new_cell->params[id_SRMODE] = std::string("LSR_OVER_CE");
new_cell->params[id_CEMUX] = std::string("1");
new_cell->params[id_CLKMUX] = std::string("0");
new_cell->params[id_LSRMUX] = std::string("LSR");
new_cell->params[id_LSRONMUX] = std::string("LSRMUX");
new_cell->params[id_LUT0_INITVAL] = Property(0xFFFF, 16);
new_cell->params[id_LUT1_INITVAL] = Property(0xFFFF, 16);
new_cell->params[id_REG0_SD] = std::string("1");
new_cell->params[id_REG1_SD] = std::string("1");
new_cell->params[id_REG0_REGSET] = std::string("SET");
new_cell->params[id_REG1_REGSET] = std::string("SET");
new_cell->params[id_REG0_REGMODE] = std::string("FF");
new_cell->params[id_REG1_REGMODE] = std::string("FF");
new_cell->params[id_CCU2_INJECT1_0] = std::string("YES");
new_cell->params[id_CCU2_INJECT1_1] = std::string("YES");
new_cell->params[id_WREMUX] = std::string("INV");
add_port(ctx, new_cell.get(), id_A0, PORT_IN);
add_port(ctx, new_cell.get(), id_B0, PORT_IN);
add_port(ctx, new_cell.get(), id_C0, PORT_IN);
add_port(ctx, new_cell.get(), id_D0, PORT_IN);
add_port(ctx, new_cell.get(), id_A1, PORT_IN);
add_port(ctx, new_cell.get(), id_B1, PORT_IN);
add_port(ctx, new_cell.get(), id_C1, PORT_IN);
add_port(ctx, new_cell.get(), id_D1, PORT_IN);
add_port(ctx, new_cell.get(), id_M0, PORT_IN);
add_port(ctx, new_cell.get(), id_M1, PORT_IN);
add_port(ctx, new_cell.get(), id_FCI, PORT_IN);
add_port(ctx, new_cell.get(), id_FXA, PORT_IN);
add_port(ctx, new_cell.get(), id_FXB, PORT_IN);
add_port(ctx, new_cell.get(), id_CLK, PORT_IN);
add_port(ctx, new_cell.get(), id_LSR, PORT_IN);
add_port(ctx, new_cell.get(), id_CE, PORT_IN);
add_port(ctx, new_cell.get(), id_DI0, PORT_IN);
add_port(ctx, new_cell.get(), id_DI1, PORT_IN);
add_port(ctx, new_cell.get(), id_WD0, PORT_IN);
add_port(ctx, new_cell.get(), id_WD1, PORT_IN);
add_port(ctx, new_cell.get(), id_WAD0, PORT_IN);
add_port(ctx, new_cell.get(), id_WAD1, PORT_IN);
add_port(ctx, new_cell.get(), id_WAD2, PORT_IN);
add_port(ctx, new_cell.get(), id_WAD3, PORT_IN);
add_port(ctx, new_cell.get(), id_WRE, PORT_IN);
add_port(ctx, new_cell.get(), id_WCK, PORT_IN);
add_port(ctx, new_cell.get(), id_F0, PORT_OUT);
add_port(ctx, new_cell.get(), id_Q0, PORT_OUT);
add_port(ctx, new_cell.get(), id_F1, PORT_OUT);
add_port(ctx, new_cell.get(), id_Q1, PORT_OUT);
add_port(ctx, new_cell.get(), id_FCO, PORT_OUT);
add_port(ctx, new_cell.get(), id_OFX0, PORT_OUT);
add_port(ctx, new_cell.get(), id_OFX1, PORT_OUT);
add_port(ctx, new_cell.get(), id_WDO0, PORT_OUT);
add_port(ctx, new_cell.get(), id_WDO1, PORT_OUT);
add_port(ctx, new_cell.get(), id_WDO2, PORT_OUT);
add_port(ctx, new_cell.get(), id_WDO3, PORT_OUT);
add_port(ctx, new_cell.get(), id_WADO0, PORT_OUT);
add_port(ctx, new_cell.get(), id_WADO1, PORT_OUT);
add_port(ctx, new_cell.get(), id_WADO2, PORT_OUT);
add_port(ctx, new_cell.get(), id_WADO3, PORT_OUT);
} else if (type == id_FACADE_IO) {
new_cell->params[id_DIR] = std::string("INPUT");
new_cell->attrs[ctx->id("IO_TYPE")] = std::string("LVCMOS33");
add_port(ctx, new_cell.get(), "PAD", PORT_INOUT);
add_port(ctx, new_cell.get(), "I", PORT_IN);
add_port(ctx, new_cell.get(), "EN", PORT_IN);
add_port(ctx, new_cell.get(), "O", PORT_OUT);
} else if (type == id_LUT4) {
new_cell->params[id_INIT] = Property(0, 16);
add_port(ctx, new_cell.get(), id_A, PORT_IN);
add_port(ctx, new_cell.get(), id_B, PORT_IN);
add_port(ctx, new_cell.get(), id_C, PORT_IN);
add_port(ctx, new_cell.get(), id_D, PORT_IN);
add_port(ctx, new_cell.get(), id_Z, PORT_OUT);
} else {
log_error("unable to create MachXO2 cell of type %s", type.c_str(ctx));
}
return new_cell;
}
void lut_to_lc(const Context *ctx, CellInfo *lut, CellInfo *lc, bool no_dff)
{
lc->params[ctx->id("LUT0_INITVAL")] = lut->params[ctx->id("INIT")];
for (std::string i : {"A", "B", "C", "D"}) {
IdString lut_port = ctx->id(i);
IdString lc_port = ctx->id(i + "0");
replace_port(lut, lut_port, lc, lc_port);
}
replace_port(lut, ctx->id("Z"), lc, ctx->id("F0"));
}
void dff_to_lc(const Context *ctx, CellInfo *dff, CellInfo *lc, bool pass_thru_lut)
{
// By this point, we have shown that LUT4 Z is attached to FACADE_FF DI.
// This connection will be preserved by port replacement, but the SD mux
// which selects the actual DFF input needs to be told to use the
// FACADE_SLICE DI input instead of the FACADE_SLICE M input.
lc->params[ctx->id("REG0_SD")] = std::string("0");
// FIXME: This will have to change once we support FFs with reset value of 1.
lc->params[ctx->id("REG0_REGSET")] = std::string("RESET");
replace_port(dff, ctx->id("CLK"), lc, ctx->id("CLK"));
replace_port(dff, ctx->id("DI"), lc, ctx->id("DI0"));
replace_port(dff, ctx->id("LSR"), lc, ctx->id("LSR"));
replace_port(dff, ctx->id("Q"), lc, ctx->id("Q0"));
}
void nxio_to_iob(Context *ctx, CellInfo *nxio, CellInfo *iob, std::unordered_set<IdString> &todelete_cells) {}
NEXTPNR_NAMESPACE_END
<commit_msg>machxo2: Fix reversed interpretation of REG_SD config bits.<commit_after>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2019 David Shah <[email protected]>
* Copyright (C) 2021 William D. Jones <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "cells.h"
#include "design_utils.h"
#include "log.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
void add_port(const Context *ctx, CellInfo *cell, std::string name, PortType dir)
{
IdString id = ctx->id(name);
NPNR_ASSERT(cell->ports.count(id) == 0);
cell->ports[id] = PortInfo{id, nullptr, dir};
}
void add_port(const Context *ctx, CellInfo *cell, IdString id, PortType dir)
{
NPNR_ASSERT(cell->ports.count(id) == 0);
cell->ports[id] = PortInfo{id, nullptr, dir};
}
std::unique_ptr<CellInfo> create_machxo2_cell(Context *ctx, IdString type, std::string name)
{
static int auto_idx = 0;
std::unique_ptr<CellInfo> new_cell = std::unique_ptr<CellInfo>(new CellInfo());
if (name.empty()) {
new_cell->name = ctx->id("$nextpnr_" + type.str(ctx) + "_" + std::to_string(auto_idx++));
} else {
new_cell->name = ctx->id(name);
}
new_cell->type = type;
if (type == id_FACADE_SLICE) {
new_cell->params[id_MODE] = std::string("LOGIC");
new_cell->params[id_GSR] = std::string("ENABLED");
new_cell->params[id_SRMODE] = std::string("LSR_OVER_CE");
new_cell->params[id_CEMUX] = std::string("1");
new_cell->params[id_CLKMUX] = std::string("0");
new_cell->params[id_LSRMUX] = std::string("LSR");
new_cell->params[id_LSRONMUX] = std::string("LSRMUX");
new_cell->params[id_LUT0_INITVAL] = Property(0xFFFF, 16);
new_cell->params[id_LUT1_INITVAL] = Property(0xFFFF, 16);
new_cell->params[id_REG0_SD] = std::string("1");
new_cell->params[id_REG1_SD] = std::string("1");
new_cell->params[id_REG0_REGSET] = std::string("SET");
new_cell->params[id_REG1_REGSET] = std::string("SET");
new_cell->params[id_REG0_REGMODE] = std::string("FF");
new_cell->params[id_REG1_REGMODE] = std::string("FF");
new_cell->params[id_CCU2_INJECT1_0] = std::string("YES");
new_cell->params[id_CCU2_INJECT1_1] = std::string("YES");
new_cell->params[id_WREMUX] = std::string("INV");
add_port(ctx, new_cell.get(), id_A0, PORT_IN);
add_port(ctx, new_cell.get(), id_B0, PORT_IN);
add_port(ctx, new_cell.get(), id_C0, PORT_IN);
add_port(ctx, new_cell.get(), id_D0, PORT_IN);
add_port(ctx, new_cell.get(), id_A1, PORT_IN);
add_port(ctx, new_cell.get(), id_B1, PORT_IN);
add_port(ctx, new_cell.get(), id_C1, PORT_IN);
add_port(ctx, new_cell.get(), id_D1, PORT_IN);
add_port(ctx, new_cell.get(), id_M0, PORT_IN);
add_port(ctx, new_cell.get(), id_M1, PORT_IN);
add_port(ctx, new_cell.get(), id_FCI, PORT_IN);
add_port(ctx, new_cell.get(), id_FXA, PORT_IN);
add_port(ctx, new_cell.get(), id_FXB, PORT_IN);
add_port(ctx, new_cell.get(), id_CLK, PORT_IN);
add_port(ctx, new_cell.get(), id_LSR, PORT_IN);
add_port(ctx, new_cell.get(), id_CE, PORT_IN);
add_port(ctx, new_cell.get(), id_DI0, PORT_IN);
add_port(ctx, new_cell.get(), id_DI1, PORT_IN);
add_port(ctx, new_cell.get(), id_WD0, PORT_IN);
add_port(ctx, new_cell.get(), id_WD1, PORT_IN);
add_port(ctx, new_cell.get(), id_WAD0, PORT_IN);
add_port(ctx, new_cell.get(), id_WAD1, PORT_IN);
add_port(ctx, new_cell.get(), id_WAD2, PORT_IN);
add_port(ctx, new_cell.get(), id_WAD3, PORT_IN);
add_port(ctx, new_cell.get(), id_WRE, PORT_IN);
add_port(ctx, new_cell.get(), id_WCK, PORT_IN);
add_port(ctx, new_cell.get(), id_F0, PORT_OUT);
add_port(ctx, new_cell.get(), id_Q0, PORT_OUT);
add_port(ctx, new_cell.get(), id_F1, PORT_OUT);
add_port(ctx, new_cell.get(), id_Q1, PORT_OUT);
add_port(ctx, new_cell.get(), id_FCO, PORT_OUT);
add_port(ctx, new_cell.get(), id_OFX0, PORT_OUT);
add_port(ctx, new_cell.get(), id_OFX1, PORT_OUT);
add_port(ctx, new_cell.get(), id_WDO0, PORT_OUT);
add_port(ctx, new_cell.get(), id_WDO1, PORT_OUT);
add_port(ctx, new_cell.get(), id_WDO2, PORT_OUT);
add_port(ctx, new_cell.get(), id_WDO3, PORT_OUT);
add_port(ctx, new_cell.get(), id_WADO0, PORT_OUT);
add_port(ctx, new_cell.get(), id_WADO1, PORT_OUT);
add_port(ctx, new_cell.get(), id_WADO2, PORT_OUT);
add_port(ctx, new_cell.get(), id_WADO3, PORT_OUT);
} else if (type == id_FACADE_IO) {
new_cell->params[id_DIR] = std::string("INPUT");
new_cell->attrs[ctx->id("IO_TYPE")] = std::string("LVCMOS33");
add_port(ctx, new_cell.get(), "PAD", PORT_INOUT);
add_port(ctx, new_cell.get(), "I", PORT_IN);
add_port(ctx, new_cell.get(), "EN", PORT_IN);
add_port(ctx, new_cell.get(), "O", PORT_OUT);
} else if (type == id_LUT4) {
new_cell->params[id_INIT] = Property(0, 16);
add_port(ctx, new_cell.get(), id_A, PORT_IN);
add_port(ctx, new_cell.get(), id_B, PORT_IN);
add_port(ctx, new_cell.get(), id_C, PORT_IN);
add_port(ctx, new_cell.get(), id_D, PORT_IN);
add_port(ctx, new_cell.get(), id_Z, PORT_OUT);
} else {
log_error("unable to create MachXO2 cell of type %s", type.c_str(ctx));
}
return new_cell;
}
void lut_to_lc(const Context *ctx, CellInfo *lut, CellInfo *lc, bool no_dff)
{
lc->params[ctx->id("LUT0_INITVAL")] = lut->params[ctx->id("INIT")];
for (std::string i : {"A", "B", "C", "D"}) {
IdString lut_port = ctx->id(i);
IdString lc_port = ctx->id(i + "0");
replace_port(lut, lut_port, lc, lc_port);
}
replace_port(lut, ctx->id("Z"), lc, ctx->id("F0"));
}
void dff_to_lc(const Context *ctx, CellInfo *dff, CellInfo *lc, bool pass_thru_lut)
{
// FIXME: This will have to change once we support FFs with reset value of 1.
lc->params[ctx->id("REG0_REGSET")] = std::string("RESET");
replace_port(dff, ctx->id("CLK"), lc, ctx->id("CLK"));
replace_port(dff, ctx->id("DI"), lc, ctx->id("DI0"));
replace_port(dff, ctx->id("LSR"), lc, ctx->id("LSR"));
replace_port(dff, ctx->id("Q"), lc, ctx->id("Q0"));
}
void nxio_to_iob(Context *ctx, CellInfo *nxio, CellInfo *iob, std::unordered_set<IdString> &todelete_cells) {}
NEXTPNR_NAMESPACE_END
<|endoftext|> |
<commit_before>#include <QCoreApplication>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QCache>
#include <QVector>
#include <QStringList>
#include <QSqlRecord>
#include <QUrl>
#include <QDir>
#include <cxxabi.h>
#include <QException>
#include "kernel.h"
#include "factory.h"
#include "angle.h"
#include "point.h"
#include "box.h"
#include "line.h"
#include "connectorinterface.h"
#include "abstractfactory.h"
#include "ilwisobjectfactory.h"
#include "ilwiscontext.h"
#include "catalogconnectorfactory.h"
#include "connectorfactory.h"
#include "catalogconnector.h"
#include "featurefactory.h"
#include "catalog.h"
#include "module.h"
#include "mastercatalog.h"
#include "version.h"
#include "issuelogger.h"
#include "errorobject.h"
#include "ilwisdata.h"
#include "domain.h"
#include "itemdomain.h"
#include "domainitem.h"
#include "identifieritem.h"
#include "thematicitem.h"
#include "range.h"
#include "itemrange.h"
#include "valuedefiner.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geometry.h"
#include "feature.h"
#include "operationmetadata.h"
#include "operationExpression.h"
#include "operation.h"
#include "commandhandler.h"
Ilwis::Kernel *Ilwis::Kernel::_kernel = 0;
using namespace Ilwis;
Catalog *createCatalog() {
return new Catalog();
}
Ilwis::Kernel* kernel() {
if (Kernel::_kernel == 0) {
Kernel::_kernel = new Kernel();
Kernel::_kernel->init();
}
return Kernel::_kernel;
}
Kernel::Kernel(QObject *parent) :
QObject(parent), _version(0)
{
}
void Kernel::init() {
if ( !_version.isNull())
return;
_version.reset(new Version());
_version->addBinaryVersion(Ilwis::Version::bvFORMAT30);
_version->addBinaryVersion(Ilwis::Version::bvFORMATFOREIGN);
_version->addBinaryVersion(Ilwis::Version::bvPOLYGONFORMAT37);
_version->addODFVersion("3.1");
_issues.reset( new IssueLogger());
_dbPublic = QSqlDatabase::addDatabase("QSQLITE");
_dbPublic.setHostName("localhost");
_dbPublic.setDatabaseName(":memory:");
_dbPublic.open();
_dbPublic.prepare();
CatalogConnectorFactory *catfactory = new CatalogConnectorFactory();
addFactory(catfactory);
ConnectorFactory *confac = new ConnectorFactory();
addFactory(confac);
FeatureFactory *featureFac = new FeatureFactory();
featureFac->addCreator("feature", createFeature);
addFactory(featureFac);
_modules.addModules();
mastercatalog()->addContainer(QUrl("ilwis://system"));
// ItemRange::addCreateItem("ThematicItem", ThematicItem::createRange());
}
Kernel::~Kernel() {
_dbPublic.close();
}
const QVariant *Kernel::getFromTLS(const QString& key) const{
if (_caches.hasLocalData()) {
return _caches.localData()->object(key);
}
return 0;
}
void Kernel::setTLS(const QString& key, QVariant* data){
if (!_caches.hasLocalData())
_caches.setLocalData(new QCache<QString, QVariant>);
_caches.localData()->insert(key, data);
}
void Kernel::deleteTLS(const QString &key) {
if (_caches.hasLocalData())
_caches.localData()->remove(key);
}
QString Kernel::translate(const QString& s) const {
//TODO implement translator class here and load in in the application object
return s;
}
const SPVersion& Kernel::version() const{
return _version;
}
PublicDatabase &Kernel::database()
{
return _dbPublic;
}
QScopedPointer<IssueLogger>& Kernel::issues()
{
return _issues;
}
void Kernel::addFactory(FactoryInterface *fac)
{
QString key = fac->key().toLower();
if (!_masterfactory.contains(key)) {
_masterfactory[key] = fac;
}
}
QString Kernel::demangle(const char *mangled_name)
{
int status;
char *realname = abi::__cxa_demangle(mangled_name,0,0,&status);
QString type(realname);
free(realname);
return type;
}
bool Kernel::error(const QString &message, const QString p1, const QString p2, const QString p3)
{
if ( p1 == sUNDEF)
issues()->log(TR(message));
if (p2 == sUNDEF)
issues()->log(TR(message).arg(p1));
else if ( p3 == sUNDEF)
issues()->log(TR(message).arg(p1, p2));
else
issues()->log(TR(message).arg(p1, p2, p3));
return false;
}
void Kernel::startClock(){
_start_clock = clock();
}
void Kernel::endClock(){
clock_t end = clock();
double total = (double)(end - _start_clock) / CLOCKS_PER_SEC;
qDebug() << "calc old in " << total << " seconds";
}
<commit_msg>use different sting construction in the main error message routine<commit_after>#include <QCoreApplication>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QCache>
#include <QVector>
#include <QStringList>
#include <QSqlRecord>
#include <QUrl>
#include <QDir>
#include <cxxabi.h>
#include <QException>
#include "kernel.h"
#include "factory.h"
#include "angle.h"
#include "point.h"
#include "box.h"
#include "line.h"
#include "connectorinterface.h"
#include "abstractfactory.h"
#include "ilwisobjectfactory.h"
#include "ilwiscontext.h"
#include "catalogconnectorfactory.h"
#include "connectorfactory.h"
#include "catalogconnector.h"
#include "featurefactory.h"
#include "catalog.h"
#include "module.h"
#include "mastercatalog.h"
#include "version.h"
#include "issuelogger.h"
#include "errorobject.h"
#include "ilwisdata.h"
#include "domain.h"
#include "itemdomain.h"
#include "domainitem.h"
#include "identifieritem.h"
#include "thematicitem.h"
#include "range.h"
#include "itemrange.h"
#include "valuedefiner.h"
#include "columndefinition.h"
#include "table.h"
#include "attributerecord.h"
#include "geometry.h"
#include "feature.h"
#include "operationmetadata.h"
#include "operationExpression.h"
#include "operation.h"
#include "commandhandler.h"
Ilwis::Kernel *Ilwis::Kernel::_kernel = 0;
using namespace Ilwis;
Catalog *createCatalog() {
return new Catalog();
}
Ilwis::Kernel* kernel() {
if (Kernel::_kernel == 0) {
Kernel::_kernel = new Kernel();
Kernel::_kernel->init();
}
return Kernel::_kernel;
}
Kernel::Kernel(QObject *parent) :
QObject(parent), _version(0)
{
}
void Kernel::init() {
if ( !_version.isNull())
return;
_version.reset(new Version());
_version->addBinaryVersion(Ilwis::Version::bvFORMAT30);
_version->addBinaryVersion(Ilwis::Version::bvFORMATFOREIGN);
_version->addBinaryVersion(Ilwis::Version::bvPOLYGONFORMAT37);
_version->addODFVersion("3.1");
_issues.reset( new IssueLogger());
_dbPublic = QSqlDatabase::addDatabase("QSQLITE");
_dbPublic.setHostName("localhost");
_dbPublic.setDatabaseName(":memory:");
_dbPublic.open();
_dbPublic.prepare();
CatalogConnectorFactory *catfactory = new CatalogConnectorFactory();
addFactory(catfactory);
ConnectorFactory *confac = new ConnectorFactory();
addFactory(confac);
FeatureFactory *featureFac = new FeatureFactory();
featureFac->addCreator("feature", createFeature);
addFactory(featureFac);
_modules.addModules();
mastercatalog()->addContainer(QUrl("ilwis://system"));
// ItemRange::addCreateItem("ThematicItem", ThematicItem::createRange());
}
Kernel::~Kernel() {
_dbPublic.close();
}
const QVariant *Kernel::getFromTLS(const QString& key) const{
if (_caches.hasLocalData()) {
return _caches.localData()->object(key);
}
return 0;
}
void Kernel::setTLS(const QString& key, QVariant* data){
if (!_caches.hasLocalData())
_caches.setLocalData(new QCache<QString, QVariant>);
_caches.localData()->insert(key, data);
}
void Kernel::deleteTLS(const QString &key) {
if (_caches.hasLocalData())
_caches.localData()->remove(key);
}
QString Kernel::translate(const QString& s) const {
//TODO implement translator class here and load in in the application object
return s;
}
const SPVersion& Kernel::version() const{
return _version;
}
PublicDatabase &Kernel::database()
{
return _dbPublic;
}
QScopedPointer<IssueLogger>& Kernel::issues()
{
return _issues;
}
void Kernel::addFactory(FactoryInterface *fac)
{
QString key = fac->key().toLower();
if (!_masterfactory.contains(key)) {
_masterfactory[key] = fac;
}
}
QString Kernel::demangle(const char *mangled_name)
{
int status;
char *realname = abi::__cxa_demangle(mangled_name,0,0,&status);
QString type(realname);
free(realname);
return type;
}
bool Kernel::error(const QString &message, const QString p1, const QString p2, const QString p3)
{
if ( p1 == sUNDEF)
issues()->log(TR(message));
if (p2 == sUNDEF)
issues()->log(TR(message).arg(p1));
else if ( p3 == sUNDEF)
issues()->log(TR(message).arg(p1, p2));
else
issues()->log(TR(message).arg(p1).arg(p2).arg(p3));
return false;
}
void Kernel::startClock(){
_start_clock = clock();
}
void Kernel::endClock(){
clock_t end = clock();
double total = (double)(end - _start_clock) / CLOCKS_PER_SEC;
qDebug() << "calc old in " << total << " seconds";
}
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2014 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "WebSocketMessagingStubFactory.h"
#include <QtCore/QDebug>
#include <QtCore/QEventLoop>
#include <QtWebSockets/QWebSocket>
#include <assert.h>
#include "websocket/WebSocketMessagingStub.h"
#include "joynr/system/RoutingTypes/Address.h"
#include "joynr/system/RoutingTypes/WebSocketAddress.h"
#include "joynr/system/RoutingTypes/WebSocketClientAddress.h"
#include "joynr/TypeUtil.h"
namespace joynr
{
joynr_logging::Logger* WebSocketMessagingStubFactory::logger =
joynr_logging::Logging::getInstance()->getLogger("MSG", "WebSocketMessagingStubFactory");
WebSocketMessagingStubFactory::WebSocketMessagingStubFactory(QObject* parent)
: QObject(parent), serverStubMap(), clientStubMap(), mutex()
{
}
bool WebSocketMessagingStubFactory::canCreate(
const joynr::system::RoutingTypes::Address& destAddress)
{
return dynamic_cast<const system::RoutingTypes::WebSocketAddress*>(&destAddress) ||
dynamic_cast<const system::RoutingTypes::WebSocketClientAddress*>(&destAddress);
}
std::shared_ptr<IMessaging> WebSocketMessagingStubFactory::create(
const joynr::system::RoutingTypes::Address& destAddress)
{
// if destination is a WS client address
if (auto webSocketClientAddress =
dynamic_cast<const system::RoutingTypes::WebSocketClientAddress*>(&destAddress)) {
// lookup address
{
std::lock_guard<std::mutex> lock(mutex);
if (clientStubMap.find(*webSocketClientAddress) == clientStubMap.cend()) {
LOG_ERROR(logger,
FormatString("No websocket found for address %1")
.arg(webSocketClientAddress->toString())
.str());
return std::shared_ptr<IMessaging>();
}
}
return clientStubMap[*webSocketClientAddress];
}
// if destination is a WS server address
if (const system::RoutingTypes::WebSocketAddress* webSocketServerAddress =
dynamic_cast<const system::RoutingTypes::WebSocketAddress*>(&destAddress)) {
// lookup address
{
std::lock_guard<std::mutex> lock(mutex);
if (serverStubMap.find(*webSocketServerAddress) == serverStubMap.cend()) {
LOG_ERROR(logger,
FormatString("No websocket found for address %1")
.arg(webSocketServerAddress->toString())
.str());
return std::shared_ptr<IMessaging>();
}
}
return serverStubMap[*webSocketServerAddress];
}
return std::shared_ptr<IMessaging>();
}
void WebSocketMessagingStubFactory::addClient(
const joynr::system::RoutingTypes::WebSocketClientAddress* clientAddress,
QWebSocket* webSocket)
{
WebSocketMessagingStub* wsClientStub = new WebSocketMessagingStub(clientAddress, webSocket);
connect(wsClientStub,
&WebSocketMessagingStub::closed,
this,
&WebSocketMessagingStubFactory::onMessagingStubClosed);
std::shared_ptr<IMessaging> clientStub(wsClientStub);
clientStubMap[*clientAddress] = clientStub;
}
void WebSocketMessagingStubFactory::removeClient(
const joynr::system::RoutingTypes::WebSocketClientAddress& clientAddress)
{
clientStubMap.erase(clientAddress);
}
void WebSocketMessagingStubFactory::addServer(
const joynr::system::RoutingTypes::WebSocketAddress& serverAddress,
QWebSocket* webSocket)
{
WebSocketMessagingStub* wsServerStub = new WebSocketMessagingStub(
new system::RoutingTypes::WebSocketAddress(serverAddress), webSocket);
connect(wsServerStub,
&WebSocketMessagingStub::closed,
this,
&WebSocketMessagingStubFactory::onMessagingStubClosed);
std::shared_ptr<IMessaging> serverStub(wsServerStub);
serverStubMap[serverAddress] = serverStub;
}
void WebSocketMessagingStubFactory::onMessagingStubClosed(
const system::RoutingTypes::Address& address)
{
LOG_DEBUG(
logger,
FormatString("removing messaging stub for address: %1").arg(address.toString()).str());
// if destination is a WS client address
if (auto webSocketClientAddress =
dynamic_cast<const system::RoutingTypes::WebSocketClientAddress*>(&address)) {
clientStubMap.erase(*webSocketClientAddress);
}
if (auto webSocketServerAddress =
dynamic_cast<const system::RoutingTypes::WebSocketAddress*>(&address)) {
serverStubMap.erase(*webSocketServerAddress);
}
}
QUrl WebSocketMessagingStubFactory::convertWebSocketAddressToUrl(
const system::RoutingTypes::WebSocketAddress& address)
{
return QUrl(QString("%0://%1:%2%3")
.arg(QString::fromStdString(
joynr::system::RoutingTypes::WebSocketProtocol::getLiteral(
address.getProtocol())).toLower())
.arg(QString::fromStdString(address.getHost()))
.arg(address.getPort())
.arg(QString::fromStdString(address.getPath())));
}
} // namespace joynr
<commit_msg>[C++] Adapt logic in WebSocketMessagingStubFactory.onMessagingStubClosed<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2014 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "WebSocketMessagingStubFactory.h"
#include <QtCore/QDebug>
#include <QtCore/QEventLoop>
#include <QtWebSockets/QWebSocket>
#include <assert.h>
#include "websocket/WebSocketMessagingStub.h"
#include "joynr/system/RoutingTypes/Address.h"
#include "joynr/system/RoutingTypes/WebSocketAddress.h"
#include "joynr/system/RoutingTypes/WebSocketClientAddress.h"
#include "joynr/TypeUtil.h"
namespace joynr
{
joynr_logging::Logger* WebSocketMessagingStubFactory::logger =
joynr_logging::Logging::getInstance()->getLogger("MSG", "WebSocketMessagingStubFactory");
WebSocketMessagingStubFactory::WebSocketMessagingStubFactory(QObject* parent)
: QObject(parent), serverStubMap(), clientStubMap(), mutex()
{
}
bool WebSocketMessagingStubFactory::canCreate(
const joynr::system::RoutingTypes::Address& destAddress)
{
return dynamic_cast<const system::RoutingTypes::WebSocketAddress*>(&destAddress) ||
dynamic_cast<const system::RoutingTypes::WebSocketClientAddress*>(&destAddress);
}
std::shared_ptr<IMessaging> WebSocketMessagingStubFactory::create(
const joynr::system::RoutingTypes::Address& destAddress)
{
// if destination is a WS client address
if (auto webSocketClientAddress =
dynamic_cast<const system::RoutingTypes::WebSocketClientAddress*>(&destAddress)) {
// lookup address
{
std::lock_guard<std::mutex> lock(mutex);
if (clientStubMap.find(*webSocketClientAddress) == clientStubMap.cend()) {
LOG_ERROR(logger,
FormatString("No websocket found for address %1")
.arg(webSocketClientAddress->toString())
.str());
return std::shared_ptr<IMessaging>();
}
}
return clientStubMap[*webSocketClientAddress];
}
// if destination is a WS server address
if (const system::RoutingTypes::WebSocketAddress* webSocketServerAddress =
dynamic_cast<const system::RoutingTypes::WebSocketAddress*>(&destAddress)) {
// lookup address
{
std::lock_guard<std::mutex> lock(mutex);
if (serverStubMap.find(*webSocketServerAddress) == serverStubMap.cend()) {
LOG_ERROR(logger,
FormatString("No websocket found for address %1")
.arg(webSocketServerAddress->toString())
.str());
return std::shared_ptr<IMessaging>();
}
}
return serverStubMap[*webSocketServerAddress];
}
return std::shared_ptr<IMessaging>();
}
void WebSocketMessagingStubFactory::addClient(
const joynr::system::RoutingTypes::WebSocketClientAddress* clientAddress,
QWebSocket* webSocket)
{
WebSocketMessagingStub* wsClientStub = new WebSocketMessagingStub(clientAddress, webSocket);
connect(wsClientStub,
&WebSocketMessagingStub::closed,
this,
&WebSocketMessagingStubFactory::onMessagingStubClosed);
std::shared_ptr<IMessaging> clientStub(wsClientStub);
clientStubMap[*clientAddress] = clientStub;
}
void WebSocketMessagingStubFactory::removeClient(
const joynr::system::RoutingTypes::WebSocketClientAddress& clientAddress)
{
clientStubMap.erase(clientAddress);
}
void WebSocketMessagingStubFactory::addServer(
const joynr::system::RoutingTypes::WebSocketAddress& serverAddress,
QWebSocket* webSocket)
{
WebSocketMessagingStub* wsServerStub = new WebSocketMessagingStub(
new system::RoutingTypes::WebSocketAddress(serverAddress), webSocket);
connect(wsServerStub,
&WebSocketMessagingStub::closed,
this,
&WebSocketMessagingStubFactory::onMessagingStubClosed);
std::shared_ptr<IMessaging> serverStub(wsServerStub);
serverStubMap[serverAddress] = serverStub;
}
void WebSocketMessagingStubFactory::onMessagingStubClosed(
const system::RoutingTypes::Address& address)
{
LOG_DEBUG(
logger,
FormatString("removing messaging stub for address: %1").arg(address.toString()).str());
// if destination is a WS client address
if (auto webSocketClientAddress =
dynamic_cast<const system::RoutingTypes::WebSocketClientAddress*>(&address)) {
clientStubMap.erase(*webSocketClientAddress);
} else if (auto webSocketServerAddress =
dynamic_cast<const system::RoutingTypes::WebSocketAddress*>(&address)) {
serverStubMap.erase(*webSocketServerAddress);
}
}
QUrl WebSocketMessagingStubFactory::convertWebSocketAddressToUrl(
const system::RoutingTypes::WebSocketAddress& address)
{
return QUrl(QString("%0://%1:%2%3")
.arg(QString::fromStdString(
joynr::system::RoutingTypes::WebSocketProtocol::getLiteral(
address.getProtocol())).toLower())
.arg(QString::fromStdString(address.getHost()))
.arg(address.getPort())
.arg(QString::fromStdString(address.getPath())));
}
} // namespace joynr
<|endoftext|> |
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2013 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/JoynrRuntime.h"
#include "JoynrClusterControllerRuntime.h"
#include "joynr/SettingsMerger.h"
namespace joynr
{
JoynrRuntime* JoynrRuntime::createRuntime(const QString& pathToLibjoynrSettings,
const QString& pathToMessagingSettings)
{
QSettings* settings = SettingsMerger::mergeSettings(pathToLibjoynrSettings);
SettingsMerger::mergeSettings(pathToMessagingSettings, settings);
return JoynrClusterControllerRuntime::create(settings);
}
} // namespace joynr
<commit_msg>[cpp] Fix cluster controller runtime not defining addBroadcast()<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2013 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/JoynrRuntime.h"
#include "JoynrClusterControllerRuntime.h"
#include "joynr/SettingsMerger.h"
namespace joynr
{
JoynrRuntime* JoynrRuntime::createRuntime(const QString& pathToLibjoynrSettings,
const QString& pathToMessagingSettings)
{
QSettings* settings = SettingsMerger::mergeSettings(pathToLibjoynrSettings);
SettingsMerger::mergeSettings(pathToMessagingSettings, settings);
return JoynrClusterControllerRuntime::create(settings);
}
void JoynrRuntime::addBroadcastFilter(QSharedPointer<IBroadcastFilter> filter)
{
if (!publicationManager) {
throw JoynrException("Exception in JoynrRuntime: PublicationManager not created yet.");
}
publicationManager->addBroadcastFilter(filter);
}
} // namespace joynr
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <mutex>
#include "../Characters/Format.h"
#include "../Characters/StringBuilder.h"
#include "../Execution/Exceptions.h"
#include "../Execution/StringException.h"
#include "../Streams/InputStream.h"
#include "BLOB.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Streams;
using Memory::BLOB;
/*
********************************************************************************
************************* Memory::BLOB::BasicRep_ ******************************
********************************************************************************
*/
namespace {
size_t len_ (const initializer_list<pair<const Byte*, const Byte*>>& startEndPairs)
{
size_t sz = 0;
for (auto i : startEndPairs) {
sz += (i.second - i.first);
}
return sz;
}
size_t len_ (const initializer_list<BLOB>& list2Concatenate)
{
size_t sz = 0;
for (auto i : list2Concatenate) {
sz += i.GetSize ();
}
return sz;
}
}
BLOB::BasicRep_::BasicRep_ (const initializer_list<pair<const Byte*, const Byte*>>& startEndPairs)
: fData{len_ (startEndPairs)}
{
Byte* pb = fData.begin ();
for (auto i : startEndPairs) {
(void)::memcpy (pb, i.first, i.second - i.first);
pb += (i.second - i.first);
}
Ensure (pb == fData.end ());
}
BLOB::BasicRep_::BasicRep_ (const initializer_list<BLOB>& list2Concatenate)
: fData{len_ (list2Concatenate)}
{
Byte* pb = fData.begin ();
for (auto i : list2Concatenate) {
(void)::memcpy (pb, i.begin (), i.GetSize ());
pb += i.GetSize ();
}
Ensure (pb == fData.end ());
}
pair<const Byte*, const Byte*> BLOB::BasicRep_::GetBounds () const
{
Ensure (fData.begin () <= fData.end ());
return pair<const Byte*, const Byte*> (fData.begin (), fData.end ());
}
/*
********************************************************************************
************************** Memory::BLOB::ZeroRep_ ******************************
********************************************************************************
*/
pair<const Byte*, const Byte*> BLOB::ZeroRep_::GetBounds () const
{
return pair<const Byte*, const Byte*> (nullptr, nullptr);
}
/*
********************************************************************************
************************* Memory::BLOB::AdoptRep_ ******************************
********************************************************************************
*/
BLOB::AdoptRep_::AdoptRep_ (const Byte* start, const Byte* end)
: fStart (start)
, fEnd (end)
{
Require (start <= end);
}
BLOB::AdoptRep_::~AdoptRep_ ()
{
delete[] fStart;
}
pair<const Byte*, const Byte*> BLOB::AdoptRep_::GetBounds () const
{
Ensure (fStart <= fEnd);
return pair<const Byte*, const Byte*> (fStart, fEnd);
}
/*
********************************************************************************
******************* Memory::BLOB::AdoptAppLifetimeRep_ *************************
********************************************************************************
*/
BLOB::AdoptAppLifetimeRep_::AdoptAppLifetimeRep_ (const Byte* start, const Byte* end)
: fStart (start)
, fEnd (end)
{
Require (start <= end);
}
pair<const Byte*, const Byte*> BLOB::AdoptAppLifetimeRep_::GetBounds () const
{
Ensure (fStart <= fEnd);
return pair<const Byte*, const Byte*> (fStart, fEnd);
}
/*
********************************************************************************
********************************* Memory::BLOB *********************************
********************************************************************************
*/
namespace {
unsigned int HexChar2Num_ (char c)
{
if ('0' <= c and c <= '9') {
return c - '0';
}
if ('A' <= c and c <= 'F') {
return (c - 'A') + 10;
}
if ('a' <= c and c <= 'f') {
return (c - 'a') + 10;
}
Execution::Throw (Execution::StringException (L"Invalid HEX character in BLOB::Hex"));
}
}
BLOB BLOB::Hex (const char* s, const char* e)
{
SmallStackBuffer<Byte> buf;
for (const char* i = s; i < e; ++i) {
if (isspace (*i)) {
continue;
}
Byte b = HexChar2Num_ (*i);
++i;
if (i == e) {
Execution::Throw (Execution::StringException (L"Invalid partial HEX character in BLOB::Hex"));
}
b = (b << 4) + HexChar2Num_ (*i);
buf.push_back (b);
}
return BLOB (buf.begin (), buf.end ());
}
int BLOB::Compare (const BLOB& rhs) const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
pair<const Byte*, const Byte*> l = fRep_->GetBounds ();
pair<const Byte*, const Byte*> r = rhs.fRep_->GetBounds ();
size_t lSize = l.second - l.first;
size_t rSize = r.second - r.first;
size_t nCommonBytes = min (lSize, rSize);
int tmp = ::memcmp (l.first, r.first, nCommonBytes);
if (tmp != 0) {
return tmp;
}
// if tmp is zero, and same size - its really zero. But if lhs shorter than right, say lhs < right
if (lSize == rSize) {
return 0;
}
return (lSize < rSize) ? -1 : 1;
}
namespace {
using namespace Streams;
struct BLOBBINSTREAM_ : InputStream<Byte>::Ptr {
BLOBBINSTREAM_ (const BLOB& b)
: InputStream<Byte>::Ptr (make_shared<REP> (b))
{
}
struct REP : InputStream<Byte>::_IRep, private Debug::AssertExternallySynchronizedLock {
bool fIsOpenForRead_{true};
REP (const BLOB& b)
: fCur (b.begin ())
, fStart (b.begin ())
, fEnd (b.end ())
{
}
virtual bool IsSeekable () const override
{
return true;
}
virtual void CloseRead () override
{
Require (IsOpenRead ());
fIsOpenForRead_ = false;
}
virtual bool IsOpenRead () const override
{
return fIsOpenForRead_;
}
virtual size_t Read (Byte* intoStart, Byte* intoEnd) override
{
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
size_t bytesToRead = intoEnd - intoStart;
size_t bytesLeft = fEnd - fCur;
bytesToRead = min (bytesLeft, bytesToRead);
if (bytesToRead != 0) {
// see http://stackoverflow.com/questions/16362925/can-i-pass-a-null-pointer-to-memcmp -- illegal to pass nullptr to memcmp() even if size 0 (aka for memcpy)
(void)::memcpy (intoStart, fCur, bytesToRead);
fCur += bytesToRead;
}
return bytesToRead;
}
virtual Memory::Optional<size_t> ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override
{
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
return _ReadNonBlocking_ReferenceImplementation_ForNonblockingUpstream (intoStart, intoEnd, fEnd - fCur);
}
virtual SeekOffsetType GetReadOffset () const override
{
Require (IsOpenRead ());
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
return fCur - fStart;
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (IsOpenRead ());
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (offset > (fEnd - fStart)) {
Execution::Throw (std::range_error ("seek"));
}
fCur = fStart + offset;
} break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fCur - fStart;
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (newOffset > (fEnd - fStart)) {
Execution::Throw (std::range_error ("seek"));
}
fCur = fStart + newOffset;
} break;
case Whence::eFromEnd: {
Streams::SeekOffsetType curOffset = fCur - fStart;
Streams::SignedSeekOffsetType newOffset = (fEnd - fStart) + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (newOffset > (fEnd - fStart)) {
Execution::Throw (std::range_error ("seek"));
}
fCur = fStart + newOffset;
} break;
}
Ensure ((fStart <= fCur) and (fCur <= fEnd));
return GetReadOffset ();
}
const Byte* fCur;
const Byte* fStart;
const Byte* fEnd;
};
};
}
template <>
Streams::InputStream<Byte>::Ptr BLOB::As () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return BLOBBINSTREAM_{*this};
}
Characters::String BLOB::AsHex (size_t maxBytesToShow) const
{
// @todo Could be more efficient
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
StringBuilder sb;
size_t cnt{};
for (Byte b : *this) {
if (cnt++ > maxBytesToShow) {
break;
}
sb += Characters::Format (L"%02x", b);
}
return sb.str ();
}
BLOB BLOB::Repeat (unsigned int count) const
{
// @todo - re-implement using powers of 2 - so fewer concats (maybe - prealloc / reserve so only one - using vector)
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
BLOB tmp = *this;
for (unsigned int i = 1; i < count; ++i) {
tmp = tmp + *this;
}
return tmp;
}
BLOB BLOB::Slice (size_t startAt, size_t endAt) const
{
Require (startAt <= endAt);
Require (endAt < size ());
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return BLOB (begin () + startAt, begin () + endAt);
}
String BLOB::ToString (size_t maxBytesToShow) const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
if (size () > maxBytesToShow) {
String hexStr = AsHex (maxBytesToShow + 1); // so we can replace/elispis with LimitLength ()
size_t maxStrLen = maxBytesToShow < numeric_limits<size_t>::max () / 2 ? maxBytesToShow * 2 : maxBytesToShow;
return Characters::Format (L"[%d bytes: ", size ()) + hexStr.LimitLength (maxStrLen) + L"]";
}
else {
return Characters::Format (L"[%d bytes: ", size ()) + AsHex () + L"]";
}
}
<commit_msg>cosmetic<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <mutex>
#include "../Characters/Format.h"
#include "../Characters/StringBuilder.h"
#include "../Execution/Exceptions.h"
#include "../Execution/StringException.h"
#include "../Streams/InputStream.h"
#include "BLOB.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Foundation::Streams;
using Memory::BLOB;
/*
********************************************************************************
************************* Memory::BLOB::BasicRep_ ******************************
********************************************************************************
*/
namespace {
size_t len_ (const initializer_list<pair<const Byte*, const Byte*>>& startEndPairs)
{
size_t sz = 0;
for (auto i : startEndPairs) {
sz += (i.second - i.first);
}
return sz;
}
size_t len_ (const initializer_list<BLOB>& list2Concatenate)
{
size_t sz = 0;
for (auto i : list2Concatenate) {
sz += i.GetSize ();
}
return sz;
}
}
BLOB::BasicRep_::BasicRep_ (const initializer_list<pair<const Byte*, const Byte*>>& startEndPairs)
: fData{len_ (startEndPairs)}
{
Byte* pb = fData.begin ();
for (auto i : startEndPairs) {
(void)::memcpy (pb, i.first, i.second - i.first);
pb += (i.second - i.first);
}
Ensure (pb == fData.end ());
}
BLOB::BasicRep_::BasicRep_ (const initializer_list<BLOB>& list2Concatenate)
: fData{len_ (list2Concatenate)}
{
Byte* pb = fData.begin ();
for (auto i : list2Concatenate) {
(void)::memcpy (pb, i.begin (), i.GetSize ());
pb += i.GetSize ();
}
Ensure (pb == fData.end ());
}
pair<const Byte*, const Byte*> BLOB::BasicRep_::GetBounds () const
{
Ensure (fData.begin () <= fData.end ());
return pair<const Byte*, const Byte*> (fData.begin (), fData.end ());
}
/*
********************************************************************************
************************** Memory::BLOB::ZeroRep_ ******************************
********************************************************************************
*/
pair<const Byte*, const Byte*> BLOB::ZeroRep_::GetBounds () const
{
return pair<const Byte*, const Byte*> (nullptr, nullptr);
}
/*
********************************************************************************
************************* Memory::BLOB::AdoptRep_ ******************************
********************************************************************************
*/
BLOB::AdoptRep_::AdoptRep_ (const Byte* start, const Byte* end)
: fStart (start)
, fEnd (end)
{
Require (start <= end);
}
BLOB::AdoptRep_::~AdoptRep_ ()
{
delete[] fStart;
}
pair<const Byte*, const Byte*> BLOB::AdoptRep_::GetBounds () const
{
Ensure (fStart <= fEnd);
return pair<const Byte*, const Byte*> (fStart, fEnd);
}
/*
********************************************************************************
******************* Memory::BLOB::AdoptAppLifetimeRep_ *************************
********************************************************************************
*/
BLOB::AdoptAppLifetimeRep_::AdoptAppLifetimeRep_ (const Byte* start, const Byte* end)
: fStart (start)
, fEnd (end)
{
Require (start <= end);
}
pair<const Byte*, const Byte*> BLOB::AdoptAppLifetimeRep_::GetBounds () const
{
Ensure (fStart <= fEnd);
return pair<const Byte*, const Byte*> (fStart, fEnd);
}
/*
********************************************************************************
********************************* Memory::BLOB *********************************
********************************************************************************
*/
namespace {
Byte HexChar2Num_ (char c)
{
if ('0' <= c and c <= '9') {
return c - '0';
}
if ('A' <= c and c <= 'F') {
return (c - 'A') + 10;
}
if ('a' <= c and c <= 'f') {
return (c - 'a') + 10;
}
Execution::Throw (Execution::StringException (L"Invalid HEX character in BLOB::Hex"));
}
}
BLOB BLOB::Hex (const char* s, const char* e)
{
SmallStackBuffer<Byte> buf;
for (const char* i = s; i < e; ++i) {
if (isspace (*i)) {
continue;
}
Byte b = HexChar2Num_ (*i);
++i;
if (i == e) {
Execution::Throw (Execution::StringException (L"Invalid partial HEX character in BLOB::Hex"));
}
b = (b << 4) + HexChar2Num_ (*i);
buf.push_back (b);
}
return BLOB (buf.begin (), buf.end ());
}
int BLOB::Compare (const BLOB& rhs) const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
pair<const Byte*, const Byte*> l = fRep_->GetBounds ();
pair<const Byte*, const Byte*> r = rhs.fRep_->GetBounds ();
size_t lSize = l.second - l.first;
size_t rSize = r.second - r.first;
size_t nCommonBytes = min (lSize, rSize);
int tmp = ::memcmp (l.first, r.first, nCommonBytes);
if (tmp != 0) {
return tmp;
}
// if tmp is zero, and same size - its really zero. But if lhs shorter than right, say lhs < right
if (lSize == rSize) {
return 0;
}
return (lSize < rSize) ? -1 : 1;
}
namespace {
using namespace Streams;
struct BLOBBINSTREAM_ : InputStream<Byte>::Ptr {
BLOBBINSTREAM_ (const BLOB& b)
: InputStream<Byte>::Ptr (make_shared<REP> (b))
{
}
struct REP : InputStream<Byte>::_IRep, private Debug::AssertExternallySynchronizedLock {
bool fIsOpenForRead_{true};
REP (const BLOB& b)
: fCur (b.begin ())
, fStart (b.begin ())
, fEnd (b.end ())
{
}
virtual bool IsSeekable () const override
{
return true;
}
virtual void CloseRead () override
{
Require (IsOpenRead ());
fIsOpenForRead_ = false;
}
virtual bool IsOpenRead () const override
{
return fIsOpenForRead_;
}
virtual size_t Read (Byte* intoStart, Byte* intoEnd) override
{
RequireNotNull (intoStart);
RequireNotNull (intoEnd);
Require (intoStart < intoEnd);
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
size_t bytesToRead = intoEnd - intoStart;
size_t bytesLeft = fEnd - fCur;
bytesToRead = min (bytesLeft, bytesToRead);
if (bytesToRead != 0) {
// see http://stackoverflow.com/questions/16362925/can-i-pass-a-null-pointer-to-memcmp -- illegal to pass nullptr to memcmp() even if size 0 (aka for memcpy)
(void)::memcpy (intoStart, fCur, bytesToRead);
fCur += bytesToRead;
}
return bytesToRead;
}
virtual Memory::Optional<size_t> ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override
{
Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1);
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
return _ReadNonBlocking_ReferenceImplementation_ForNonblockingUpstream (intoStart, intoEnd, fEnd - fCur);
}
virtual SeekOffsetType GetReadOffset () const override
{
Require (IsOpenRead ());
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
return fCur - fStart;
}
virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
Require (IsOpenRead ());
switch (whence) {
case Whence::eFromStart: {
if (offset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (offset > (fEnd - fStart)) {
Execution::Throw (std::range_error ("seek"));
}
fCur = fStart + offset;
} break;
case Whence::eFromCurrent: {
Streams::SeekOffsetType curOffset = fCur - fStart;
Streams::SignedSeekOffsetType newOffset = curOffset + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (newOffset > (fEnd - fStart)) {
Execution::Throw (std::range_error ("seek"));
}
fCur = fStart + newOffset;
} break;
case Whence::eFromEnd: {
Streams::SeekOffsetType curOffset = fCur - fStart;
Streams::SignedSeekOffsetType newOffset = (fEnd - fStart) + offset;
if (newOffset < 0) {
Execution::Throw (std::range_error ("seek"));
}
if (newOffset > (fEnd - fStart)) {
Execution::Throw (std::range_error ("seek"));
}
fCur = fStart + newOffset;
} break;
}
Ensure ((fStart <= fCur) and (fCur <= fEnd));
return GetReadOffset ();
}
const Byte* fCur;
const Byte* fStart;
const Byte* fEnd;
};
};
}
template <>
Streams::InputStream<Byte>::Ptr BLOB::As () const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return BLOBBINSTREAM_{*this};
}
Characters::String BLOB::AsHex (size_t maxBytesToShow) const
{
// @todo Could be more efficient
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
StringBuilder sb;
size_t cnt{};
for (Byte b : *this) {
if (cnt++ > maxBytesToShow) {
break;
}
sb += Characters::Format (L"%02x", b);
}
return sb.str ();
}
BLOB BLOB::Repeat (unsigned int count) const
{
// @todo - re-implement using powers of 2 - so fewer concats (maybe - prealloc / reserve so only one - using vector)
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
BLOB tmp = *this;
for (unsigned int i = 1; i < count; ++i) {
tmp = tmp + *this;
}
return tmp;
}
BLOB BLOB::Slice (size_t startAt, size_t endAt) const
{
Require (startAt <= endAt);
Require (endAt < size ());
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
return BLOB (begin () + startAt, begin () + endAt);
}
String BLOB::ToString (size_t maxBytesToShow) const
{
shared_lock<const AssertExternallySynchronizedLock> critSec{*this};
if (size () > maxBytesToShow) {
String hexStr = AsHex (maxBytesToShow + 1); // so we can replace/elispis with LimitLength ()
size_t maxStrLen = maxBytesToShow < numeric_limits<size_t>::max () / 2 ? maxBytesToShow * 2 : maxBytesToShow;
return Characters::Format (L"[%d bytes: ", size ()) + hexStr.LimitLength (maxStrLen) + L"]";
}
else {
return Characters::Format (L"[%d bytes: ", size ()) + AsHex () + L"]";
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
/*
* CompositingVisualLoop.cpp
*
* Created on: 16 janv. 2012
* Author: Jeremy Ringard
*/
//#define DEBUG_DRAW
#include <sofa/component/visualmodel/CompositingVisualLoop.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/simulation/common/VisualVisitor.h>
#include <sofa/simulation/common/UpdateContextVisitor.h>
#include <sofa/simulation/common/UpdateMappingVisitor.h>
#include <sofa/simulation/common/UpdateMappingEndEvent.h>
#include <sofa/simulation/common/PropagateEventVisitor.h>
#include <sofa/helper/AdvancedTimer.h>
namespace sofa
{
namespace component
{
namespace visualmodel
{
SOFA_DECL_CLASS(CompositingVisualLoop);
int CompositingVisualLoopClass = core::RegisterObject("Visual loop enabling multipass rendering. Needs multiple fbo data and a compositing shader")
.add< CompositingVisualLoop >()
;
CompositingVisualLoop::CompositingVisualLoop(simulation::Node* _gnode)
: simulation::DefaultVisualManagerLoop(_gnode),
vertFilename(initData(&vertFilename, (std::string) "shaders/compositing.vert", "vertFilename", "Set the vertex shader filename to load")),
fragFilename(initData(&fragFilename, (std::string) "shaders/compositing.frag", "fragFilename", "Set the fragment shader filename to load"))
{
//assert(gRoot);
}
CompositingVisualLoop::~CompositingVisualLoop()
{}
void CompositingVisualLoop::initVisual()
{}
void CompositingVisualLoop::init()
{
if (!gRoot)
gRoot = dynamic_cast<simulation::Node*>(this->getContext());
}
//should not be called if scene file is well formed
void CompositingVisualLoop::defaultRendering(sofa::core::visual::VisualParams* vparams)
{
vparams->pass() = sofa::core::visual::VisualParams::Std;
VisualDrawVisitor act ( vparams );
gRoot->execute ( &act );
vparams->pass() = sofa::core::visual::VisualParams::Transparent;
VisualDrawVisitor act2 ( vparams );
gRoot->execute ( &act2 );
}
void CompositingVisualLoop::drawStep(sofa::core::visual::VisualParams* vparams)
{
if ( !gRoot ) return;
//should not happen: the compositing loop relies on one or more rendered passes done by the VisualManagerPass component
if (gRoot->visualManager.empty())
{
serr << "CompositingVisualLoop: no VisualManagerPass found. Disable multipass rendering." << sendl;
defaultRendering(vparams);
}
//rendering sequence: call each VisualManagerPass elements, then composite the frames
else
{
Node::Sequence<core::visual::VisualManager>::iterator begin = gRoot->visualManager.begin(), end = gRoot->visualManager.end(), it;
VisualManagerPass* currentVMP;
bool stopLoop=false;
//preDraw sequence
it=begin;
for (it = begin; it != end; ++it)
{
(*it)->preDrawScene(vparams);
currentVMP=dynamic_cast<VisualManagerPass*>(*it);
if( currentVMP!=NULL && !currentVMP->isPrerendered())
{
#ifdef DEBUG_DRAW
std::cout<<"final pass is "<<currentVMP->getName()<< "end of predraw loop" <<std::endl;
#endif
break;
}
}
//Draw sequence
bool rendered = false; // true if a manager did the rendering
for (it = begin; it != end; ++it)
if ((*it)->drawScene(vparams)) { rendered = true; break; }
if (!rendered) // do the rendering
{
std::cerr << "VisualLoop error: no visualManager rendered the scene. Please make sure the final visualManager(Secondary)Pass has a renderToScreen=\"true\" attribute" << std::endl;
}
//postDraw sequence
Node::Sequence<core::visual::VisualManager>::reverse_iterator rbegin = gRoot->visualManager.rbegin(), rend = gRoot->visualManager.rend(), rit;
for (rit = rbegin; rit != rend; ++rit)
(*rit)->postDrawScene(vparams);
}
}
//render a fullscreen quad
void CompositingVisualLoop::traceFullScreenQuad()
{
float vxmax, vymax, vzmax ;
float vxmin, vymin, vzmin ;
float txmax,tymax,tzmax;
float txmin,tymin,tzmin;
txmin = tymin = tzmin = 0.0;
vxmin = vymin = vzmin = -1.0;
vxmax = vymax = vzmax = txmax = tymax = tzmax = 1.0;
glBegin(GL_QUADS);
{
glTexCoord3f(txmin,tymax,0.0); glVertex3f(vxmin,vymax,0.0);
glTexCoord3f(txmax,tymax,0.0); glVertex3f(vxmax,vymax,0.0);
glTexCoord3f(txmax,tymin,0.0); glVertex3f(vxmax,vymin,0.0);
glTexCoord3f(txmin,tymin,0.0); glVertex3f(vxmin,vymin,0.0);
}
glEnd();
}
} // namespace visualmodel
} // namespace component
} //sofa
<commit_msg>r12105/sofa-dev : Now can be combined with other visualizations by checking the 'Advanced Rendering' option in the GUI<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
/*
* CompositingVisualLoop.cpp
*
* Created on: 16 janv. 2012
* Author: Jeremy Ringard
*/
//#define DEBUG_DRAW
#include <sofa/component/visualmodel/CompositingVisualLoop.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/component/visualmodel/VisualStyle.h>
#include <sofa/core/visual/DisplayFlags.h>
#include <sofa/simulation/common/VisualVisitor.h>
#include <sofa/simulation/common/UpdateContextVisitor.h>
#include <sofa/simulation/common/UpdateMappingVisitor.h>
#include <sofa/simulation/common/UpdateMappingEndEvent.h>
#include <sofa/simulation/common/PropagateEventVisitor.h>
#include <sofa/helper/AdvancedTimer.h>
namespace sofa
{
namespace component
{
namespace visualmodel
{
SOFA_DECL_CLASS(CompositingVisualLoop);
int CompositingVisualLoopClass = core::RegisterObject("Visual loop enabling multipass rendering. Needs multiple fbo data and a compositing shader")
.add< CompositingVisualLoop >()
;
CompositingVisualLoop::CompositingVisualLoop(simulation::Node* _gnode)
: simulation::DefaultVisualManagerLoop(_gnode),
vertFilename(initData(&vertFilename, (std::string) "shaders/compositing.vert", "vertFilename", "Set the vertex shader filename to load")),
fragFilename(initData(&fragFilename, (std::string) "shaders/compositing.frag", "fragFilename", "Set the fragment shader filename to load"))
{
//assert(gRoot);
}
CompositingVisualLoop::~CompositingVisualLoop()
{}
void CompositingVisualLoop::initVisual()
{}
void CompositingVisualLoop::init()
{
if (!gRoot)
gRoot = dynamic_cast<simulation::Node*>(this->getContext());
}
//should not be called if scene file is well formed
void CompositingVisualLoop::defaultRendering(sofa::core::visual::VisualParams* vparams)
{
vparams->pass() = sofa::core::visual::VisualParams::Std;
VisualDrawVisitor act ( vparams );
gRoot->execute ( &act );
vparams->pass() = sofa::core::visual::VisualParams::Transparent;
VisualDrawVisitor act2 ( vparams );
gRoot->execute ( &act2 );
}
void CompositingVisualLoop::drawStep(sofa::core::visual::VisualParams* vparams)
{
if ( !gRoot ) return;
sofa::core::visual::tristate renderingState;
//vparams->displayFlags().setShowRendering(false);
component::visualmodel::VisualStyle::SPtr visualStyle = NULL;
gRoot->get(visualStyle);
const sofa::core::visual::DisplayFlags &backupFlags = vparams->displayFlags();
const sofa::core::visual::DisplayFlags ¤tFlags = visualStyle->displayFlags.getValue();
vparams->displayFlags() = sofa::core::visual::merge_displayFlags(backupFlags, currentFlags);
renderingState = vparams->displayFlags().getShowRendering();
if (vparams->displayFlags().getShowRendering())
std::cout << "Advanced Rendering is ON" << std::endl;
else
{
std::cout << "Advanced Rendering is OFF" << std::endl;
defaultRendering(vparams);
}
//should not happen: the compositing loop relies on one or more rendered passes done by the VisualManagerPass component
if (gRoot->visualManager.empty())
{
serr << "CompositingVisualLoop: no VisualManagerPass found. Disable multipass rendering." << sendl;
defaultRendering(vparams);
}
//rendering sequence: call each VisualManagerPass elements, then composite the frames
else
{
if (renderingState == sofa::core::visual::tristate::false_value || renderingState == sofa::core::visual::tristate::neutral_value) return;
Node::Sequence<core::visual::VisualManager>::iterator begin = gRoot->visualManager.begin(), end = gRoot->visualManager.end(), it;
VisualManagerPass* currentVMP;
bool stopLoop=false;
//preDraw sequence
it=begin;
for (it = begin; it != end; ++it)
{
(*it)->preDrawScene(vparams);
currentVMP=dynamic_cast<VisualManagerPass*>(*it);
if( currentVMP!=NULL && !currentVMP->isPrerendered())
{
#ifdef DEBUG_DRAW
std::cout<<"final pass is "<<currentVMP->getName()<< "end of predraw loop" <<std::endl;
#endif
break;
}
}
//Draw sequence
bool rendered = false; // true if a manager did the rendering
for (it = begin; it != end; ++it)
if ((*it)->drawScene(vparams)) { rendered = true; break; }
if (!rendered) // do the rendering
{
std::cerr << "VisualLoop error: no visualManager rendered the scene. Please make sure the final visualManager(Secondary)Pass has a renderToScreen=\"true\" attribute" << std::endl;
}
//postDraw sequence
Node::Sequence<core::visual::VisualManager>::reverse_iterator rbegin = gRoot->visualManager.rbegin(), rend = gRoot->visualManager.rend(), rit;
for (rit = rbegin; rit != rend; ++rit)
(*rit)->postDrawScene(vparams);
}
}
} // namespace visualmodel
} // namespace component
} //sofa
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "mutation_fragment.hh"
#include "clustering_ranges_walker.hh"
namespace sstables {
class mutation_fragment_filter {
const schema& _schema;
query::clustering_key_filter_ranges _ranges;
clustering_ranges_walker _walker;
// True when we visited all the ranges or when we're after _fwd_end
bool _out_of_range = false;
streamed_mutation::forwarding _fwd;
/*
* _fwd_end reflects the end of the window set by fast forward to.
* If fast forwarding is not enabled then it is set to allow the whole range.
* Otherwise it is initially set to static row.
*/
position_in_partition _fwd_end;
size_t _last_lower_bound_counter = 0;
bool is_after_fwd_window(position_in_partition_view pos) const {
return _fwd && !position_in_partition::less_compare(_schema)(pos, _fwd_end);
}
public:
mutation_fragment_filter(const schema& schema,
const query::partition_slice& slice,
const partition_key& pk,
streamed_mutation::forwarding fwd)
: _schema(schema)
, _ranges(query::clustering_key_filter_ranges::get_ranges(schema, slice, pk))
, _walker(schema, _ranges.ranges(), schema.has_static_columns())
, _fwd(fwd)
, _fwd_end(fwd ? position_in_partition_view::before_all_clustered_rows()
: position_in_partition_view::after_all_clustered_rows())
{ }
mutation_fragment_filter(const mutation_fragment_filter&) = delete;
mutation_fragment_filter(mutation_fragment_filter&&) = delete;
mutation_fragment_filter& operator=(const mutation_fragment_filter&) = delete;
mutation_fragment_filter& operator=(mutation_fragment_filter&&) = delete;
enum class result {
ignore,
emit,
store_and_finish
};
result apply(const static_row& sr) {
bool inside_requested_ranges = _walker.advance_to(sr.position());
_out_of_range |= _walker.out_of_range();
if (!inside_requested_ranges) {
return result::ignore;
} else {
return result::emit;
}
}
result apply(const clustering_row& cr) {
bool inside_requested_ranges = _walker.advance_to(cr.position());
_out_of_range |= _walker.out_of_range();
if (!inside_requested_ranges) {
return result::ignore;
}
if (is_after_fwd_window(cr.position())) {
// This happens only when fwd is set
_out_of_range = true;
return result::store_and_finish;
} else {
return result::emit;
}
}
result apply(const range_tombstone& rt) {
bool inside_requested_ranges = _walker.advance_to(rt.position(), rt.end_position());
_out_of_range |= _walker.out_of_range();
if (!inside_requested_ranges) {
return result::ignore;
}
if (is_after_fwd_window(rt.position())) {
// This happens only when fwd is set
_out_of_range = true;
return result::store_and_finish;
} else {
return result::emit;
}
}
bool out_of_range() const {
return _out_of_range;
}
std::optional<position_in_partition_view> maybe_skip() {
if (!is_current_range_changed()) {
return {};
}
_last_lower_bound_counter = _walker.lower_bound_change_counter();
return _walker.lower_bound();
}
/*
* The method fast-forwards the current range to the passed position range.
* Returned optional is engaged iff the input range overlaps with any of the
* query ranges tracked by _walker.
*/
std::optional<position_in_partition_view> fast_forward_to(position_range r) {
assert(_fwd);
_walker.trim_front(r.start());
_fwd_end = std::move(r).end();
_out_of_range = !_walker.advance_to(r.start(), _fwd_end);
if (_out_of_range) {
return {};
}
_last_lower_bound_counter = _walker.lower_bound_change_counter();
return _walker.lower_bound();
}
/*
* Tells if current range has changed since last reader fast-forwarding or skip
*/
inline bool is_current_range_changed() const {
return (_last_lower_bound_counter != _walker.lower_bound_change_counter());
}
position_in_partition_view lower_bound() const {
return _walker.lower_bound();
}
position_in_partition_view uppermost_bound() const {
return _walker.uppermost_bound();
}
};
}; // namespace sstables
<commit_msg>sstables: mc: mutation_fragment_filter: Check the fast-forward window first<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "mutation_fragment.hh"
#include "clustering_ranges_walker.hh"
namespace sstables {
class mutation_fragment_filter {
const schema& _schema;
query::clustering_key_filter_ranges _ranges;
clustering_ranges_walker _walker;
// True when we visited all the ranges or when we're after _fwd_end
bool _out_of_range = false;
streamed_mutation::forwarding _fwd;
/*
* _fwd_end reflects the end of the window set by fast forward to.
* If fast forwarding is not enabled then it is set to allow the whole range.
* Otherwise it is initially set to static row.
*/
position_in_partition _fwd_end;
size_t _last_lower_bound_counter = 0;
bool is_after_fwd_window(position_in_partition_view pos) const {
return _fwd && !position_in_partition::less_compare(_schema)(pos, _fwd_end);
}
public:
mutation_fragment_filter(const schema& schema,
const query::partition_slice& slice,
const partition_key& pk,
streamed_mutation::forwarding fwd)
: _schema(schema)
, _ranges(query::clustering_key_filter_ranges::get_ranges(schema, slice, pk))
, _walker(schema, _ranges.ranges(), schema.has_static_columns())
, _fwd(fwd)
, _fwd_end(fwd ? position_in_partition_view::before_all_clustered_rows()
: position_in_partition_view::after_all_clustered_rows())
{ }
mutation_fragment_filter(const mutation_fragment_filter&) = delete;
mutation_fragment_filter(mutation_fragment_filter&&) = delete;
mutation_fragment_filter& operator=(const mutation_fragment_filter&) = delete;
mutation_fragment_filter& operator=(mutation_fragment_filter&&) = delete;
enum class result {
ignore,
emit,
store_and_finish
};
result apply(const static_row& sr) {
bool inside_requested_ranges = _walker.advance_to(sr.position());
_out_of_range |= _walker.out_of_range();
if (!inside_requested_ranges) {
return result::ignore;
} else {
return result::emit;
}
}
result apply(const clustering_row& cr) {
if (is_after_fwd_window(cr.position())) {
// This happens only when fwd is set
_out_of_range = true;
return result::store_and_finish;
}
bool inside_requested_ranges = _walker.advance_to(cr.position());
_out_of_range |= _walker.out_of_range();
if (!inside_requested_ranges) {
return result::ignore;
}
return result::emit;
}
result apply(const range_tombstone& rt) {
bool inside_requested_ranges = _walker.advance_to(rt.position(), rt.end_position());
_out_of_range |= _walker.out_of_range();
if (!inside_requested_ranges) {
return result::ignore;
}
if (is_after_fwd_window(rt.position())) {
// This happens only when fwd is set
_out_of_range = true;
return result::store_and_finish;
} else {
return result::emit;
}
}
bool out_of_range() const {
return _out_of_range;
}
std::optional<position_in_partition_view> maybe_skip() {
if (!is_current_range_changed()) {
return {};
}
_last_lower_bound_counter = _walker.lower_bound_change_counter();
return _walker.lower_bound();
}
/*
* The method fast-forwards the current range to the passed position range.
* Returned optional is engaged iff the input range overlaps with any of the
* query ranges tracked by _walker.
*/
std::optional<position_in_partition_view> fast_forward_to(position_range r) {
assert(_fwd);
_walker.trim_front(r.start());
_fwd_end = std::move(r).end();
_out_of_range = !_walker.advance_to(r.start(), _fwd_end);
if (_out_of_range) {
return {};
}
_last_lower_bound_counter = _walker.lower_bound_change_counter();
return _walker.lower_bound();
}
/*
* Tells if current range has changed since last reader fast-forwarding or skip
*/
inline bool is_current_range_changed() const {
return (_last_lower_bound_counter != _walker.lower_bound_change_counter());
}
position_in_partition_view lower_bound() const {
return _walker.lower_bound();
}
position_in_partition_view uppermost_bound() const {
return _walker.uppermost_bound();
}
};
}; // namespace sstables
<|endoftext|> |
<commit_before>// Copyright © 2017-2018 Dmitriy Khaustov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: [email protected]
// File created on: 2017.02.25
// Server.cpp
#include "../net/SslAcceptor.hpp"
#include "../thread/ThreadPool.hpp"
#include "Server.hpp"
#include "../net/ConnectionManager.hpp"
#include "../storage/DbManager.hpp"
#include "../extra/Applications.hpp"
#include "../transport/Transports.hpp"
#include "../telemetry/SysInfo.hpp"
#include "../services/Services.hpp"
#include "../utils/Daemon.hpp"
#include "../thread/TaskManager.hpp"
Server* Server::_instance = nullptr;
Server::Server(const std::shared_ptr<Config>& configs)
: _log("Server")
, _workerCount(0)
, _configs(configs)
{
if (_instance != nullptr)
{
throw std::runtime_error("Server already instantiated");
}
_instance = this;
_log.info("Server instantiate");
try
{
const auto& settings = _configs->getRoot()["core"];
std::string processName;
if (settings.lookupValue("processName", processName) && !processName.empty())
{
Daemon::SetProcessName(processName);
}
if (!settings.lookupValue("workers", _workerCount))
{
_workerCount = std::thread::hardware_concurrency();
}
if (_workerCount < 2)
{
throw std::runtime_error("Count of workers too few. Programm won't be work correctly");
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.warn("Core config not found");
}
catch (const std::exception& exception)
{
_log.error("Can't configure of core ← %s", exception.what());
}
try
{
const auto& settings = _configs->getRoot()["applications"];
for (const auto& setting : settings)
{
Applications::add(setting);
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.warn("Applications' config not found");
}
catch (const std::exception& exception)
{
_log.error("Can't init one of application ← %s", exception.what());
}
try
{
const auto& settings = _configs->getRoot()["databases"];
for (const auto& setting : settings)
{
try
{
DbManager::openPool(setting);
}
catch (const std::exception& exception)
{
_log.warn("Can't init one of database connection pool ← %s", exception.what());
}
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.warn("Databases' config not found");
}
try
{
const auto& settings = _configs->getRoot()["transports"];
for (const auto& setting : settings)
{
try
{
Transports::add(setting);
}
catch (const std::exception& exception)
{
_log.warn("Can't init one of transport ← %s", exception.what());
}
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.warn("Transports' config not found");
}
try
{
const auto& settings = _configs->getRoot()["services"];
for (const auto& setting : settings)
{
try
{
Services::add(setting);
}
catch (const std::exception& exception)
{
_log.error("Can't init one of service ← %s", exception.what());
}
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.error("Services' config not found");
}
SysInfo::start();
TaskManager::enqueue(
ConnectionManager::dispatch
);
}
Server::~Server()
{
_instance = nullptr;
_log.info("Server shutdown");
}
void Server::wait()
{
ThreadPool::wait();
}
bool Server::start()
{
if (!Transports::enableAll())
{
_log.info("Can't enable all services");
return false;
}
ThreadPool::setThreadNum(_workerCount);
_log.info("Server start (pid=%u)", getpid());
return true;
}
void Server::stop()
{
std::lock_guard<std::recursive_mutex> guard(_mutex);
Services::deactivateAll();
Transports::disableAll();
_log.info("Server stop");
}
<commit_msg>Changes in Server<commit_after>// Copyright © 2017-2018 Dmitriy Khaustov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: Dmitriy Khaustov aka xDimon
// Contacts: [email protected]
// File created on: 2017.02.25
// Server.cpp
#include "../net/SslAcceptor.hpp"
#include "../thread/ThreadPool.hpp"
#include "Server.hpp"
#include "../net/ConnectionManager.hpp"
#include "../storage/DbManager.hpp"
#include "../extra/Applications.hpp"
#include "../transport/Transports.hpp"
#include "../telemetry/SysInfo.hpp"
#include "../services/Services.hpp"
#include "../utils/Daemon.hpp"
#include "../thread/TaskManager.hpp"
Server* Server::_instance = nullptr;
Server::Server(const std::shared_ptr<Config>& configs)
: _log("Server")
, _workerCount(0)
, _configs(configs)
{
if (_instance != nullptr)
{
throw std::runtime_error("Server already instantiated");
}
_instance = this;
_log.info("Server instantiate");
try
{
const auto& settings = _configs->getRoot()["core"];
std::string timeZone;
if (settings.lookupValue("timeZone", timeZone) && !timeZone.empty())
{
setenv("TZ", timeZone.c_str(), 1);
tzset();
}
std::string processName;
if (settings.lookupValue("processName", processName) && !processName.empty())
{
Daemon::SetProcessName(processName);
}
if (!settings.lookupValue("workers", _workerCount))
{
_workerCount = std::thread::hardware_concurrency();
}
if (_workerCount < 2)
{
throw std::runtime_error("Count of workers too few. Programm won't be work correctly");
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.warn("Core config not found");
}
catch (const std::exception& exception)
{
_log.error("Can't configure of core ← %s", exception.what());
}
try
{
const auto& settings = _configs->getRoot()["applications"];
for (const auto& setting : settings)
{
Applications::add(setting);
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.warn("Applications' config not found");
}
catch (const std::exception& exception)
{
_log.error("Can't init one of application ← %s", exception.what());
}
try
{
const auto& settings = _configs->getRoot()["databases"];
for (const auto& setting : settings)
{
try
{
DbManager::openPool(setting);
}
catch (const std::exception& exception)
{
_log.warn("Can't init one of database connection pool ← %s", exception.what());
}
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.warn("Databases' config not found");
}
try
{
const auto& settings = _configs->getRoot()["transports"];
for (const auto& setting : settings)
{
try
{
Transports::add(setting);
}
catch (const std::exception& exception)
{
_log.warn("Can't init one of transport ← %s", exception.what());
}
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.warn("Transports' config not found");
}
try
{
const auto& settings = _configs->getRoot()["services"];
for (const auto& setting : settings)
{
try
{
Services::add(setting);
}
catch (const std::exception& exception)
{
_log.error("Can't init one of service ← %s", exception.what());
}
}
}
catch (const libconfig::SettingNotFoundException& exception)
{
_log.error("Services' config not found");
}
SysInfo::start();
TaskManager::enqueue(
ConnectionManager::dispatch
);
}
Server::~Server()
{
_instance = nullptr;
_log.info("Server shutdown");
}
void Server::wait()
{
ThreadPool::wait();
}
bool Server::start()
{
if (!Transports::enableAll())
{
_log.info("Can't enable all services");
return false;
}
ThreadPool::setThreadNum(_workerCount);
_log.info("Server start (pid=%u)", getpid());
return true;
}
void Server::stop()
{
std::lock_guard<std::recursive_mutex> guard(_mutex);
Services::deactivateAll();
Transports::disableAll();
_log.info("Server stop");
}
<|endoftext|> |
<commit_before>/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <signal.h>
#include "swoole_server.h"
namespace swoole {
using network::Socket;
ProcessFactory::ProcessFactory(Server *server) : Factory(server) {}
bool ProcessFactory::shutdown() {
int status;
if (swoole_kill(server_->gs->manager_pid, SIGTERM) < 0) {
swoole_sys_warning("kill(%d) failed", server_->gs->manager_pid);
}
if (swoole_waitpid(server_->gs->manager_pid, &status, 0) < 0) {
swoole_sys_warning("waitpid(%d) failed", server_->gs->manager_pid);
}
SW_LOOP_N(server_->worker_num) {
Worker *worker = &server_->workers[i];
server_->destroy_worker(worker);
}
return SW_OK;
}
ProcessFactory::~ProcessFactory() {
if (server_->stream_socket_file) {
unlink(server_->stream_socket_file);
sw_free(server_->stream_socket_file);
server_->stream_socket->free();
}
}
bool ProcessFactory::start() {
if (server_->dispatch_mode == Server::DISPATCH_STREAM) {
server_->stream_socket_file = swoole_string_format(64, "/tmp/swoole.%d.sock", server_->gs->master_pid);
if (server_->stream_socket_file == nullptr) {
return false;
}
Socket *sock = swoole::make_server_socket(SW_SOCK_UNIX_STREAM, server_->stream_socket_file);
if (sock == nullptr) {
return false;
}
sock->set_fd_option(1, 1);
server_->stream_socket = sock;
}
SW_LOOP_N(server_->worker_num) {
server_->create_worker(server_->get_worker(i));
}
SW_LOOP_N(server_->worker_num) {
auto _sock = new UnixSocket(true, SOCK_DGRAM);
if (!_sock->ready()) {
delete _sock;
return false;
}
pipes.emplace_back(_sock);
server_->workers[i].pipe_master = _sock->get_socket(true);
server_->workers[i].pipe_worker = _sock->get_socket(false);
server_->workers[i].pipe_object = _sock;
server_->store_pipe_fd(server_->workers[i].pipe_object);
}
server_->init_ipc_max_size();
if (server_->create_pipe_buffers() < 0) {
return false;
}
/**
* The manager process must be started first, otherwise it will have a thread fork
*/
if (server_->start_manager_process() < 0) {
swoole_warning("failed to start");
return false;
}
return true;
}
/**
* [ReactorThread] notify info to worker process
*/
bool ProcessFactory::notify(DataHead *ev) {
SendData task;
task.info = *ev;
task.data = nullptr;
return dispatch(&task);
}
/**
* [ReactorThread] dispatch request to worker
*/
bool ProcessFactory::dispatch(SendData *task) {
int fd = task->info.fd;
int target_worker_id = server_->schedule_worker(fd, task);
if (target_worker_id < 0) {
switch (target_worker_id) {
case Server::DISPATCH_RESULT_DISCARD_PACKET:
return false;
case Server::DISPATCH_RESULT_CLOSE_CONNECTION:
// TODO: close connection
return false;
default:
swoole_warning("invalid target worker id[%d]", target_worker_id);
return false;
}
}
if (Server::is_stream_event(task->info.type)) {
Connection *conn = server_->get_connection(fd);
if (conn == nullptr || conn->active == 0) {
swoole_warning("dispatch[type=%d] failed, connection#%d is not active", task->info.type, fd);
return false;
}
// server active close, discard data.
if (conn->closed) {
// Connection has been clsoed by server
if (!(task->info.type == SW_SERVER_EVENT_CLOSE && conn->close_force)) {
return true;
}
}
// converted fd to session_id
task->info.fd = conn->session_id;
task->info.server_fd = conn->server_fd;
}
Worker *worker = server_->get_worker(target_worker_id);
if (task->info.type == SW_SERVER_EVENT_RECV_DATA) {
sw_atomic_fetch_add(&worker->dispatch_count, 1);
}
SendData _task;
memcpy(&_task, task, sizeof(SendData));
network::Socket *pipe_socket =
server_->is_reactor_thread() ? server_->get_worker_pipe_socket(worker) : worker->pipe_master;
return server_->message_bus.write(pipe_socket, &_task);
}
static bool inline process_is_supported_send_yield(Server *serv, Connection *conn) {
if (!serv->is_hash_dispatch_mode()) {
return false;
} else {
return serv->schedule_worker(conn->fd, nullptr) == (int) SwooleG.process_id;
}
}
/**
* [Worker] send to client, proxy by reactor
*/
bool ProcessFactory::finish(SendData *resp) {
/**
* More than the output buffer
*/
if (resp->info.len > server_->output_buffer_size) {
swoole_error_log(SW_LOG_WARNING,
SW_ERROR_DATA_LENGTH_TOO_LARGE,
"The length of data [%u] exceeds the output buffer size[%u], "
"please use the sendfile, chunked transfer mode or adjust the output_buffer_size",
resp->info.len,
server_->output_buffer_size);
return false;
}
SessionId session_id = resp->info.fd;
Connection *conn;
if (resp->info.type != SW_SERVER_EVENT_CLOSE) {
conn = server_->get_connection_verify(session_id);
} else {
conn = server_->get_connection_verify_no_ssl(session_id);
}
if (!conn) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_NOT_EXIST, "session#%ld does not exists", session_id);
return false;
} else if ((conn->closed || conn->peer_closed) && resp->info.type != SW_SERVER_EVENT_CLOSE) {
swoole_error_log(SW_LOG_NOTICE,
SW_ERROR_SESSION_CLOSED,
"send %d bytes failed, because session#%ld is closed",
resp->info.len,
session_id);
return false;
} else if (conn->overflow &&
(resp->info.type == SW_SERVER_EVENT_SEND_DATA || resp->info.type == SW_SERVER_EVENT_SEND_FILE)) {
if (server_->send_yield && process_is_supported_send_yield(server_, conn)) {
swoole_set_last_error(SW_ERROR_OUTPUT_SEND_YIELD);
} else {
swoole_error_log(SW_LOG_WARNING,
SW_ERROR_OUTPUT_BUFFER_OVERFLOW,
"send failed, session=%ld output buffer overflow",
session_id);
}
return false;
}
if (server_->last_stream_socket) {
uint32_t _len = resp->info.len;
uint32_t _header = htonl(_len + sizeof(resp->info));
if (swoole_event_write(server_->last_stream_socket, (char *) &_header, sizeof(_header)) < 0) {
return false;
}
if (swoole_event_write(server_->last_stream_socket, &resp->info, sizeof(resp->info)) < 0) {
return false;
}
if (_len > 0 && swoole_event_write(server_->last_stream_socket, resp->data, _len) < 0) {
return false;
}
return true;
}
SendData task;
memcpy(&task, resp, sizeof(SendData));
task.info.fd = session_id;
task.info.reactor_id = conn->reactor_id;
task.info.server_fd = SwooleG.process_id;
swoole_trace("worker_id=%d, type=%d", SwooleG.process_id, task.info.type);
return server_->message_bus.write(server_->get_reactor_pipe_socket(session_id, task.info.reactor_id), &task);
}
bool ProcessFactory::end(SessionId session_id, int flags) {
SendData _send{};
DataHead info{};
_send.info.fd = session_id;
_send.info.len = 0;
_send.info.type = SW_SERVER_EVENT_CLOSE;
Connection *conn = server_->get_connection_verify_no_ssl(session_id);
if (!conn) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_NOT_EXIST, "session#%ld is closed", session_id);
return false;
}
// Reset send buffer, Immediately close the connection.
if (flags & Server::CLOSE_RESET) {
conn->close_reset = 1;
}
// Server is initiative to close the connection
if (flags & Server::CLOSE_ACTIVELY) {
conn->close_actively = 1;
}
swoole_trace_log(SW_TRACE_CLOSE, "session_id=%ld, fd=%d", session_id, conn->fd);
Worker *worker;
DataHead ev = {};
/**
* Only active shutdown needs to determine whether it is in the process of connection binding
*/
if (conn->close_actively && server_->is_hash_dispatch_mode()) {
/**
* The worker process is not currently bound to this connection,
* and needs to be forwarded to the correct worker process
*/
int worker_id = server_->schedule_worker(conn->fd, nullptr);
if (worker_id == (int) SwooleG.process_id) {
worker = server_->get_worker(worker_id);
ev.type = SW_SERVER_EVENT_CLOSE;
ev.fd = session_id;
ev.reactor_id = conn->reactor_id;
return server_->send_to_worker_from_worker(worker, &ev, sizeof(ev), SW_PIPE_MASTER) > 0;
}
}
if (conn->closing) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_CLOSING, "session#%ld is closing", session_id);
return false;
} else if (!(conn->close_force || conn->close_reset) && conn->closed) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_CLOSED, "session#%ld is closed", session_id);
return false;
}
if (server_->onClose != nullptr && !conn->closed) {
info.fd = session_id;
if (conn->close_actively) {
info.reactor_id = -1;
} else {
info.reactor_id = conn->reactor_id;
}
info.server_fd = conn->server_fd;
conn->closing = 1;
server_->onClose(server_, &info);
conn->closing = 0;
}
conn->closed = 1;
conn->close_errno = 0;
return finish(&_send);
}
} // namespace swoole
<commit_msg>fix tests<commit_after>/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <[email protected]> |
+----------------------------------------------------------------------+
*/
#include <signal.h>
#include "swoole_server.h"
namespace swoole {
using network::Socket;
ProcessFactory::ProcessFactory(Server *server) : Factory(server) {}
bool ProcessFactory::shutdown() {
int status;
if (swoole_kill(server_->gs->manager_pid, SIGTERM) < 0) {
swoole_sys_warning("kill(%d) failed", server_->gs->manager_pid);
}
if (swoole_waitpid(server_->gs->manager_pid, &status, 0) < 0) {
swoole_sys_warning("waitpid(%d) failed", server_->gs->manager_pid);
}
SW_LOOP_N(server_->worker_num) {
Worker *worker = &server_->workers[i];
server_->destroy_worker(worker);
}
return SW_OK;
}
ProcessFactory::~ProcessFactory() {
if (server_->stream_socket_file) {
unlink(server_->stream_socket_file);
sw_free(server_->stream_socket_file);
server_->stream_socket->free();
}
}
bool ProcessFactory::start() {
if (server_->dispatch_mode == Server::DISPATCH_STREAM) {
server_->stream_socket_file = swoole_string_format(64, "/tmp/swoole.%d.sock", server_->gs->master_pid);
if (server_->stream_socket_file == nullptr) {
return false;
}
Socket *sock = swoole::make_server_socket(SW_SOCK_UNIX_STREAM, server_->stream_socket_file);
if (sock == nullptr) {
return false;
}
sock->set_fd_option(1, 1);
server_->stream_socket = sock;
}
SW_LOOP_N(server_->worker_num) {
server_->create_worker(server_->get_worker(i));
}
SW_LOOP_N(server_->worker_num) {
auto _sock = new UnixSocket(true, SOCK_DGRAM);
if (!_sock->ready()) {
delete _sock;
return false;
}
pipes.emplace_back(_sock);
server_->workers[i].pipe_master = _sock->get_socket(true);
server_->workers[i].pipe_worker = _sock->get_socket(false);
server_->workers[i].pipe_object = _sock;
server_->store_pipe_fd(server_->workers[i].pipe_object);
}
server_->init_ipc_max_size();
if (server_->create_pipe_buffers() < 0) {
return false;
}
/**
* The manager process must be started first, otherwise it will have a thread fork
*/
if (server_->start_manager_process() < 0) {
swoole_warning("failed to start");
return false;
}
return true;
}
/**
* [ReactorThread] notify info to worker process
*/
bool ProcessFactory::notify(DataHead *ev) {
SendData task;
task.info = *ev;
task.data = nullptr;
return dispatch(&task);
}
/**
* [ReactorThread] dispatch request to worker
*/
bool ProcessFactory::dispatch(SendData *task) {
int fd = task->info.fd;
int target_worker_id = server_->schedule_worker(fd, task);
if (target_worker_id < 0) {
switch (target_worker_id) {
case Server::DISPATCH_RESULT_DISCARD_PACKET:
return false;
case Server::DISPATCH_RESULT_CLOSE_CONNECTION:
// TODO: close connection
return false;
default:
swoole_warning("invalid target worker id[%d]", target_worker_id);
return false;
}
}
if (Server::is_stream_event(task->info.type)) {
Connection *conn = server_->get_connection(fd);
if (conn == nullptr || conn->active == 0) {
swoole_warning("dispatch[type=%d] failed, connection#%d is not active", task->info.type, fd);
return false;
}
// server active close, discard data.
if (conn->closed) {
// Connection has been clsoed by server
if (!(task->info.type == SW_SERVER_EVENT_CLOSE && conn->close_force)) {
return true;
}
}
// converted fd to session_id
task->info.fd = conn->session_id;
task->info.server_fd = conn->server_fd;
}
Worker *worker = server_->get_worker(target_worker_id);
if (task->info.type == SW_SERVER_EVENT_RECV_DATA) {
sw_atomic_fetch_add(&worker->dispatch_count, 1);
}
SendData _task;
memcpy(&_task, task, sizeof(SendData));
network::Socket *pipe_socket =
server_->is_reactor_thread() ? server_->get_worker_pipe_socket(worker) : worker->pipe_master;
return server_->message_bus.write(pipe_socket, &_task);
}
static bool inline process_is_supported_send_yield(Server *serv, Connection *conn) {
if (!serv->is_hash_dispatch_mode()) {
return false;
} else {
return serv->schedule_worker(conn->fd, nullptr) == (int) SwooleG.process_id;
}
}
/**
* [Worker] send to client, proxy by reactor
*/
bool ProcessFactory::finish(SendData *resp) {
/**
* More than the output buffer
*/
if (resp->info.len > server_->output_buffer_size) {
swoole_error_log(SW_LOG_WARNING,
SW_ERROR_DATA_LENGTH_TOO_LARGE,
"The length of data [%u] exceeds the output buffer size[%u], "
"please use the sendfile, chunked transfer mode or adjust the output_buffer_size",
resp->info.len,
server_->output_buffer_size);
return false;
}
SessionId session_id = resp->info.fd;
Connection *conn;
if (resp->info.type != SW_SERVER_EVENT_CLOSE) {
conn = server_->get_connection_verify(session_id);
} else {
conn = server_->get_connection_verify_no_ssl(session_id);
}
if (!conn) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_NOT_EXIST, "session#%ld does not exists", session_id);
return false;
} else if ((conn->closed || conn->peer_closed) && resp->info.type != SW_SERVER_EVENT_CLOSE) {
swoole_error_log(SW_LOG_NOTICE,
SW_ERROR_SESSION_CLOSED,
"send %d bytes failed, because session#%ld is closed",
resp->info.len,
session_id);
return false;
} else if (conn->overflow &&
(resp->info.type == SW_SERVER_EVENT_SEND_DATA || resp->info.type == SW_SERVER_EVENT_SEND_FILE)) {
if (server_->send_yield && process_is_supported_send_yield(server_, conn)) {
swoole_set_last_error(SW_ERROR_OUTPUT_SEND_YIELD);
} else {
swoole_error_log(SW_LOG_WARNING,
SW_ERROR_OUTPUT_BUFFER_OVERFLOW,
"send failed, session=%ld output buffer overflow",
session_id);
}
return false;
}
if (server_->last_stream_socket) {
uint32_t _len = resp->info.len;
uint32_t _header = htonl(_len + sizeof(resp->info));
if (swoole_event_write(server_->last_stream_socket, (char *) &_header, sizeof(_header)) < 0) {
return false;
}
if (swoole_event_write(server_->last_stream_socket, &resp->info, sizeof(resp->info)) < 0) {
return false;
}
if (_len > 0 && swoole_event_write(server_->last_stream_socket, resp->data, _len) < 0) {
return false;
}
return true;
}
SendData task;
memcpy(&task, resp, sizeof(SendData));
task.info.fd = session_id;
task.info.reactor_id = conn->reactor_id;
task.info.server_fd = SwooleG.process_id;
swoole_trace("worker_id=%d, type=%d", SwooleG.process_id, task.info.type);
return server_->message_bus.write(server_->get_reactor_pipe_socket(session_id, task.info.reactor_id), &task);
}
bool ProcessFactory::end(SessionId session_id, int flags) {
SendData _send{};
DataHead info{};
_send.info.fd = session_id;
_send.info.len = 0;
_send.info.type = SW_SERVER_EVENT_CLOSE;
Connection *conn = server_->get_connection_verify_no_ssl(session_id);
if (!conn) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_NOT_EXIST, "session#%ld is closed", session_id);
return false;
}
// Reset send buffer, Immediately close the connection.
if (flags & Server::CLOSE_RESET) {
conn->close_reset = 1;
}
// Server is initiative to close the connection
if (flags & Server::CLOSE_ACTIVELY) {
conn->close_actively = 1;
}
swoole_trace_log(SW_TRACE_CLOSE, "session_id=%ld, fd=%d", session_id, conn->fd);
Worker *worker;
DataHead ev = {};
/**
* Only close actively needs to determine whether it is in the process of connection binding.
* If the worker process is not currently bound to this connection,
* MUST forward to the correct worker process
*/
if (conn->close_actively) {
if (server_->last_stream_socket) {
goto _close;
}
bool hash = server_->is_hash_dispatch_mode();
int worker_id = hash ? server_->schedule_worker(conn->fd, nullptr) : conn->fd % server_->worker_num;
if (server_->is_worker() && (!hash || worker_id == (int) SwooleG.process_id)) {
goto _close;
}
worker = server_->get_worker(worker_id);
ev.type = SW_SERVER_EVENT_CLOSE;
ev.fd = session_id;
ev.reactor_id = conn->reactor_id;
return server_->send_to_worker_from_worker(worker, &ev, sizeof(ev), SW_PIPE_MASTER) > 0;
}
_close:
if (conn->closing) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_CLOSING, "session#%ld is closing", session_id);
return false;
} else if (!(conn->close_force || conn->close_reset) && conn->closed) {
swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_CLOSED, "session#%ld is closed", session_id);
return false;
}
if (server_->onClose != nullptr && !conn->closed) {
info.fd = session_id;
if (conn->close_actively) {
info.reactor_id = -1;
} else {
info.reactor_id = conn->reactor_id;
}
info.server_fd = conn->server_fd;
conn->closing = 1;
server_->onClose(server_, &info);
conn->closing = 0;
}
conn->closed = 1;
conn->close_errno = 0;
return finish(&_send);
}
} // namespace swoole
<|endoftext|> |
<commit_before>#include "LotsOfLinesApp.h"
#include <QFileDialog>
#include <QCheckBox>
#include <QMessageBox>
#include <QMetaType>
#include <QTableView>
#include "LoadDataDialog.h"
#include "PreferencesDialog.h"
#include "DataTableModel.h"
#include "LoadingWorker.h"
#include <LotsOfLines/RenderingSystem.hpp>
#include <LotsOfLines/IVisualizationMethod.hpp>
//Custom checkbox for selecting visualization methods.
class VisualizationTypeCheckbox : public QCheckBox
{
public:
VisualizationTypeCheckbox(const QString& text, QWidget* parent, LotsOfLines::E_VISUALIZATION_TYPE type)
:QCheckBox(text, parent),
m_visualizationType(type)
{}
LotsOfLines::E_VISUALIZATION_TYPE getVisualizationType() { return m_visualizationType; }
private:
LotsOfLines::E_VISUALIZATION_TYPE m_visualizationType;
};
LotsOfLinesApp::LotsOfLinesApp(const QString& openFile, QWidget *parent)
:QMainWindow(parent),
m_dataSet(nullptr)
{
ui.setupUi(this);
//Setup rendering window
auto rendererWidget = new VisualizationRendererWidget(this);
//Populate visualization type selection menu
LotsOfLines::VisualizationMethodList visualizationMethods;
rendererWidget->getRenderingSystem()->getVisualizationMethods(visualizationMethods);
for (auto method : visualizationMethods)
{
VisualizationTypeCheckbox* methodCheckbox = new VisualizationTypeCheckbox(QString::fromStdString(method->getTypeName()), ui.visualizationTypeArea, method->getType());
connect(methodCheckbox, SIGNAL(stateChanged(int)), this, SLOT(onVisualizationChecked(int)));
ui.visualizationTypeLayout->addWidget(methodCheckbox);
}
delete rendererWidget;
//Setup dock widgets
ui.menuView->addAction(ui.sidebarDockWidget->toggleViewAction());
ui.menuView->addAction(ui.dataTableDock->toggleViewAction());
// Register data types with meta system
qRegisterMetaType<LotsOfLines::LoadOptions>("LotsOfLines::LoadOptions");
qRegisterMetaType<std::shared_ptr<LotsOfLines::DataSet>>("std::shared_ptr<LotsOfLines::DataSet>");
//Connect signals and slots
connect(ui.actionLoad, SIGNAL(triggered()), this, SLOT(onLoadFile()));
connect(ui.actionPreferences, SIGNAL(triggered()), this, SLOT(onOpenPreferences()));
//Open initial file
}
void LotsOfLinesApp::loadFile(const QString& filename, const LotsOfLines::LoadOptions& options)
{
// Initialize progress dialog
QProgressDialog progressDialog(this);
progressDialog.setLabelText("Please wait while loading the data file. This may take awhile depending on the size.");
progressDialog.setMaximum(100);
// Initialize thread
QThread *loadingThread = new QThread();
// Initialize loader and progress messaging
ProgressMessageCallback messenger(progressDialog);
LotsOfLines::ProgressMessage *progress(&messenger);
LoadingWorker *loader = new LoadingWorker(progress);
loader->moveToThread(loadingThread);
// Connect signals and slots
connect(this, SIGNAL(requestDatasetUpdate(const QString&, const LotsOfLines::LoadOptions&)),
loader, SLOT(updateDataset(const QString&, const LotsOfLines::LoadOptions&)));
connect(loader, SIGNAL(datasetUpdated(std::shared_ptr<LotsOfLines::DataSet>)),
this, SLOT(addNewDataset(std::shared_ptr<LotsOfLines::DataSet>)));
connect(loader, SIGNAL(datasetUpdated(std::shared_ptr<LotsOfLines::DataSet>)), loadingThread, SLOT(quit()));
connect(loadingThread, SIGNAL(finished()), &progressDialog, SLOT(reset()));
connect(&progressDialog, SIGNAL(canceled()), loadingThread, SLOT(terminate()));
// Start thread and emit request
loadingThread->start();
emit requestDatasetUpdate(filename, options);
// Display dialog
progressDialog.exec();
// If load canceled, make sure to set nullptr dataset
if (progressDialog.wasCanceled())
{
addNewDataset(nullptr);
}
}
void LotsOfLinesApp::reloadDataTable()
{
if (m_dataSet) {
//Delete all tabs
for (unsigned int i = 0; i < ui.dataClassTabs->count(); ++i)
{
QWidget* tab = ui.dataClassTabs->widget(i);
delete tab;
}
ui.dataClassTabs->clear();
//Generate new tabs for each data class
for (auto dataClass : m_dataSet->getClasses())
{
QTableView* dataTable = new QTableView(ui.dataClassTabs);
dataTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
dataTable->setModel(new DataTableModel(m_dataSet, dataClass));
dataTable->setSelectionMode(QAbstractItemView::NoSelection);
ui.dataClassTabs->addTab(dataTable, QString::fromStdString(dataClass));
}
}
}
void LotsOfLinesApp::addNewDataset(std::shared_ptr<LotsOfLines::DataSet> dataSet)
{
m_dataSet = dataSet;
if (m_dataSet == nullptr)
{
QMessageBox::warning(this, "Failed to load", "There was an error loading the data file.");
}
//Pass data along to rendering system
for (auto rendererWidget : m_rendererWidgets)
{
auto renderingSystem = rendererWidget.second->getRenderingSystem();
renderingSystem->setDataSet(m_dataSet);
renderingSystem->redraw();
}
// Freezes with lots of classes
reloadDataTable();
}
void LotsOfLinesApp::onLoadFile()
{
//Get file path of data to load
QString file = QFileDialog::getOpenFileName(this, "Select data file");
if (file.isNull())
{
return;
}
//Show data loading options
LoadDataDialog dlg(this, file);
if (dlg.exec() == QDialog::Accepted)
{
LotsOfLines::LoadOptions options = dlg.getLoadOptions();
loadFile(file, options);
}
}
void LotsOfLinesApp::onOpenPreferences()
{
PreferencesDialog dlg(this);
dlg.exec();
}
void LotsOfLinesApp::onVisualizationChecked(int state)
{
VisualizationTypeCheckbox* checkbox = (VisualizationTypeCheckbox*)sender();
LotsOfLines::E_VISUALIZATION_TYPE visualizationType = checkbox->getVisualizationType();
if (state)
{
//Init callback will be called by the rendering widget after OpenGL loads
auto initCallback = [this, visualizationType](LotsOfLines::RenderingSystem* renderingSystem)
{
//Set visualization type and dataset now that OpenGL is initialized
renderingSystem->setDataSet(m_dataSet);
renderingSystem->setVisualizationType(visualizationType);
renderingSystem->redraw();
//Add options editor widget for visualization method
OptionEditorWidget* editorWidget = new OptionEditorWidget(
QString::fromStdString(renderingSystem->getCurrentVisualizationMethod()->getTypeName()),
renderingSystem->getVisualizationOptions(),
ui.optionsScrollArea
);
m_optionEditorWidgets[visualizationType] = editorWidget;
ui.optionsScrollLayout->addWidget(editorWidget);
//Connect option editing signal so that the visualization can be redrawn when options are changed
connect(editorWidget, SIGNAL(optionChanged(const std::string&)), this, SLOT(onVisualizationOptionsChanged(const std::string&)));
};
//Create widget for screen section and use init callback to set parameters
VisualizationRendererWidget* rendererWidget = new VisualizationRendererWidget(this, initCallback);
m_rendererWidgets[checkbox->getVisualizationType()] = rendererWidget;
reorderSplitScreens();
}
else
{
//Remove visualization type from splitscreen display
m_rendererWidgets.erase(visualizationType);
reorderSplitScreens();
//Remove editor widget
auto optionEditorWidget = m_optionEditorWidgets.find(visualizationType);
if (optionEditorWidget != m_optionEditorWidgets.end())
{
ui.optionsScrollLayout->removeWidget(optionEditorWidget->second);
delete optionEditorWidget->second;
m_optionEditorWidgets.erase(optionEditorWidget);
}
}
}
void LotsOfLinesApp::onVisualizationOptionsChanged(const std::string& name)
{
for (auto rendererWidget : m_rendererWidgets)
{
auto renderingSystem = rendererWidget.second->getRenderingSystem();
renderingSystem->redraw();
}
}
void LotsOfLinesApp::reorderSplitScreens()
{
//Clear layout
while (ui.centralLayout->count() > 0)
{
QLayoutItem* rendererLayoutItem = ui.centralLayout->itemAt(0);
VisualizationRendererWidget* renderWidget = (VisualizationRendererWidget*)rendererLayoutItem->widget();
LotsOfLines::E_VISUALIZATION_TYPE visualizationType = renderWidget->getRenderingSystem()->getCurrentVisualizationMethod()->getType();
ui.centralLayout->removeItem(rendererLayoutItem);
//If the visualization method has been disabled, then delete the rendering widget.
if (m_rendererWidgets.find(visualizationType) == m_rendererWidgets.end())
{
delete renderWidget;
}
}
//Assign based on index
unsigned int idx = 0;
for (auto widget : m_rendererWidgets)
{
unsigned int row = idx / 2;
unsigned int col = idx % 2;
ui.centralLayout->addWidget(widget.second, row, col);
idx++;
}
}<commit_msg>Limit classes in data table<commit_after>#include "LotsOfLinesApp.h"
#include <QFileDialog>
#include <QCheckBox>
#include <QMessageBox>
#include <QMetaType>
#include <QTableView>
#include "LoadDataDialog.h"
#include "PreferencesDialog.h"
#include "DataTableModel.h"
#include "LoadingWorker.h"
#include <LotsOfLines/RenderingSystem.hpp>
#include <LotsOfLines/IVisualizationMethod.hpp>
//Custom checkbox for selecting visualization methods.
class VisualizationTypeCheckbox : public QCheckBox
{
public:
VisualizationTypeCheckbox(const QString& text, QWidget* parent, LotsOfLines::E_VISUALIZATION_TYPE type)
:QCheckBox(text, parent),
m_visualizationType(type)
{}
LotsOfLines::E_VISUALIZATION_TYPE getVisualizationType() { return m_visualizationType; }
private:
LotsOfLines::E_VISUALIZATION_TYPE m_visualizationType;
};
LotsOfLinesApp::LotsOfLinesApp(const QString& openFile, QWidget *parent)
:QMainWindow(parent),
m_dataSet(nullptr)
{
ui.setupUi(this);
//Setup rendering window
auto rendererWidget = new VisualizationRendererWidget(this);
//Populate visualization type selection menu
LotsOfLines::VisualizationMethodList visualizationMethods;
rendererWidget->getRenderingSystem()->getVisualizationMethods(visualizationMethods);
for (auto method : visualizationMethods)
{
VisualizationTypeCheckbox* methodCheckbox = new VisualizationTypeCheckbox(QString::fromStdString(method->getTypeName()), ui.visualizationTypeArea, method->getType());
connect(methodCheckbox, SIGNAL(stateChanged(int)), this, SLOT(onVisualizationChecked(int)));
ui.visualizationTypeLayout->addWidget(methodCheckbox);
}
delete rendererWidget;
//Setup dock widgets
ui.menuView->addAction(ui.sidebarDockWidget->toggleViewAction());
ui.menuView->addAction(ui.dataTableDock->toggleViewAction());
// Register data types with meta system
qRegisterMetaType<LotsOfLines::LoadOptions>("LotsOfLines::LoadOptions");
qRegisterMetaType<std::shared_ptr<LotsOfLines::DataSet>>("std::shared_ptr<LotsOfLines::DataSet>");
//Connect signals and slots
connect(ui.actionLoad, SIGNAL(triggered()), this, SLOT(onLoadFile()));
connect(ui.actionPreferences, SIGNAL(triggered()), this, SLOT(onOpenPreferences()));
//Open initial file
}
void LotsOfLinesApp::loadFile(const QString& filename, const LotsOfLines::LoadOptions& options)
{
// Initialize progress dialog
QProgressDialog progressDialog(this);
progressDialog.setLabelText("Please wait while loading the data file. This may take awhile depending on the size.");
progressDialog.setMaximum(100);
// Initialize thread
QThread *loadingThread = new QThread();
// Initialize loader and progress messaging
ProgressMessageCallback messenger(progressDialog);
LotsOfLines::ProgressMessage *progress(&messenger);
LoadingWorker *loader = new LoadingWorker(progress);
loader->moveToThread(loadingThread);
// Connect signals and slots
connect(this, SIGNAL(requestDatasetUpdate(const QString&, const LotsOfLines::LoadOptions&)),
loader, SLOT(updateDataset(const QString&, const LotsOfLines::LoadOptions&)));
connect(loader, SIGNAL(datasetUpdated(std::shared_ptr<LotsOfLines::DataSet>)),
this, SLOT(addNewDataset(std::shared_ptr<LotsOfLines::DataSet>)));
connect(loader, SIGNAL(datasetUpdated(std::shared_ptr<LotsOfLines::DataSet>)), loadingThread, SLOT(quit()));
connect(loadingThread, SIGNAL(finished()), &progressDialog, SLOT(reset()));
connect(&progressDialog, SIGNAL(canceled()), loadingThread, SLOT(terminate()));
// Start thread and emit request
loadingThread->start();
emit requestDatasetUpdate(filename, options);
// Display dialog
progressDialog.exec();
// If load canceled, make sure to set nullptr dataset
if (progressDialog.wasCanceled())
{
addNewDataset(nullptr);
}
}
void LotsOfLinesApp::reloadDataTable()
{
if (m_dataSet) {
//Delete all tabs
for (unsigned int i = 0; i < ui.dataClassTabs->count(); ++i)
{
QWidget* tab = ui.dataClassTabs->widget(i);
delete tab;
}
ui.dataClassTabs->clear();
//Generate new tabs for each data class
std::set<std::string> dataClasses = m_dataSet->getClasses();
int i = 0, MAX_COLUMNS = 50;
for (std::set<std::string>::iterator iter = dataClasses.begin(); iter != dataClasses.end() && i < MAX_COLUMNS; ++iter, ++i)
{
QTableView* dataTable = new QTableView(ui.dataClassTabs);
dataTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
dataTable->setModel(new DataTableModel(m_dataSet, *iter));
dataTable->setSelectionMode(QAbstractItemView::NoSelection);
ui.dataClassTabs->addTab(dataTable, QString::fromStdString(*iter));
}
}
}
void LotsOfLinesApp::addNewDataset(std::shared_ptr<LotsOfLines::DataSet> dataSet)
{
m_dataSet = dataSet;
if (m_dataSet == nullptr)
{
QMessageBox::warning(this, "Failed to load", "There was an error loading the data file.");
}
//Pass data along to rendering system
for (auto rendererWidget : m_rendererWidgets)
{
auto renderingSystem = rendererWidget.second->getRenderingSystem();
renderingSystem->setDataSet(m_dataSet);
renderingSystem->redraw();
}
// Freezes with lots of classes
reloadDataTable();
}
void LotsOfLinesApp::onLoadFile()
{
//Get file path of data to load
QString file = QFileDialog::getOpenFileName(this, "Select data file");
if (file.isNull())
{
return;
}
//Show data loading options
LoadDataDialog dlg(this, file);
if (dlg.exec() == QDialog::Accepted)
{
LotsOfLines::LoadOptions options = dlg.getLoadOptions();
loadFile(file, options);
}
}
void LotsOfLinesApp::onOpenPreferences()
{
PreferencesDialog dlg(this);
dlg.exec();
}
void LotsOfLinesApp::onVisualizationChecked(int state)
{
VisualizationTypeCheckbox* checkbox = (VisualizationTypeCheckbox*)sender();
LotsOfLines::E_VISUALIZATION_TYPE visualizationType = checkbox->getVisualizationType();
if (state)
{
//Init callback will be called by the rendering widget after OpenGL loads
auto initCallback = [this, visualizationType](LotsOfLines::RenderingSystem* renderingSystem)
{
//Set visualization type and dataset now that OpenGL is initialized
renderingSystem->setDataSet(m_dataSet);
renderingSystem->setVisualizationType(visualizationType);
renderingSystem->redraw();
//Add options editor widget for visualization method
OptionEditorWidget* editorWidget = new OptionEditorWidget(
QString::fromStdString(renderingSystem->getCurrentVisualizationMethod()->getTypeName()),
renderingSystem->getVisualizationOptions(),
ui.optionsScrollArea
);
m_optionEditorWidgets[visualizationType] = editorWidget;
ui.optionsScrollLayout->addWidget(editorWidget);
//Connect option editing signal so that the visualization can be redrawn when options are changed
connect(editorWidget, SIGNAL(optionChanged(const std::string&)), this, SLOT(onVisualizationOptionsChanged(const std::string&)));
};
//Create widget for screen section and use init callback to set parameters
VisualizationRendererWidget* rendererWidget = new VisualizationRendererWidget(this, initCallback);
m_rendererWidgets[checkbox->getVisualizationType()] = rendererWidget;
reorderSplitScreens();
}
else
{
//Remove visualization type from splitscreen display
m_rendererWidgets.erase(visualizationType);
reorderSplitScreens();
//Remove editor widget
auto optionEditorWidget = m_optionEditorWidgets.find(visualizationType);
if (optionEditorWidget != m_optionEditorWidgets.end())
{
ui.optionsScrollLayout->removeWidget(optionEditorWidget->second);
delete optionEditorWidget->second;
m_optionEditorWidgets.erase(optionEditorWidget);
}
}
}
void LotsOfLinesApp::onVisualizationOptionsChanged(const std::string& name)
{
for (auto rendererWidget : m_rendererWidgets)
{
auto renderingSystem = rendererWidget.second->getRenderingSystem();
renderingSystem->redraw();
}
}
void LotsOfLinesApp::reorderSplitScreens()
{
//Clear layout
while (ui.centralLayout->count() > 0)
{
QLayoutItem* rendererLayoutItem = ui.centralLayout->itemAt(0);
VisualizationRendererWidget* renderWidget = (VisualizationRendererWidget*)rendererLayoutItem->widget();
LotsOfLines::E_VISUALIZATION_TYPE visualizationType = renderWidget->getRenderingSystem()->getCurrentVisualizationMethod()->getType();
ui.centralLayout->removeItem(rendererLayoutItem);
//If the visualization method has been disabled, then delete the rendering widget.
if (m_rendererWidgets.find(visualizationType) == m_rendererWidgets.end())
{
delete renderWidget;
}
}
//Assign based on index
unsigned int idx = 0;
for (auto widget : m_rendererWidgets)
{
unsigned int row = idx / 2;
unsigned int col = idx % 2;
ui.centralLayout->addWidget(widget.second, row, col);
idx++;
}
}<|endoftext|> |
<commit_before>#include "serverConnection.h"
#include <vector>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <libwatcher/message.h>
#include <libwatcher/messageStatus.h>
#include "messageFactory.h"
#include "dataMarshaller.h"
#include "watcherd.h"
#include "writeDBMessageHandler.h"
#include "watcherdConfig.h"
using namespace std;
using namespace boost::asio;
namespace {
using namespace watcher::event;
/* Grr, because there is no std::copy_if have to use the negation with
* remove_copy_if() */
bool not_feeder_message(const MessagePtr& m)
{
return !isFeederEvent(m->type);
}
}
namespace watcher {
using namespace event;
INIT_LOGGER(ServerConnection, "Connection.ServerConnection");
ServerConnection::ServerConnection(Watcherd& w, boost::asio::io_service& io_service) :
Connection(io_service),
watcher(w),
strand_(io_service),
write_strand_(io_service)
{
TRACE_ENTER();
TRACE_EXIT();
}
ServerConnection::~ServerConnection()
{
TRACE_ENTER();
//shared_from_this() not allowed in destructor
//watcher.unsubscribe(shared_from_this());
TRACE_EXIT();
}
/** Initialization point for start of new ServerConnection thread. */
void ServerConnection::run()
{
/*
* Pull endpoint info out of the socket and make it available via the
* Connection::getPeerAddr() member function.
*/
boost::asio::ip::tcp::endpoint ep = getSocket().remote_endpoint();
endpoint_addr_ = ep.address().to_string();
endpoint_port_ = ep.port();
start();
}
void ServerConnection::start()
{
TRACE_ENTER();
boost::asio::async_read(
theSocket,
boost::asio::buffer(incomingBuffer, DataMarshaller::header_length),
strand_.wrap(
boost::bind(
&ServerConnection::handle_read_header,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
TRACE_EXIT();
}
void ServerConnection::handle_read_header(const boost::system::error_code& e, size_t bytes_transferred)
{
TRACE_ENTER();
if (!e)
{
LOG_DEBUG("Read " << bytes_transferred << " bytes.");
size_t payloadSize;
unsigned short numOfMessages;
if (!DataMarshaller::unmarshalHeader(incomingBuffer.begin(), bytes_transferred, payloadSize, numOfMessages))
{
LOG_ERROR("Error parsing incoming message header.");
if (conn_type == gui)
watcher.unsubscribe(shared_from_this());
}
else
{
LOG_DEBUG("Reading packet payload of " << payloadSize << " bytes.");
boost::asio::async_read(
theSocket,
boost::asio::buffer(
incomingBuffer,
payloadSize), // Should incoming buffer be new'd()?
strand_.wrap(
boost::bind(
&ServerConnection::handle_read_payload,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
numOfMessages)));
}
}
else
{
if (e==boost::asio::error::eof)
{
LOG_DEBUG("Received empty message from clienti or client closed connection.");
LOG_INFO("Connection to client closed.");
}
else
{
LOG_ERROR("Error reading socket: " << e.message());
}
// unsubscribe to event stream, otherwise it will hold a
// shared_ptr open
if (conn_type == gui)
watcher.unsubscribe(shared_from_this());
}
TRACE_EXIT();
}
void ServerConnection::handle_read_payload(const boost::system::error_code& e, size_t bytes_transferred, unsigned short numOfMessages)
{
TRACE_ENTER();
if (!e)
{
vector<MessagePtr> arrivedMessages;
if (DataMarshaller::unmarshalPayload(arrivedMessages, numOfMessages, incomingBuffer.begin(), bytes_transferred))
{
LOG_INFO("Recvd " << arrivedMessages.size() << " message" <<
(arrivedMessages.size()>1?"s":"") << " from " <<
getPeerAddr());
/*
* If this connection type is unknown or gui, then traverse the
* list of arrived messages. For GUI clients, look for the
* STOP_MESSAGE to unsubscribe from the event stream.
*
* For unknown clients, infer the type from the message
* received:
* START_MESSAGE => gui
* isFeederMessage => feeder
*/
if (conn_type == unknown || conn_type == gui) {
BOOST_FOREACH(MessagePtr i, arrivedMessages) {
if (conn_type == gui) {
if (i->type == STOP_MESSAGE_TYPE)
watcher.unsubscribe(shared_from_this());
} else if (conn_type == unknown) {
if (i->type == START_MESSAGE_TYPE) {
/* Client is requesting the live stream of events. */
watcher.subscribe(shared_from_this());
conn_type = gui;
} else if (isFeederEvent(i->type)) {
conn_type = feeder;
/*
* This connection is a watcher test daemon. Add a message handler to write
* its event stream to the database.
*/
std::string path;
if (watcher.config().lookupValue(dbPath, path))
addMessageHandler(MessageHandlerPtr(new WriteDBMessageHandler(path)));
else
LOG_ERROR("unable to lookup \"" << dbPath << " in server configuration");
}
}
}
}
/* Flag indicating whether to continue reading from this
* connection. */
bool fail = false;
BOOST_FOREACH(MessageHandlerPtr mh, messageHandlers) {
if (mh->handleMessagesArrive(shared_from_this(), arrivedMessages)) {
fail = true;
LOG_DEBUG("Message handler told us to close this connection.");
}
}
if (!fail) {
// initiate request to read next message
LOG_DEBUG("Waiting for next message.");
start();
}
if (conn_type == feeder) {
/* relay feeder message to any client requesting the live stream.
* Warning: currently there is no check to make sure that a client doesn't
* receive a message it just sent. This should be OK since we are just
* relaying feeder messages only, and the GUIs should not be sending
* them. */
vector<MessagePtr> feeder;
remove_copy_if(arrivedMessages.begin(), arrivedMessages.end(), back_inserter(feeder), not_feeder_message);
if (! feeder.empty()) {
LOG_DEBUG("Sending " << feeder.size() << " feeder messages to clients.");
watcher.sendMessage(feeder);
}
}
}
}
else
{
LOG_WARN("Did not understand incoming message.");
// unsubscribe to event stream, otherwise it will hold a
// shared_ptr open
if (conn_type == gui)
watcher.unsubscribe(shared_from_this());
}
// If an error occurs then no new asynchronous operations are started. This
// means that all shared_ptr references to the ServerConnection object will
// disappear and the object will be destroyed automatically after this
// handler returns. The ServerConnection class's destructor closes the socket.
TRACE_EXIT();
}
void ServerConnection::handle_write(const boost::system::error_code& e, MessagePtr message)
{
TRACE_ENTER();
if (!e)
{
LOG_DEBUG("Successfully sent message to client: " << message);
BOOST_FOREACH(MessageHandlerPtr mh, messageHandlers)
{
#if 0
/* melkins
* The reads and writes to the socket are asynchronous, so
* we should never be waiting for something to be read as
* a result of a write.
*/
if(waitForResponse) // someone already said they wanted a response, so ignore ret val for others
mh->handleMessageSent(message);
else
waitForResponse=mh->handleMessageSent(message);
#endif
mh->handleMessageSent(message);
}
// melkins
// start() calls async_read(), which is not what we want to do here
/*
if(waitForResponse)
start();
*/
}
else
{
LOG_WARN("Error while sending response to client: " << e);
if (conn_type == gui)
watcher.unsubscribe(shared_from_this());
}
// No new asynchronous operations are started. This means that all shared_ptr
// references to the connection object will disappear and the object will be
// destroyed automatically after this handler returns. The connection class's
// destructor closes the socket.
/* NOTE: The refcount will not go to zero so long as there is an
* async_read operation also oustanding. */
TRACE_EXIT();
}
/** Send a single message to this connected client. */
void ServerConnection::sendMessage(MessagePtr msg)
{
TRACE_ENTER();
DataMarshaller::NetworkMarshalBuffers outBuffers;
DataMarshaller::marshalPayload(msg, outBuffers);
/// FIXME melkins 2004-04-19
// is it safe to call async_write and async_read from different
// threads at the same time? asio::tcp::socket() is listed at not
// shared thread safe
async_write(theSocket,
outBuffers,
write_strand_.wrap( boost::bind( &ServerConnection::handle_write,
shared_from_this(),
placeholders::error,
msg)));
TRACE_EXIT();
}
/** Send a set of messages to this connected client. */
void ServerConnection::sendMessage(const std::vector<MessagePtr>& msgs)
{
TRACE_ENTER();
DataMarshaller::NetworkMarshalBuffers outBuffers;
DataMarshaller::marshalPayload(msgs, outBuffers);
/// FIXME melkins 2004-04-19
// is it safe to call async_write and async_read from different
// threads at the same time?
async_write(theSocket,
outBuffers,
write_strand_.wrap( boost::bind( &ServerConnection::handle_write,
shared_from_this(),
placeholders::error,
msgs.front())));
TRACE_EXIT();
}
}
<commit_msg>initialiaze conn_type in ctor<commit_after>#include "serverConnection.h"
#include <vector>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <libwatcher/message.h>
#include <libwatcher/messageStatus.h>
#include "messageFactory.h"
#include "dataMarshaller.h"
#include "watcherd.h"
#include "writeDBMessageHandler.h"
#include "watcherdConfig.h"
using namespace std;
using namespace boost::asio;
namespace {
using namespace watcher::event;
/* Grr, because there is no std::copy_if have to use the negation with
* remove_copy_if() */
bool not_feeder_message(const MessagePtr& m)
{
return !isFeederEvent(m->type);
}
}
namespace watcher {
using namespace event;
INIT_LOGGER(ServerConnection, "Connection.ServerConnection");
ServerConnection::ServerConnection(Watcherd& w, boost::asio::io_service& io_service) :
Connection(io_service),
watcher(w),
strand_(io_service),
write_strand_(io_service),
conn_type(unknown)
{
TRACE_ENTER();
TRACE_EXIT();
}
ServerConnection::~ServerConnection()
{
TRACE_ENTER();
//shared_from_this() not allowed in destructor
//watcher.unsubscribe(shared_from_this());
TRACE_EXIT();
}
/** Initialization point for start of new ServerConnection thread. */
void ServerConnection::run()
{
/*
* Pull endpoint info out of the socket and make it available via the
* Connection::getPeerAddr() member function.
*/
boost::asio::ip::tcp::endpoint ep = getSocket().remote_endpoint();
endpoint_addr_ = ep.address().to_string();
endpoint_port_ = ep.port();
start();
}
void ServerConnection::start()
{
TRACE_ENTER();
boost::asio::async_read(
theSocket,
boost::asio::buffer(incomingBuffer, DataMarshaller::header_length),
strand_.wrap(
boost::bind(
&ServerConnection::handle_read_header,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)));
TRACE_EXIT();
}
void ServerConnection::handle_read_header(const boost::system::error_code& e, size_t bytes_transferred)
{
TRACE_ENTER();
if (!e)
{
LOG_DEBUG("Read " << bytes_transferred << " bytes.");
size_t payloadSize;
unsigned short numOfMessages;
if (!DataMarshaller::unmarshalHeader(incomingBuffer.begin(), bytes_transferred, payloadSize, numOfMessages))
{
LOG_ERROR("Error parsing incoming message header.");
if (conn_type == gui)
watcher.unsubscribe(shared_from_this());
}
else
{
LOG_DEBUG("Reading packet payload of " << payloadSize << " bytes.");
boost::asio::async_read(
theSocket,
boost::asio::buffer(
incomingBuffer,
payloadSize), // Should incoming buffer be new'd()?
strand_.wrap(
boost::bind(
&ServerConnection::handle_read_payload,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred,
numOfMessages)));
}
}
else
{
if (e==boost::asio::error::eof)
{
LOG_DEBUG("Received empty message from clienti or client closed connection.");
LOG_INFO("Connection to client closed.");
}
else
{
LOG_ERROR("Error reading socket: " << e.message());
}
// unsubscribe to event stream, otherwise it will hold a
// shared_ptr open
if (conn_type == gui)
watcher.unsubscribe(shared_from_this());
}
TRACE_EXIT();
}
void ServerConnection::handle_read_payload(const boost::system::error_code& e, size_t bytes_transferred, unsigned short numOfMessages)
{
TRACE_ENTER();
if (!e)
{
vector<MessagePtr> arrivedMessages;
if (DataMarshaller::unmarshalPayload(arrivedMessages, numOfMessages, incomingBuffer.begin(), bytes_transferred))
{
LOG_INFO("Recvd " << arrivedMessages.size() << " message" <<
(arrivedMessages.size()>1?"s":"") << " from " <<
getPeerAddr());
/*
* If this connection type is unknown or gui, then traverse the
* list of arrived messages. For GUI clients, look for the
* STOP_MESSAGE to unsubscribe from the event stream.
*
* For unknown clients, infer the type from the message
* received:
* START_MESSAGE => gui
* isFeederMessage => feeder
*/
if (conn_type == unknown || conn_type == gui) {
BOOST_FOREACH(MessagePtr i, arrivedMessages) {
if (conn_type == gui) {
if (i->type == STOP_MESSAGE_TYPE)
watcher.unsubscribe(shared_from_this());
} else if (conn_type == unknown) {
if (i->type == START_MESSAGE_TYPE) {
/* Client is requesting the live stream of events. */
watcher.subscribe(shared_from_this());
conn_type = gui;
} else if (isFeederEvent(i->type)) {
conn_type = feeder;
/*
* This connection is a watcher test daemon. Add a message handler to write
* its event stream to the database.
*/
std::string path;
if (watcher.config().lookupValue(dbPath, path))
addMessageHandler(MessageHandlerPtr(new WriteDBMessageHandler(path)));
else
LOG_ERROR("unable to lookup \"" << dbPath << " in server configuration");
}
}
}
}
/* Flag indicating whether to continue reading from this
* connection. */
bool fail = false;
BOOST_FOREACH(MessageHandlerPtr mh, messageHandlers) {
if (mh->handleMessagesArrive(shared_from_this(), arrivedMessages)) {
fail = true;
LOG_DEBUG("Message handler told us to close this connection.");
}
}
if (!fail) {
// initiate request to read next message
LOG_DEBUG("Waiting for next message.");
start();
}
if (conn_type == feeder) {
/* relay feeder message to any client requesting the live stream.
* Warning: currently there is no check to make sure that a client doesn't
* receive a message it just sent. This should be OK since we are just
* relaying feeder messages only, and the GUIs should not be sending
* them. */
vector<MessagePtr> feeder;
remove_copy_if(arrivedMessages.begin(), arrivedMessages.end(), back_inserter(feeder), not_feeder_message);
if (! feeder.empty()) {
LOG_DEBUG("Sending " << feeder.size() << " feeder messages to clients.");
watcher.sendMessage(feeder);
}
}
}
}
else
{
LOG_WARN("Did not understand incoming message.");
// unsubscribe to event stream, otherwise it will hold a
// shared_ptr open
if (conn_type == gui)
watcher.unsubscribe(shared_from_this());
}
// If an error occurs then no new asynchronous operations are started. This
// means that all shared_ptr references to the ServerConnection object will
// disappear and the object will be destroyed automatically after this
// handler returns. The ServerConnection class's destructor closes the socket.
TRACE_EXIT();
}
void ServerConnection::handle_write(const boost::system::error_code& e, MessagePtr message)
{
TRACE_ENTER();
if (!e)
{
LOG_DEBUG("Successfully sent message to client: " << message);
BOOST_FOREACH(MessageHandlerPtr mh, messageHandlers)
{
#if 0
/* melkins
* The reads and writes to the socket are asynchronous, so
* we should never be waiting for something to be read as
* a result of a write.
*/
if(waitForResponse) // someone already said they wanted a response, so ignore ret val for others
mh->handleMessageSent(message);
else
waitForResponse=mh->handleMessageSent(message);
#endif
mh->handleMessageSent(message);
}
// melkins
// start() calls async_read(), which is not what we want to do here
/*
if(waitForResponse)
start();
*/
}
else
{
LOG_WARN("Error while sending response to client: " << e);
if (conn_type == gui)
watcher.unsubscribe(shared_from_this());
}
// No new asynchronous operations are started. This means that all shared_ptr
// references to the connection object will disappear and the object will be
// destroyed automatically after this handler returns. The connection class's
// destructor closes the socket.
/* NOTE: The refcount will not go to zero so long as there is an
* async_read operation also oustanding. */
TRACE_EXIT();
}
/** Send a single message to this connected client. */
void ServerConnection::sendMessage(MessagePtr msg)
{
TRACE_ENTER();
DataMarshaller::NetworkMarshalBuffers outBuffers;
DataMarshaller::marshalPayload(msg, outBuffers);
/// FIXME melkins 2004-04-19
// is it safe to call async_write and async_read from different
// threads at the same time? asio::tcp::socket() is listed at not
// shared thread safe
async_write(theSocket,
outBuffers,
write_strand_.wrap( boost::bind( &ServerConnection::handle_write,
shared_from_this(),
placeholders::error,
msg)));
TRACE_EXIT();
}
/** Send a set of messages to this connected client. */
void ServerConnection::sendMessage(const std::vector<MessagePtr>& msgs)
{
TRACE_ENTER();
DataMarshaller::NetworkMarshalBuffers outBuffers;
DataMarshaller::marshalPayload(msgs, outBuffers);
/// FIXME melkins 2004-04-19
// is it safe to call async_write and async_read from different
// threads at the same time?
async_write(theSocket,
outBuffers,
write_strand_.wrap( boost::bind( &ServerConnection::handle_write,
shared_from_this(),
placeholders::error,
msgs.front())));
TRACE_EXIT();
}
}
<|endoftext|> |
<commit_before>#include <QDebug>
#include <QTreeView>
#include <QTabBar>
#include <QSettings>
/// CTK includes
#include <ctkCheckableHeaderView.h>
// ctkDICOMCore includes
#include "ctkDICOMDatabase.h"
#include "ctkDICOMModel.h"
#include "ctkDICOMQuery.h"
#include "ctkDICOMRetrieve.h"
// ctkDICOMWidgets includes
#include "ctkDICOMQueryRetrieveWidget.h"
#include "ctkDICOMQueryResultsTabWidget.h"
#include "ui_ctkDICOMQueryRetrieveWidget.h"
#include <ctkLogger.h>
static ctkLogger logger("org.commontk.DICOM.Widgets.ctkDICOMQueryRetrieveWidget");
//----------------------------------------------------------------------------
class ctkDICOMQueryRetrieveWidgetPrivate: public Ui_ctkDICOMQueryRetrieveWidget
{
public:
ctkDICOMQueryRetrieveWidgetPrivate(){}
QMap<QString, ctkDICOMQuery*> queries;
ctkDICOMModel model;
};
//----------------------------------------------------------------------------
// ctkDICOMQueryRetrieveWidgetPrivate methods
//----------------------------------------------------------------------------
// ctkDICOMQueryRetrieveWidget methods
//----------------------------------------------------------------------------
ctkDICOMQueryRetrieveWidget::ctkDICOMQueryRetrieveWidget(QWidget* _parent):Superclass(_parent),
d_ptr(new ctkDICOMQueryRetrieveWidgetPrivate)
{
Q_D(ctkDICOMQueryRetrieveWidget);
d->setupUi(this);
connect(d->QueryButton, SIGNAL(clicked()), this, SLOT(processQuery()));
}
//----------------------------------------------------------------------------
ctkDICOMQueryRetrieveWidget::~ctkDICOMQueryRetrieveWidget()
{
}
//----------------------------------------------------------------------------
void ctkDICOMQueryRetrieveWidget::setRetrieveDirectory(const QString& directory)
{
QSettings settings;
settings.setValue("RetrieveDirectory", directory);
settings.sync();
}
//----------------------------------------------------------------------------
void ctkDICOMQueryRetrieveWidget::setRetrieveDatabaseFileName(const QString& fileName)
{
QSettings settings;
settings.setValue("RetrieveDatabaseFileName", fileName);
settings.sync();
}
//----------------------------------------------------------------------------
void ctkDICOMQueryRetrieveWidget::processQuery()
{
Q_D(ctkDICOMQueryRetrieveWidget);
ctkDICOMDatabase queryResultDatabase;
// create a database in memory to hold query results
try { queryResultDatabase.openDatabase( ":memory:" ); }
catch (std::exception e)
{
logger.error ( "Database error: " + queryResultDatabase.GetLastError() );
queryResultDatabase.closeDatabase();
return;
}
// for each of the selected server nodes, send the query
QStringList serverNodes = d->ServerNodeWidget->nodes();
foreach (QString server, serverNodes)
{
QMap<QString, QVariant> parameters = d->ServerNodeWidget->nodeParameters(server);
if ( parameters["CheckState"] == Qt::Checked )
{
// create a query for the current server
d->queries[server] = new ctkDICOMQuery;
d->queries[server]->setCallingAETitle(d->ServerNodeWidget->callingAETitle());
d->queries[server]->setCalledAETitle(parameters["AETitle"].toString());
d->queries[server]->setHost(parameters["Address"].toString());
d->queries[server]->setPort(parameters["Port"].toInt());
// populate the query with the current search options
d->queries[server]->setFilters( d->QueryWidget->parameters() );
try
{
// run the query against the selected server and put results in database
d->queries[server]->query ( queryResultDatabase );
}
catch (std::exception e)
{
logger.error ( "Query error: " + parameters["Name"].toString() );
}
}
}
// checkable headers - allow user to select the patient/studies to retrieve
d->results->setModel(&d->model);
d->model.setHeaderData(0, Qt::Horizontal, Qt::Unchecked, Qt::CheckStateRole);
QHeaderView* previousHeaderView = d->results->header();
ctkCheckableHeaderView* headerView = new ctkCheckableHeaderView(Qt::Horizontal, d->results);
headerView->setClickable(previousHeaderView->isClickable());
headerView->setMovable(previousHeaderView->isMovable());
headerView->setHighlightSections(previousHeaderView->highlightSections());
headerView->setPropagateToItems(true);
d->results->setHeader(headerView);
d->model.setDatabase(queryResultDatabase.database());
d->results->setModel(&d->model);
}
<commit_msg>Conditionally enable the retrieve button only if there are results<commit_after>#include <QDebug>
#include <QTreeView>
#include <QTabBar>
#include <QSettings>
/// CTK includes
#include <ctkCheckableHeaderView.h>
// ctkDICOMCore includes
#include "ctkDICOMDatabase.h"
#include "ctkDICOMModel.h"
#include "ctkDICOMQuery.h"
#include "ctkDICOMRetrieve.h"
// ctkDICOMWidgets includes
#include "ctkDICOMQueryRetrieveWidget.h"
#include "ctkDICOMQueryResultsTabWidget.h"
#include "ui_ctkDICOMQueryRetrieveWidget.h"
#include <ctkLogger.h>
static ctkLogger logger("org.commontk.DICOM.Widgets.ctkDICOMQueryRetrieveWidget");
//----------------------------------------------------------------------------
class ctkDICOMQueryRetrieveWidgetPrivate: public Ui_ctkDICOMQueryRetrieveWidget
{
public:
ctkDICOMQueryRetrieveWidgetPrivate(){}
QMap<QString, ctkDICOMQuery*> queries;
ctkDICOMModel model;
};
//----------------------------------------------------------------------------
// ctkDICOMQueryRetrieveWidgetPrivate methods
//----------------------------------------------------------------------------
// ctkDICOMQueryRetrieveWidget methods
//----------------------------------------------------------------------------
ctkDICOMQueryRetrieveWidget::ctkDICOMQueryRetrieveWidget(QWidget* _parent):Superclass(_parent),
d_ptr(new ctkDICOMQueryRetrieveWidgetPrivate)
{
Q_D(ctkDICOMQueryRetrieveWidget);
d->setupUi(this);
connect(d->QueryButton, SIGNAL(clicked()), this, SLOT(processQuery()));
}
//----------------------------------------------------------------------------
ctkDICOMQueryRetrieveWidget::~ctkDICOMQueryRetrieveWidget()
{
}
//----------------------------------------------------------------------------
void ctkDICOMQueryRetrieveWidget::setRetrieveDirectory(const QString& directory)
{
QSettings settings;
settings.setValue("RetrieveDirectory", directory);
settings.sync();
}
//----------------------------------------------------------------------------
void ctkDICOMQueryRetrieveWidget::setRetrieveDatabaseFileName(const QString& fileName)
{
QSettings settings;
settings.setValue("RetrieveDatabaseFileName", fileName);
settings.sync();
}
//----------------------------------------------------------------------------
void ctkDICOMQueryRetrieveWidget::processQuery()
{
Q_D(ctkDICOMQueryRetrieveWidget);
d->RetrieveButton->setEnabled(false);
ctkDICOMDatabase queryResultDatabase;
// create a database in memory to hold query results
try { queryResultDatabase.openDatabase( ":memory:" ); }
catch (std::exception e)
{
logger.error ( "Database error: " + queryResultDatabase.GetLastError() );
queryResultDatabase.closeDatabase();
return;
}
// for each of the selected server nodes, send the query
QStringList serverNodes = d->ServerNodeWidget->nodes();
foreach (QString server, serverNodes)
{
QMap<QString, QVariant> parameters = d->ServerNodeWidget->nodeParameters(server);
if ( parameters["CheckState"] == Qt::Checked )
{
// create a query for the current server
d->queries[server] = new ctkDICOMQuery;
d->queries[server]->setCallingAETitle(d->ServerNodeWidget->callingAETitle());
d->queries[server]->setCalledAETitle(parameters["AETitle"].toString());
d->queries[server]->setHost(parameters["Address"].toString());
d->queries[server]->setPort(parameters["Port"].toInt());
// populate the query with the current search options
d->queries[server]->setFilters( d->QueryWidget->parameters() );
try
{
// run the query against the selected server and put results in database
d->queries[server]->query ( queryResultDatabase );
}
catch (std::exception e)
{
logger.error ( "Query error: " + parameters["Name"].toString() );
}
}
}
// checkable headers - allow user to select the patient/studies to retrieve
d->results->setModel(&d->model);
d->model.setHeaderData(0, Qt::Horizontal, Qt::Unchecked, Qt::CheckStateRole);
QHeaderView* previousHeaderView = d->results->header();
ctkCheckableHeaderView* headerView = new ctkCheckableHeaderView(Qt::Horizontal, d->results);
headerView->setClickable(previousHeaderView->isClickable());
headerView->setMovable(previousHeaderView->isMovable());
headerView->setHighlightSections(previousHeaderView->highlightSections());
headerView->setPropagateToItems(true);
d->results->setHeader(headerView);
d->model.setDatabase(queryResultDatabase.database());
d->results->setModel(&d->model);
if ( d->model.rowCount() > 0 )
{
d->RetrieveButton->setEnabled(true);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Cloudius Systems
*/
#ifndef SSTRING_HH_
#define SSTRING_HH_
#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
template <typename char_type, typename size_type, size_type max_size>
class basic_sstring {
union contents {
struct external_type {
char* str;
size_type size;
int8_t pad;
} external;
struct internal_type {
char str[max_size];
int8_t size;
} internal;
static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
static_assert(max_size <= 127, "max_size too large");
} u;
bool is_internal() const noexcept {
return u.internal.size >= 0;
}
bool is_external() const noexcept {
return !is_internal();
}
const char* str() const {
return is_internal() ? u.internal.str : u.external.str;
}
char* str() {
return is_internal() ? u.internal.str : u.external.str;
}
struct initialized_later {};
public:
basic_sstring() noexcept {
u.internal.size = 0;
u.internal.str[0] = '\0';
}
basic_sstring(const basic_sstring& x) {
if (x.is_internal()) {
u.internal = x.u.internal;
} else {
u.internal.size = -1;
u.external.str = new char[x.u.external.size + 1];
std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
u.external.size = x.u.external.size;
}
}
basic_sstring(basic_sstring&& x) noexcept {
u = x.u;
x.u.internal.size = 0;
x.u.internal.str[0] = '\0';
}
basic_sstring(initialized_later, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
std::copy(x, x + size, u.internal.str);
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
std::copy(x, x + size, u.external.str);
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {}
basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
basic_sstring(const std::basic_string<char_type>& s)
: basic_sstring(s.data(), s.size()) {}
~basic_sstring() noexcept {
if (is_external()) {
delete[] u.external.str;
}
}
basic_sstring& operator=(const basic_sstring& x) {
basic_sstring tmp(x);
swap(tmp);
return *this;
}
basic_sstring& operator=(basic_sstring&& x) noexcept {
if (this != &x) {
swap(x);
x.reset();
}
return *this;
}
operator std::string() const {
return str();
}
size_t size() const noexcept {
return is_internal() ? u.internal.size : u.external.size;
}
bool empty() const noexcept {
return u.internal.size == 0;
}
void reset() noexcept {
if (is_external()) {
delete[] u.external.str;
}
u.internal.size = 0;
u.internal.str[0] = '\0';
}
void swap(basic_sstring& x) noexcept {
contents tmp;
tmp = x.u;
x.u = u;
u = tmp;
}
const char* c_str() const {
return str();
}
const char_type* begin() const { return str(); }
const char_type* end() const { return str() + size(); }
char_type* begin() { return str(); }
char_type* end() { return str() + size(); }
bool operator==(const basic_sstring& x) const {
return size() == x.size() && std::equal(begin(), end(), x.begin());
}
bool operator!=(const basic_sstring& x) const {
return !operator==(x);
}
basic_sstring operator+(const basic_sstring& x) const {
basic_sstring ret(initialized_later(), size() + x.size());
std::copy(begin(), end(), ret.begin());
std::copy(x.begin(), x.end(), ret.begin() + size());
return ret;
}
basic_sstring& operator+=(const basic_sstring& x) {
return *this = *this + x;
}
};
template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
basic_sstring<char_type, size_type, max_size>& y) noexcept
{
return x.swap(y);
}
template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
const basic_sstring<char_type, size_type, max_size>& s) {
return os.write(s.begin(), s.size());
}
namespace std {
template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
size_t ret = 0;
for (auto c : s) {
ret = (ret << 6) | (ret >> (sizeof(ret) * 8 - 6));
ret ^= c;
}
return ret;
}
};
}
using sstring = basic_sstring<char, uint32_t, 15>;
template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);
template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
char tmp[sizeof(value) * 3 + 3];
auto len = std::sprintf(tmp, fmt, value);
return sstring(tmp, len);
}
template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
return to_sstring_sprintf(value, "%d");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
return to_sstring_sprintf(value, "%u");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
return to_sstring_sprintf(value, "%ld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%llu");
}
#endif /* SSTRING_HH_ */
<commit_msg>core: add operator<< which can print any vector<commit_after>/*
* Copyright 2014 Cloudius Systems
*/
#ifndef SSTRING_HH_
#define SSTRING_HH_
#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
template <typename char_type, typename size_type, size_type max_size>
class basic_sstring {
union contents {
struct external_type {
char* str;
size_type size;
int8_t pad;
} external;
struct internal_type {
char str[max_size];
int8_t size;
} internal;
static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
static_assert(max_size <= 127, "max_size too large");
} u;
bool is_internal() const noexcept {
return u.internal.size >= 0;
}
bool is_external() const noexcept {
return !is_internal();
}
const char* str() const {
return is_internal() ? u.internal.str : u.external.str;
}
char* str() {
return is_internal() ? u.internal.str : u.external.str;
}
struct initialized_later {};
public:
basic_sstring() noexcept {
u.internal.size = 0;
u.internal.str[0] = '\0';
}
basic_sstring(const basic_sstring& x) {
if (x.is_internal()) {
u.internal = x.u.internal;
} else {
u.internal.size = -1;
u.external.str = new char[x.u.external.size + 1];
std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
u.external.size = x.u.external.size;
}
}
basic_sstring(basic_sstring&& x) noexcept {
u = x.u;
x.u.internal.size = 0;
x.u.internal.str[0] = '\0';
}
basic_sstring(initialized_later, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
std::copy(x, x + size, u.internal.str);
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
std::copy(x, x + size, u.external.str);
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {}
basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
basic_sstring(const std::basic_string<char_type>& s)
: basic_sstring(s.data(), s.size()) {}
~basic_sstring() noexcept {
if (is_external()) {
delete[] u.external.str;
}
}
basic_sstring& operator=(const basic_sstring& x) {
basic_sstring tmp(x);
swap(tmp);
return *this;
}
basic_sstring& operator=(basic_sstring&& x) noexcept {
if (this != &x) {
swap(x);
x.reset();
}
return *this;
}
operator std::string() const {
return str();
}
size_t size() const noexcept {
return is_internal() ? u.internal.size : u.external.size;
}
bool empty() const noexcept {
return u.internal.size == 0;
}
void reset() noexcept {
if (is_external()) {
delete[] u.external.str;
}
u.internal.size = 0;
u.internal.str[0] = '\0';
}
void swap(basic_sstring& x) noexcept {
contents tmp;
tmp = x.u;
x.u = u;
u = tmp;
}
const char* c_str() const {
return str();
}
const char_type* begin() const { return str(); }
const char_type* end() const { return str() + size(); }
char_type* begin() { return str(); }
char_type* end() { return str() + size(); }
bool operator==(const basic_sstring& x) const {
return size() == x.size() && std::equal(begin(), end(), x.begin());
}
bool operator!=(const basic_sstring& x) const {
return !operator==(x);
}
basic_sstring operator+(const basic_sstring& x) const {
basic_sstring ret(initialized_later(), size() + x.size());
std::copy(begin(), end(), ret.begin());
std::copy(x.begin(), x.end(), ret.begin() + size());
return ret;
}
basic_sstring& operator+=(const basic_sstring& x) {
return *this = *this + x;
}
};
template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
basic_sstring<char_type, size_type, max_size>& y) noexcept
{
return x.swap(y);
}
template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
const basic_sstring<char_type, size_type, max_size>& s) {
return os.write(s.begin(), s.size());
}
namespace std {
template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
size_t ret = 0;
for (auto c : s) {
ret = (ret << 6) | (ret >> (sizeof(ret) * 8 - 6));
ret ^= c;
}
return ret;
}
};
}
using sstring = basic_sstring<char, uint32_t, 15>;
template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);
template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
char tmp[sizeof(value) * 3 + 3];
auto len = std::sprintf(tmp, fmt, value);
return sstring(tmp, len);
}
template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
return to_sstring_sprintf(value, "%d");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
return to_sstring_sprintf(value, "%u");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
return to_sstring_sprintf(value, "%ld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%llu");
}
template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
bool first = true;
os << "{";
for (auto&& elem : v) {
if (!first) {
os << ", ";
} else {
first = false;
}
os << elem;
}
os << "}";
return os;
}
#endif /* SSTRING_HH_ */
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qv4compileddata_p.h"
#include "qv4jsir_p.h"
#include <private/qv4engine_p.h>
#include <private/qv4function_p.h>
#include <private/qv4objectproto_p.h>
#include <private/qv4lookup_p.h>
#include <private/qv4regexpobject_p.h>
#include <private/qv4unwindhelper_p.h>
#include <algorithm>
QT_BEGIN_NAMESPACE
namespace QV4 {
namespace CompiledData {
namespace {
bool functionSortHelper(QV4::Function *lhs, QV4::Function *rhs)
{
return reinterpret_cast<quintptr>(lhs->codePtr) < reinterpret_cast<quintptr>(rhs->codePtr);
}
}
CompilationUnit::~CompilationUnit()
{
unlink();
}
QV4::Function *CompilationUnit::linkToEngine(ExecutionEngine *engine)
{
this->engine = engine;
engine->compilationUnits.insert(this);
assert(!runtimeStrings);
assert(data);
runtimeStrings = (QV4::SafeString *)malloc(data->stringTableSize * sizeof(QV4::SafeString));
// memset the strings to 0 in case a GC run happens while we're within the loop below
memset(runtimeStrings, 0, data->stringTableSize * sizeof(QV4::SafeString));
for (int i = 0; i < data->stringTableSize; ++i)
runtimeStrings[i] = engine->newIdentifier(data->stringAt(i));
runtimeRegularExpressions = new QV4::SafeValue[data->regexpTableSize];
// memset the regexps to 0 in case a GC run happens while we're within the loop below
memset(runtimeRegularExpressions, 0, data->regexpTableSize * sizeof(QV4::SafeValue));
for (int i = 0; i < data->regexpTableSize; ++i) {
const CompiledData::RegExp *re = data->regexpAt(i);
int flags = 0;
if (re->flags & CompiledData::RegExp::RegExp_Global)
flags |= QQmlJS::V4IR::RegExp::RegExp_Global;
if (re->flags & CompiledData::RegExp::RegExp_IgnoreCase)
flags |= QQmlJS::V4IR::RegExp::RegExp_IgnoreCase;
if (re->flags & CompiledData::RegExp::RegExp_Multiline)
flags |= QQmlJS::V4IR::RegExp::RegExp_Multiline;
runtimeRegularExpressions[i] = engine->newRegExpObject(data->stringAt(re->stringIndex), flags);
}
if (data->lookupTableSize) {
runtimeLookups = new QV4::Lookup[data->lookupTableSize];
const CompiledData::Lookup *compiledLookups = data->lookupTable();
for (uint i = 0; i < data->lookupTableSize; ++i) {
QV4::Lookup *l = runtimeLookups + i;
if (compiledLookups[i].type_and_flags == CompiledData::Lookup::Type_Getter)
l->getter = QV4::Lookup::getterGeneric;
else if (compiledLookups[i].type_and_flags == CompiledData::Lookup::Type_Setter)
l->setter = QV4::Lookup::setterGeneric;
else if (compiledLookups[i].type_and_flags == CompiledData::Lookup::Type_GlobalGetter)
l->globalGetter = QV4::Lookup::globalGetterGeneric;
for (int i = 0; i < QV4::Lookup::Size; ++i)
l->classList[i] = 0;
l->level = -1;
l->index = UINT_MAX;
l->name = runtimeStrings[compiledLookups[i].nameIndex].asString();
}
}
if (data->jsClassTableSize) {
runtimeClasses = (QV4::InternalClass**)malloc(data->jsClassTableSize * sizeof(QV4::InternalClass*));
for (int i = 0; i < data->jsClassTableSize; ++i) {
int memberCount = 0;
const CompiledData::JSClassMember *member = data->jsClassAt(i, &memberCount);
QV4::InternalClass *klass = engine->objectClass;
for (int j = 0; j < memberCount; ++j, ++member)
klass = klass->addMember(runtimeStrings[member->nameOffset].asString(), member->isAccessor ? QV4::Attr_Accessor : QV4::Attr_Data);
runtimeClasses[i] = klass;
}
}
linkBackendToEngine(engine);
#if 0
runtimeFunctionsSortedByAddress.resize(runtimeFunctions.size());
memcpy(runtimeFunctionsSortedByAddress.data(), runtimeFunctions.data(), runtimeFunctions.size() * sizeof(QV4::Function*));
std::sort(runtimeFunctionsSortedByAddress.begin(), runtimeFunctionsSortedByAddress.end(), functionSortHelper);
#endif
return runtimeFunctions[data->indexOfRootFunction];
}
void CompilationUnit::unlink()
{
if (engine)
engine->compilationUnits.erase(engine->compilationUnits.find(this));
engine = 0;
if (ownsData)
free(data);
data = 0;
free(runtimeStrings);
runtimeStrings = 0;
delete [] runtimeLookups;
runtimeLookups = 0;
delete [] runtimeRegularExpressions;
runtimeRegularExpressions = 0;
free(runtimeClasses);
runtimeClasses = 0;
qDeleteAll(runtimeFunctions);
runtimeFunctions.clear();
}
void CompilationUnit::markObjects()
{
for (int i = 0; i < data->stringTableSize; ++i)
runtimeStrings[i].mark();
for (int i = 0; i < data->regexpTableSize; ++i)
runtimeRegularExpressions[i].mark();
for (int i = 0; i < runtimeFunctions.count(); ++i)
if (runtimeFunctions[i])
runtimeFunctions[i]->mark();
}
QString Binding::valueAsString(const Unit *unit) const
{
switch (type) {
case Type_Script:
case Type_String:
return unit->stringAt(stringIndex);
case Type_Boolean:
return value.b ? QStringLiteral("true") : QStringLiteral("false");
case Type_Number:
return QString::number(value.d);
case Type_Invalid:
return QString();
default:
break;
}
return QString();
}
}
}
QT_END_NAMESPACE
<commit_msg>Mark strings stored in the lookups<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qv4compileddata_p.h"
#include "qv4jsir_p.h"
#include <private/qv4engine_p.h>
#include <private/qv4function_p.h>
#include <private/qv4objectproto_p.h>
#include <private/qv4lookup_p.h>
#include <private/qv4regexpobject_p.h>
#include <private/qv4unwindhelper_p.h>
#include <algorithm>
QT_BEGIN_NAMESPACE
namespace QV4 {
namespace CompiledData {
namespace {
bool functionSortHelper(QV4::Function *lhs, QV4::Function *rhs)
{
return reinterpret_cast<quintptr>(lhs->codePtr) < reinterpret_cast<quintptr>(rhs->codePtr);
}
}
CompilationUnit::~CompilationUnit()
{
unlink();
}
QV4::Function *CompilationUnit::linkToEngine(ExecutionEngine *engine)
{
this->engine = engine;
engine->compilationUnits.insert(this);
assert(!runtimeStrings);
assert(data);
runtimeStrings = (QV4::SafeString *)malloc(data->stringTableSize * sizeof(QV4::SafeString));
// memset the strings to 0 in case a GC run happens while we're within the loop below
memset(runtimeStrings, 0, data->stringTableSize * sizeof(QV4::SafeString));
for (int i = 0; i < data->stringTableSize; ++i)
runtimeStrings[i] = engine->newIdentifier(data->stringAt(i));
runtimeRegularExpressions = new QV4::SafeValue[data->regexpTableSize];
// memset the regexps to 0 in case a GC run happens while we're within the loop below
memset(runtimeRegularExpressions, 0, data->regexpTableSize * sizeof(QV4::SafeValue));
for (int i = 0; i < data->regexpTableSize; ++i) {
const CompiledData::RegExp *re = data->regexpAt(i);
int flags = 0;
if (re->flags & CompiledData::RegExp::RegExp_Global)
flags |= QQmlJS::V4IR::RegExp::RegExp_Global;
if (re->flags & CompiledData::RegExp::RegExp_IgnoreCase)
flags |= QQmlJS::V4IR::RegExp::RegExp_IgnoreCase;
if (re->flags & CompiledData::RegExp::RegExp_Multiline)
flags |= QQmlJS::V4IR::RegExp::RegExp_Multiline;
runtimeRegularExpressions[i] = engine->newRegExpObject(data->stringAt(re->stringIndex), flags);
}
if (data->lookupTableSize) {
runtimeLookups = new QV4::Lookup[data->lookupTableSize];
const CompiledData::Lookup *compiledLookups = data->lookupTable();
for (uint i = 0; i < data->lookupTableSize; ++i) {
QV4::Lookup *l = runtimeLookups + i;
if (compiledLookups[i].type_and_flags == CompiledData::Lookup::Type_Getter)
l->getter = QV4::Lookup::getterGeneric;
else if (compiledLookups[i].type_and_flags == CompiledData::Lookup::Type_Setter)
l->setter = QV4::Lookup::setterGeneric;
else if (compiledLookups[i].type_and_flags == CompiledData::Lookup::Type_GlobalGetter)
l->globalGetter = QV4::Lookup::globalGetterGeneric;
for (int i = 0; i < QV4::Lookup::Size; ++i)
l->classList[i] = 0;
l->level = -1;
l->index = UINT_MAX;
l->name = runtimeStrings[compiledLookups[i].nameIndex].asString();
}
}
if (data->jsClassTableSize) {
runtimeClasses = (QV4::InternalClass**)malloc(data->jsClassTableSize * sizeof(QV4::InternalClass*));
for (int i = 0; i < data->jsClassTableSize; ++i) {
int memberCount = 0;
const CompiledData::JSClassMember *member = data->jsClassAt(i, &memberCount);
QV4::InternalClass *klass = engine->objectClass;
for (int j = 0; j < memberCount; ++j, ++member)
klass = klass->addMember(runtimeStrings[member->nameOffset].asString(), member->isAccessor ? QV4::Attr_Accessor : QV4::Attr_Data);
runtimeClasses[i] = klass;
}
}
linkBackendToEngine(engine);
#if 0
runtimeFunctionsSortedByAddress.resize(runtimeFunctions.size());
memcpy(runtimeFunctionsSortedByAddress.data(), runtimeFunctions.data(), runtimeFunctions.size() * sizeof(QV4::Function*));
std::sort(runtimeFunctionsSortedByAddress.begin(), runtimeFunctionsSortedByAddress.end(), functionSortHelper);
#endif
return runtimeFunctions[data->indexOfRootFunction];
}
void CompilationUnit::unlink()
{
if (engine)
engine->compilationUnits.erase(engine->compilationUnits.find(this));
engine = 0;
if (ownsData)
free(data);
data = 0;
free(runtimeStrings);
runtimeStrings = 0;
delete [] runtimeLookups;
runtimeLookups = 0;
delete [] runtimeRegularExpressions;
runtimeRegularExpressions = 0;
free(runtimeClasses);
runtimeClasses = 0;
qDeleteAll(runtimeFunctions);
runtimeFunctions.clear();
}
void CompilationUnit::markObjects()
{
for (int i = 0; i < data->stringTableSize; ++i)
runtimeStrings[i].mark();
for (int i = 0; i < data->regexpTableSize; ++i)
runtimeRegularExpressions[i].mark();
for (int i = 0; i < runtimeFunctions.count(); ++i)
if (runtimeFunctions[i])
runtimeFunctions[i]->mark();
for (int i = 0; i < data->lookupTableSize; ++i)
runtimeLookups[i].name->mark();
}
QString Binding::valueAsString(const Unit *unit) const
{
switch (type) {
case Type_Script:
case Type_String:
return unit->stringAt(stringIndex);
case Type_Boolean:
return value.b ? QStringLiteral("true") : QStringLiteral("false");
case Type_Number:
return QString::number(value.d);
case Type_Invalid:
return QString();
default:
break;
}
return QString();
}
}
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Cloudius Systems
*/
#ifndef SSTRING_HH_
#define SSTRING_HH_
#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
#include <experimental/string_view>
template <typename char_type, typename size_type, size_type max_size>
class basic_sstring {
union contents {
struct external_type {
char* str;
size_type size;
int8_t pad;
} external;
struct internal_type {
char str[max_size];
int8_t size;
} internal;
static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
static_assert(max_size <= 127, "max_size too large");
} u;
bool is_internal() const noexcept {
return u.internal.size >= 0;
}
bool is_external() const noexcept {
return !is_internal();
}
const char* str() const {
return is_internal() ? u.internal.str : u.external.str;
}
char* str() {
return is_internal() ? u.internal.str : u.external.str;
}
public:
struct initialized_later {};
basic_sstring() noexcept {
u.internal.size = 0;
u.internal.str[0] = '\0';
}
basic_sstring(const basic_sstring& x) {
if (x.is_internal()) {
u.internal = x.u.internal;
} else {
u.internal.size = -1;
u.external.str = new char[x.u.external.size + 1];
std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
u.external.size = x.u.external.size;
}
}
basic_sstring(basic_sstring&& x) noexcept {
u = x.u;
x.u.internal.size = 0;
x.u.internal.str[0] = '\0';
}
basic_sstring(initialized_later, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
std::copy(x, x + size, u.internal.str);
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
std::copy(x, x + size, u.external.str);
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {}
basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
basic_sstring(const std::basic_string<char_type>& s)
: basic_sstring(s.data(), s.size()) {}
~basic_sstring() noexcept {
if (is_external()) {
delete[] u.external.str;
}
}
basic_sstring& operator=(const basic_sstring& x) {
basic_sstring tmp(x);
swap(tmp);
return *this;
}
basic_sstring& operator=(basic_sstring&& x) noexcept {
if (this != &x) {
swap(x);
x.reset();
}
return *this;
}
operator std::string() const {
return str();
}
size_t size() const noexcept {
return is_internal() ? u.internal.size : u.external.size;
}
bool empty() const noexcept {
return u.internal.size == 0;
}
void reset() noexcept {
if (is_external()) {
delete[] u.external.str;
}
u.internal.size = 0;
u.internal.str[0] = '\0';
}
void swap(basic_sstring& x) noexcept {
contents tmp;
tmp = x.u;
x.u = u;
u = tmp;
}
const char* c_str() const {
return str();
}
const char_type* begin() const { return str(); }
const char_type* end() const { return str() + size(); }
char_type* begin() { return str(); }
char_type* end() { return str() + size(); }
bool operator==(const basic_sstring& x) const {
return size() == x.size() && std::equal(begin(), end(), x.begin());
}
bool operator!=(const basic_sstring& x) const {
return !operator==(x);
}
basic_sstring operator+(const basic_sstring& x) const {
basic_sstring ret(initialized_later(), size() + x.size());
std::copy(begin(), end(), ret.begin());
std::copy(x.begin(), x.end(), ret.begin() + size());
return ret;
}
basic_sstring& operator+=(const basic_sstring& x) {
return *this = *this + x;
}
operator std::experimental::string_view() const {
return std::experimental::string_view(str(), size());
}
};
template <size_t N>
static inline
size_t str_len(const char(&s)[N]) { return N - 1; }
template <size_t N>
static inline
const char* str_begin(const char(&s)[N]) { return s; }
template <size_t N>
static inline
const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); }
template <typename First, typename Second, typename... Tail>
static inline
const size_t str_len(const First& first, const Second& second, const Tail&... tail) {
return str_len(first) + str_len(second, tail...);
}
template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
basic_sstring<char_type, size_type, max_size>& y) noexcept
{
return x.swap(y);
}
template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
const basic_sstring<char_type, size_type, max_size>& s) {
return os.write(s.begin(), s.size());
}
namespace std {
template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
return std::hash<std::experimental::string_view>()(s);
}
};
}
using sstring = basic_sstring<char, uint32_t, 15>;
static inline
char* copy_str_to(char* dst) {
return dst;
}
template <typename Head, typename... Tail>
static inline
char* copy_str_to(char* dst, const Head& head, const Tail&... tail) {
return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...);
}
template <typename String = sstring, typename... Args>
static String make_sstring(Args&&... args)
{
String ret(sstring::initialized_later(), str_len(args...));
copy_str_to(ret.begin(), args...);
return ret;
}
template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);
template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
char tmp[sizeof(value) * 3 + 3];
auto len = std::sprintf(tmp, fmt, value);
return sstring(tmp, len);
}
template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
return to_sstring_sprintf(value, "%d");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
return to_sstring_sprintf(value, "%u");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
return to_sstring_sprintf(value, "%ld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%llu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(const char* value, void* = nullptr) {
return string_type(value);
}
template <typename string_type = sstring>
inline
string_type to_sstring(sstring value, void* = nullptr) {
return value;
}
template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
bool first = true;
os << "{";
for (auto&& elem : v) {
if (!first) {
os << ", ";
} else {
first = false;
}
os << elem;
}
os << "}";
return os;
}
#endif /* SSTRING_HH_ */
<commit_msg>sstring: overload to_sstring() for temporary_buffer<><commit_after>/*
* Copyright 2014 Cloudius Systems
*/
#ifndef SSTRING_HH_
#define SSTRING_HH_
#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
#include <experimental/string_view>
#include "core/temporary_buffer.hh"
template <typename char_type, typename size_type, size_type max_size>
class basic_sstring {
union contents {
struct external_type {
char* str;
size_type size;
int8_t pad;
} external;
struct internal_type {
char str[max_size];
int8_t size;
} internal;
static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
static_assert(max_size <= 127, "max_size too large");
} u;
bool is_internal() const noexcept {
return u.internal.size >= 0;
}
bool is_external() const noexcept {
return !is_internal();
}
const char* str() const {
return is_internal() ? u.internal.str : u.external.str;
}
char* str() {
return is_internal() ? u.internal.str : u.external.str;
}
public:
struct initialized_later {};
basic_sstring() noexcept {
u.internal.size = 0;
u.internal.str[0] = '\0';
}
basic_sstring(const basic_sstring& x) {
if (x.is_internal()) {
u.internal = x.u.internal;
} else {
u.internal.size = -1;
u.external.str = new char[x.u.external.size + 1];
std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
u.external.size = x.u.external.size;
}
}
basic_sstring(basic_sstring&& x) noexcept {
u = x.u;
x.u.internal.size = 0;
x.u.internal.str[0] = '\0';
}
basic_sstring(initialized_later, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
std::copy(x, x + size, u.internal.str);
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
std::copy(x, x + size, u.external.str);
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {}
basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
basic_sstring(const std::basic_string<char_type>& s)
: basic_sstring(s.data(), s.size()) {}
~basic_sstring() noexcept {
if (is_external()) {
delete[] u.external.str;
}
}
basic_sstring& operator=(const basic_sstring& x) {
basic_sstring tmp(x);
swap(tmp);
return *this;
}
basic_sstring& operator=(basic_sstring&& x) noexcept {
if (this != &x) {
swap(x);
x.reset();
}
return *this;
}
operator std::string() const {
return str();
}
size_t size() const noexcept {
return is_internal() ? u.internal.size : u.external.size;
}
bool empty() const noexcept {
return u.internal.size == 0;
}
void reset() noexcept {
if (is_external()) {
delete[] u.external.str;
}
u.internal.size = 0;
u.internal.str[0] = '\0';
}
void swap(basic_sstring& x) noexcept {
contents tmp;
tmp = x.u;
x.u = u;
u = tmp;
}
const char* c_str() const {
return str();
}
const char_type* begin() const { return str(); }
const char_type* end() const { return str() + size(); }
char_type* begin() { return str(); }
char_type* end() { return str() + size(); }
bool operator==(const basic_sstring& x) const {
return size() == x.size() && std::equal(begin(), end(), x.begin());
}
bool operator!=(const basic_sstring& x) const {
return !operator==(x);
}
basic_sstring operator+(const basic_sstring& x) const {
basic_sstring ret(initialized_later(), size() + x.size());
std::copy(begin(), end(), ret.begin());
std::copy(x.begin(), x.end(), ret.begin() + size());
return ret;
}
basic_sstring& operator+=(const basic_sstring& x) {
return *this = *this + x;
}
operator std::experimental::string_view() const {
return std::experimental::string_view(str(), size());
}
};
template <size_t N>
static inline
size_t str_len(const char(&s)[N]) { return N - 1; }
template <size_t N>
static inline
const char* str_begin(const char(&s)[N]) { return s; }
template <size_t N>
static inline
const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); }
template <typename First, typename Second, typename... Tail>
static inline
const size_t str_len(const First& first, const Second& second, const Tail&... tail) {
return str_len(first) + str_len(second, tail...);
}
template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
basic_sstring<char_type, size_type, max_size>& y) noexcept
{
return x.swap(y);
}
template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
const basic_sstring<char_type, size_type, max_size>& s) {
return os.write(s.begin(), s.size());
}
namespace std {
template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
return std::hash<std::experimental::string_view>()(s);
}
};
}
using sstring = basic_sstring<char, uint32_t, 15>;
static inline
char* copy_str_to(char* dst) {
return dst;
}
template <typename Head, typename... Tail>
static inline
char* copy_str_to(char* dst, const Head& head, const Tail&... tail) {
return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...);
}
template <typename String = sstring, typename... Args>
static String make_sstring(Args&&... args)
{
String ret(sstring::initialized_later(), str_len(args...));
copy_str_to(ret.begin(), args...);
return ret;
}
template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);
template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
char tmp[sizeof(value) * 3 + 3];
auto len = std::sprintf(tmp, fmt, value);
return sstring(tmp, len);
}
template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
return to_sstring_sprintf(value, "%d");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
return to_sstring_sprintf(value, "%u");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
return to_sstring_sprintf(value, "%ld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%llu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(const char* value, void* = nullptr) {
return string_type(value);
}
template <typename string_type = sstring>
inline
string_type to_sstring(sstring value, void* = nullptr) {
return value;
}
template <typename string_type = sstring>
static string_type to_sstring(const temporary_buffer<char>& buf) {
return string_type(buf.get(), buf.size());
}
template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
bool first = true;
os << "{";
for (auto&& elem : v) {
if (!first) {
os << ", ";
} else {
first = false;
}
os << elem;
}
os << "}";
return os;
}
#endif /* SSTRING_HH_ */
<|endoftext|> |
<commit_before>#include "acceptandpayofferlistpage.h"
#include "ui_acceptandpayofferlistpage.h"
#include "init.h"
#include "util.h"
#include "offeracceptdialog.h"
#include "offeracceptdialogbtc.h"
#include "offer.h"
#include "syscoingui.h"
#include "guiutil.h"
#include "platformstyle.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
#include <QString>
#include <QByteArray>
#include <QPixmap>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QRegExp>
#include <QStringList>
#include <QDesktopServices>
#include "rpcserver.h"
#include "alias.h"
#include "walletmodel.h"
using namespace std;
extern const CRPCTable tableRPC;
AcceptandPayOfferListPage::AcceptandPayOfferListPage(const PlatformStyle *platformStyle, QWidget *parent) :
QDialog(parent), platformStyle(platformStyle),
ui(new Ui::AcceptandPayOfferListPage)
{
sAddress = "";
bOnlyAcceptBTC = false;
ui->setupUi(this);
QString theme = GUIUtil::getThemeName();
if (!platformStyle->getImagesOnButtons())
{
ui->lookupButton->setIcon(QIcon());
ui->acceptButton->setIcon(QIcon());
ui->imageButton->setIcon(QIcon());
}
else
{
ui->lookupButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/search"));
ui->acceptButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/cart"));
}
ui->imageButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/imageplaceholder"));
this->offerPaid = false;
this->URIHandled = false;
ui->labelExplanation->setText(tr("Purchase an offer, Syscoin will be used from your balance to complete the transaction"));
connect(ui->acceptButton, SIGNAL(clicked()), this, SLOT(acceptOffer()));
connect(ui->lookupButton, SIGNAL(clicked()), this, SLOT(lookup()));
connect(ui->offeridEdit, SIGNAL(textChanged(const QString &)), this, SLOT(resetState()));
ui->notesEdit->setStyleSheet("color: rgb(0, 0, 0); background-color: rgb(255, 255, 255)");
ui->aliasDisclaimer->setText(tr("<font color='blue'>Select an Alias</font>"));
m_netwManager = new QNetworkAccessManager(this);
m_placeholderImage.load(":/images/" + theme + "/imageplaceholder");
ui->imageButton->setToolTip(tr("Click to open image in browser..."));
ui->infoCert->setVisible(false);
ui->certLabel->setVisible(false);
RefreshImage();
}
void AcceptandPayOfferListPage::loadAliases()
{
ui->aliasEdit->clear();
string strMethod = string("aliaslist");
UniValue params(UniValue::VARR);
UniValue result ;
string name_str;
int expired = 0;
try {
result = tableRPC.execute(strMethod, params);
if (result.type() == UniValue::VARR)
{
name_str = "";
expired = 0;
const UniValue &arr = result.get_array();
for (unsigned int idx = 0; idx < arr.size(); idx++) {
const UniValue& input = arr[idx];
if (input.type() != UniValue::VOBJ)
continue;
const UniValue& o = input.get_obj();
name_str = "";
expired = 0;
const UniValue& name_value = find_value(o, "name");
if (name_value.type() == UniValue::VSTR)
name_str = name_value.get_str();
const UniValue& expired_value = find_value(o, "expired");
if (expired_value.type() == UniValue::VNUM)
expired = expired_value.get_int();
if(expired == 0)
{
QString name = QString::fromStdString(name_str);
ui->aliasEdit->addItem(name);
}
}
}
}
catch (UniValue& objError)
{
string strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()),
QMessageBox::Ok, QMessageBox::Ok);
}
}
void AcceptandPayOfferListPage::on_imageButton_clicked()
{
if(m_url.isValid())
QDesktopServices::openUrl(QUrl(m_url.toString(),QUrl::TolerantMode));
}
void AcceptandPayOfferListPage::netwManagerFinished()
{
QNetworkReply* reply = (QNetworkReply*)sender();
if(!reply)
return;
if (reply->error() != QNetworkReply::NoError) {
QMessageBox::critical(this, windowTitle(),
reply->errorString(),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
QByteArray imageData = reply->readAll();
QPixmap pixmap;
pixmap.loadFromData(imageData);
QIcon ButtonIcon(pixmap);
ui->imageButton->setIcon(ButtonIcon);
reply->deleteLater();
}
AcceptandPayOfferListPage::~AcceptandPayOfferListPage()
{
delete ui;
this->URIHandled = false;
}
void AcceptandPayOfferListPage::resetState()
{
this->offerPaid = false;
this->URIHandled = false;
updateCaption();
}
void AcceptandPayOfferListPage::updateCaption()
{
if(this->offerPaid)
{
ui->labelExplanation->setText(tr("<font color='green'>You have successfully paid for this offer!</font>"));
}
else
{
ui->labelExplanation->setText(tr("Purchase this offer, Syscoin will be used from your balance to complete the transaction"));
}
}
void AcceptandPayOfferListPage::OpenPayDialog()
{
OfferAcceptDialog dlg(platformStyle, ui->aliasPegEdit->text(), ui->aliasEdit->currentText(), ui->offeridEdit->text(), ui->qtyEdit->text(), ui->notesEdit->toPlainText(), ui->infoTitle->text(), ui->infoCurrency->text(), ui->infoPrice->text(), ui->sellerEdit->text(), sAddress, this);
if(dlg.exec())
{
this->offerPaid = dlg.getPaymentStatus();
}
updateCaption();
}
void AcceptandPayOfferListPage::OpenBTCPayDialog()
{
OfferAcceptDialogBTC dlg(platformStyle, ui->aliasEdit->text(), ui->offeridEdit->text(), ui->qtyEdit->text(), ui->notesEdit->toPlainText(), ui->infoTitle->text(), ui->infoCurrency->text(), ui->infoPrice->text(), ui->sellerEdit->text(), sAddress, this);
if(dlg.exec())
{
this->offerPaid = dlg.getPaymentStatus();
}
updateCaption();
}
// send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands.
void AcceptandPayOfferListPage::acceptOffer()
{
if(ui->qtyEdit->text().toUInt() <= 0)
{
QMessageBox::information(this, windowTitle(),
tr("Invalid quantity when trying to accept this offer!"),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if(ui->notesEdit->toPlainText().size() <= 0 && ui->infoCert->text().size() <= 0)
{
QMessageBox::information(this, windowTitle(),
tr("Please enter pertinent information required to the offer in the <b>Notes</b> field (address, e-mail address, shipping notes, etc)."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if(ui->aliasEdit->currentText().size() <= 0)
{
QMessageBox::information(this, windowTitle(),
tr("Please choose an alias before purchasing this offer."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
this->offerPaid = false;
ui->labelExplanation->setText(tr("Waiting for confirmation on the purchase of this offer"));
if(bOnlyAcceptBTC)
OpenBTCPayDialog();
else
OpenPayDialog();
}
bool AcceptandPayOfferListPage::lookup(const QString &lookupid)
{
QString id = lookupid;
if(id == QString(""))
{
id = ui->offeridEdit->text();
}
string strError;
string strMethod = string("offerinfo");
UniValue params(UniValue::VARR);
UniValue result;
params.push_back(id.toStdString());
try {
result = tableRPC.execute(strMethod, params);
if (result.type() == UniValue::VOBJ)
{
const UniValue &offerObj = result.get_obj();
COffer offerOut;
const string &strRand = find_value(offerObj, "offer").get_str();
const string &strAddress = find_value(offerObj, "address").get_str();
offerOut.vchCert = vchFromString(find_value(offerObj, "cert").get_str());
string alias = find_value(offerObj, "alias").get_str();
offerOut.sTitle = vchFromString(find_value(offerObj, "title").get_str());
offerOut.sCategory = vchFromString(find_value(offerObj, "category").get_str());
offerOut.sCurrencyCode = vchFromString(find_value(offerObj, "currency").get_str());
offerOut.vchAliasPeg = vchFromString(find_value(offerObj, "alias_peg").get_str());
if(find_value(offerObj, "quantity").get_str() == "unlimited")
offerOut.nQty = -1;
else
offerOut.nQty = QString::fromStdString(find_value(offerObj, "quantity").get_str()).toUInt();
offerOut.bOnlyAcceptBTC = find_value(offerObj, "btconly").get_str() == "Yes"? true: false;
string descString = find_value(offerObj, "description").get_str();
offerOut.sDescription = vchFromString(descString);
UniValue outerDescValue(UniValue::VSTR);
bool read = outerDescValue.read(descString);
if (read)
{
if(outerDescValue.type() == UniValue::VOBJ)
{
const UniValue &outerDescObj = outerDescValue.get_obj();
const UniValue &descValue = find_value(outerDescObj, "description");
if (descValue.type() == UniValue::VSTR)
{
offerOut.sDescription = vchFromString(descValue.get_str());
}
}
}
setValue(QString::fromStdString(alias), QString::fromStdString(strRand), offerOut, QString::fromStdString(find_value(offerObj, "price").get_str()), QString::fromStdString(strAddress));
return true;
}
}
catch (UniValue& objError)
{
QMessageBox::critical(this, windowTitle(),
tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + id,
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("There was an exception trying to locate this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + QString::fromStdString(e.what()),
QMessageBox::Ok, QMessageBox::Ok);
}
return false;
}
bool AcceptandPayOfferListPage::handlePaymentRequest(const SendCoinsRecipient *rv)
{
if(this->URIHandled)
{
QMessageBox::critical(this, windowTitle(),
tr("URI has been already handled"),
QMessageBox::Ok, QMessageBox::Ok);
return false;
}
ui->qtyEdit->setText(QString::number(rv->amount));
ui->notesEdit->setPlainText(rv->message);
if(lookup(rv->address))
{
this->URIHandled = true;
acceptOffer();
this->URIHandled = false;
}
return true;
}
void AcceptandPayOfferListPage::setValue(const QString& strAlias, const QString& strRand, COffer &offer, QString price, QString address)
{
loadAliases();
ui->offeridEdit->setText(strRand);
if(!offer.vchCert.empty())
{
ui->infoCert->setVisible(true);
ui->certLabel->setVisible(true);
ui->infoCert->setText(QString::fromStdString(stringFromVch(offer.vchCert)));
}
else
{
ui->infoCert->setVisible(false);
ui->infoCert->setText("");
ui->certLabel->setVisible(false);
}
ui->sellerEdit->setText(strAlias);
ui->infoTitle->setText(QString::fromStdString(stringFromVch(offer.sTitle)));
ui->infoCategory->setText(QString::fromStdString(stringFromVch(offer.sCategory)));
ui->infoCurrency->setText(QString::fromStdString(stringFromVch(offer.sCurrencyCode)));
ui->aliasPegEdit->setText(QString::fromStdString(stringFromVch(offer.vchAliasPeg)));
ui->infoPrice->setText(price);
if(offer.nQty == -1)
ui->infoQty->setText(tr("unlimited"));
else
ui->infoQty->setText(QString::number(offer.nQty));
ui->infoDescription->setPlainText(QString::fromStdString(stringFromVch(offer.sDescription)));
ui->qtyEdit->setText(QString("1"));
ui->notesEdit->setPlainText(QString(""));
bOnlyAcceptBTC = offer.bOnlyAcceptBTC;
sAddress = address;
QRegExp rx("(?:https?|ftp)://\\S+");
rx.indexIn(QString::fromStdString(stringFromVch(offer.sDescription)));
m_imageList = rx.capturedTexts();
RefreshImage();
}
void AcceptandPayOfferListPage::RefreshImage()
{
QIcon ButtonIcon(m_placeholderImage);
ui->imageButton->setIcon(ButtonIcon);
if(m_imageList.size() > 0 && m_imageList.at(0) != QString(""))
{
QString parsedURL = m_imageList.at(0).simplified();
m_url = QUrl(parsedURL);
if(m_url.isValid())
{
QNetworkRequest request(m_url);
request.setRawHeader("Accept", "q=0.9,image/webp,*/*;q=0.8");
request.setRawHeader("Cache-Control", "no-cache");
request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36");
QNetworkReply *reply = m_netwManager->get(request);
reply->ignoreSslErrors();
connect(reply, SIGNAL(finished()), this, SLOT(netwManagerFinished()));
}
}
}
<commit_msg>typo<commit_after>#include "acceptandpayofferlistpage.h"
#include "ui_acceptandpayofferlistpage.h"
#include "init.h"
#include "util.h"
#include "offeracceptdialog.h"
#include "offeracceptdialogbtc.h"
#include "offer.h"
#include "syscoingui.h"
#include "guiutil.h"
#include "platformstyle.h"
#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
#include <QString>
#include <QByteArray>
#include <QPixmap>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QRegExp>
#include <QStringList>
#include <QDesktopServices>
#include "rpcserver.h"
#include "alias.h"
#include "walletmodel.h"
using namespace std;
extern const CRPCTable tableRPC;
AcceptandPayOfferListPage::AcceptandPayOfferListPage(const PlatformStyle *platformStyle, QWidget *parent) :
QDialog(parent), platformStyle(platformStyle),
ui(new Ui::AcceptandPayOfferListPage)
{
sAddress = "";
bOnlyAcceptBTC = false;
ui->setupUi(this);
QString theme = GUIUtil::getThemeName();
if (!platformStyle->getImagesOnButtons())
{
ui->lookupButton->setIcon(QIcon());
ui->acceptButton->setIcon(QIcon());
ui->imageButton->setIcon(QIcon());
}
else
{
ui->lookupButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/search"));
ui->acceptButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/cart"));
}
ui->imageButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/imageplaceholder"));
this->offerPaid = false;
this->URIHandled = false;
ui->labelExplanation->setText(tr("Purchase an offer, Syscoin will be used from your balance to complete the transaction"));
connect(ui->acceptButton, SIGNAL(clicked()), this, SLOT(acceptOffer()));
connect(ui->lookupButton, SIGNAL(clicked()), this, SLOT(lookup()));
connect(ui->offeridEdit, SIGNAL(textChanged(const QString &)), this, SLOT(resetState()));
ui->notesEdit->setStyleSheet("color: rgb(0, 0, 0); background-color: rgb(255, 255, 255)");
ui->aliasDisclaimer->setText(tr("<font color='blue'>Select an Alias</font>"));
m_netwManager = new QNetworkAccessManager(this);
m_placeholderImage.load(":/images/" + theme + "/imageplaceholder");
ui->imageButton->setToolTip(tr("Click to open image in browser..."));
ui->infoCert->setVisible(false);
ui->certLabel->setVisible(false);
RefreshImage();
}
void AcceptandPayOfferListPage::loadAliases()
{
ui->aliasEdit->clear();
string strMethod = string("aliaslist");
UniValue params(UniValue::VARR);
UniValue result ;
string name_str;
int expired = 0;
try {
result = tableRPC.execute(strMethod, params);
if (result.type() == UniValue::VARR)
{
name_str = "";
expired = 0;
const UniValue &arr = result.get_array();
for (unsigned int idx = 0; idx < arr.size(); idx++) {
const UniValue& input = arr[idx];
if (input.type() != UniValue::VOBJ)
continue;
const UniValue& o = input.get_obj();
name_str = "";
expired = 0;
const UniValue& name_value = find_value(o, "name");
if (name_value.type() == UniValue::VSTR)
name_str = name_value.get_str();
const UniValue& expired_value = find_value(o, "expired");
if (expired_value.type() == UniValue::VNUM)
expired = expired_value.get_int();
if(expired == 0)
{
QString name = QString::fromStdString(name_str);
ui->aliasEdit->addItem(name);
}
}
}
}
catch (UniValue& objError)
{
string strError = find_value(objError, "message").get_str();
QMessageBox::critical(this, windowTitle(),
tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)),
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()),
QMessageBox::Ok, QMessageBox::Ok);
}
}
void AcceptandPayOfferListPage::on_imageButton_clicked()
{
if(m_url.isValid())
QDesktopServices::openUrl(QUrl(m_url.toString(),QUrl::TolerantMode));
}
void AcceptandPayOfferListPage::netwManagerFinished()
{
QNetworkReply* reply = (QNetworkReply*)sender();
if(!reply)
return;
if (reply->error() != QNetworkReply::NoError) {
QMessageBox::critical(this, windowTitle(),
reply->errorString(),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
QByteArray imageData = reply->readAll();
QPixmap pixmap;
pixmap.loadFromData(imageData);
QIcon ButtonIcon(pixmap);
ui->imageButton->setIcon(ButtonIcon);
reply->deleteLater();
}
AcceptandPayOfferListPage::~AcceptandPayOfferListPage()
{
delete ui;
this->URIHandled = false;
}
void AcceptandPayOfferListPage::resetState()
{
this->offerPaid = false;
this->URIHandled = false;
updateCaption();
}
void AcceptandPayOfferListPage::updateCaption()
{
if(this->offerPaid)
{
ui->labelExplanation->setText(tr("<font color='green'>You have successfully paid for this offer!</font>"));
}
else
{
ui->labelExplanation->setText(tr("Purchase this offer, Syscoin will be used from your balance to complete the transaction"));
}
}
void AcceptandPayOfferListPage::OpenPayDialog()
{
OfferAcceptDialog dlg(platformStyle, ui->aliasPegEdit->text(), ui->aliasEdit->currentText(), ui->offeridEdit->text(), ui->qtyEdit->text(), ui->notesEdit->toPlainText(), ui->infoTitle->text(), ui->infoCurrency->text(), ui->infoPrice->text(), ui->sellerEdit->text(), sAddress, this);
if(dlg.exec())
{
this->offerPaid = dlg.getPaymentStatus();
}
updateCaption();
}
void AcceptandPayOfferListPage::OpenBTCPayDialog()
{
OfferAcceptDialogBTC dlg(platformStyle, ui->aliasEdit->currentText(), ui->offeridEdit->text(), ui->qtyEdit->text(), ui->notesEdit->toPlainText(), ui->infoTitle->text(), ui->infoCurrency->text(), ui->infoPrice->text(), ui->sellerEdit->text(), sAddress, this);
if(dlg.exec())
{
this->offerPaid = dlg.getPaymentStatus();
}
updateCaption();
}
// send offeraccept with offer guid/qty as params and then send offerpay with wtxid (first param of response) as param, using RPC commands.
void AcceptandPayOfferListPage::acceptOffer()
{
if(ui->qtyEdit->text().toUInt() <= 0)
{
QMessageBox::information(this, windowTitle(),
tr("Invalid quantity when trying to accept this offer!"),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if(ui->notesEdit->toPlainText().size() <= 0 && ui->infoCert->text().size() <= 0)
{
QMessageBox::information(this, windowTitle(),
tr("Please enter pertinent information required to the offer in the <b>Notes</b> field (address, e-mail address, shipping notes, etc)."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
if(ui->aliasEdit->currentText().size() <= 0)
{
QMessageBox::information(this, windowTitle(),
tr("Please choose an alias before purchasing this offer."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
this->offerPaid = false;
ui->labelExplanation->setText(tr("Waiting for confirmation on the purchase of this offer"));
if(bOnlyAcceptBTC)
OpenBTCPayDialog();
else
OpenPayDialog();
}
bool AcceptandPayOfferListPage::lookup(const QString &lookupid)
{
QString id = lookupid;
if(id == QString(""))
{
id = ui->offeridEdit->text();
}
string strError;
string strMethod = string("offerinfo");
UniValue params(UniValue::VARR);
UniValue result;
params.push_back(id.toStdString());
try {
result = tableRPC.execute(strMethod, params);
if (result.type() == UniValue::VOBJ)
{
const UniValue &offerObj = result.get_obj();
COffer offerOut;
const string &strRand = find_value(offerObj, "offer").get_str();
const string &strAddress = find_value(offerObj, "address").get_str();
offerOut.vchCert = vchFromString(find_value(offerObj, "cert").get_str());
string alias = find_value(offerObj, "alias").get_str();
offerOut.sTitle = vchFromString(find_value(offerObj, "title").get_str());
offerOut.sCategory = vchFromString(find_value(offerObj, "category").get_str());
offerOut.sCurrencyCode = vchFromString(find_value(offerObj, "currency").get_str());
offerOut.vchAliasPeg = vchFromString(find_value(offerObj, "alias_peg").get_str());
if(find_value(offerObj, "quantity").get_str() == "unlimited")
offerOut.nQty = -1;
else
offerOut.nQty = QString::fromStdString(find_value(offerObj, "quantity").get_str()).toUInt();
offerOut.bOnlyAcceptBTC = find_value(offerObj, "btconly").get_str() == "Yes"? true: false;
string descString = find_value(offerObj, "description").get_str();
offerOut.sDescription = vchFromString(descString);
UniValue outerDescValue(UniValue::VSTR);
bool read = outerDescValue.read(descString);
if (read)
{
if(outerDescValue.type() == UniValue::VOBJ)
{
const UniValue &outerDescObj = outerDescValue.get_obj();
const UniValue &descValue = find_value(outerDescObj, "description");
if (descValue.type() == UniValue::VSTR)
{
offerOut.sDescription = vchFromString(descValue.get_str());
}
}
}
setValue(QString::fromStdString(alias), QString::fromStdString(strRand), offerOut, QString::fromStdString(find_value(offerObj, "price").get_str()), QString::fromStdString(strAddress));
return true;
}
}
catch (UniValue& objError)
{
QMessageBox::critical(this, windowTitle(),
tr("Could not find this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + id,
QMessageBox::Ok, QMessageBox::Ok);
}
catch(std::exception& e)
{
QMessageBox::critical(this, windowTitle(),
tr("There was an exception trying to locate this offer, please check the offer ID and that it has been confirmed by the blockchain: ") + QString::fromStdString(e.what()),
QMessageBox::Ok, QMessageBox::Ok);
}
return false;
}
bool AcceptandPayOfferListPage::handlePaymentRequest(const SendCoinsRecipient *rv)
{
if(this->URIHandled)
{
QMessageBox::critical(this, windowTitle(),
tr("URI has been already handled"),
QMessageBox::Ok, QMessageBox::Ok);
return false;
}
ui->qtyEdit->setText(QString::number(rv->amount));
ui->notesEdit->setPlainText(rv->message);
if(lookup(rv->address))
{
this->URIHandled = true;
acceptOffer();
this->URIHandled = false;
}
return true;
}
void AcceptandPayOfferListPage::setValue(const QString& strAlias, const QString& strRand, COffer &offer, QString price, QString address)
{
loadAliases();
ui->offeridEdit->setText(strRand);
if(!offer.vchCert.empty())
{
ui->infoCert->setVisible(true);
ui->certLabel->setVisible(true);
ui->infoCert->setText(QString::fromStdString(stringFromVch(offer.vchCert)));
}
else
{
ui->infoCert->setVisible(false);
ui->infoCert->setText("");
ui->certLabel->setVisible(false);
}
ui->sellerEdit->setText(strAlias);
ui->infoTitle->setText(QString::fromStdString(stringFromVch(offer.sTitle)));
ui->infoCategory->setText(QString::fromStdString(stringFromVch(offer.sCategory)));
ui->infoCurrency->setText(QString::fromStdString(stringFromVch(offer.sCurrencyCode)));
ui->aliasPegEdit->setText(QString::fromStdString(stringFromVch(offer.vchAliasPeg)));
ui->infoPrice->setText(price);
if(offer.nQty == -1)
ui->infoQty->setText(tr("unlimited"));
else
ui->infoQty->setText(QString::number(offer.nQty));
ui->infoDescription->setPlainText(QString::fromStdString(stringFromVch(offer.sDescription)));
ui->qtyEdit->setText(QString("1"));
ui->notesEdit->setPlainText(QString(""));
bOnlyAcceptBTC = offer.bOnlyAcceptBTC;
sAddress = address;
QRegExp rx("(?:https?|ftp)://\\S+");
rx.indexIn(QString::fromStdString(stringFromVch(offer.sDescription)));
m_imageList = rx.capturedTexts();
RefreshImage();
}
void AcceptandPayOfferListPage::RefreshImage()
{
QIcon ButtonIcon(m_placeholderImage);
ui->imageButton->setIcon(ButtonIcon);
if(m_imageList.size() > 0 && m_imageList.at(0) != QString(""))
{
QString parsedURL = m_imageList.at(0).simplified();
m_url = QUrl(parsedURL);
if(m_url.isValid())
{
QNetworkRequest request(m_url);
request.setRawHeader("Accept", "q=0.9,image/webp,*/*;q=0.8");
request.setRawHeader("Cache-Control", "no-cache");
request.setRawHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36");
QNetworkReply *reply = m_netwManager->get(request);
reply->ignoreSslErrors();
connect(reply, SIGNAL(finished()), this, SLOT(netwManagerFinished()));
}
}
}
<|endoftext|> |
<commit_before>/*
* libqtxdg - An Qt implementation of freedesktop.org xdg specs
* Copyright (C) 2018 Luís Pereira <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#include "xdgmimeappsglibbackend.h"
#include "xdgmimeapps.h"
#include "qtxdglogging.h"
#include "xdgdesktopfile.h"
#include <gio/gio.h>
#include <gio/gdesktopappinfo.h>
#include <QDebug>
#include <QLoggingCategory>
#include <QMimeDatabase>
static QList<XdgDesktopFile *> GAppInfoGListToXdgDesktopQList(GList *list)
{
QList<XdgDesktopFile *> dl;
for (GList *l = list; l != nullptr; l = l->next) {
if (l->data) {
const QString file = QString::fromUtf8(g_desktop_app_info_get_filename(G_DESKTOP_APP_INFO(l->data)));
if (!file.isEmpty()) {
XdgDesktopFile *df = new XdgDesktopFile;
if (df->load(file) && df->isValid()) {
dl.append(df);
}
else {
delete df;
}
}
}
}
return dl;
}
static GDesktopAppInfo *XdgDesktopFileToGDesktopAppinfo(const XdgDesktopFile &app)
{
GDesktopAppInfo *gApp = g_desktop_app_info_new_from_filename(app.fileName().toUtf8().constData());
if (gApp == nullptr) {
qCWarning(QtXdgMimeAppsGLib, "Failed to load GDesktopAppInfo for '%s'",
qPrintable(app.fileName()));
return nullptr;
}
return gApp;
}
XdgMimeAppsGLibBackend::XdgMimeAppsGLibBackend(QObject *parent)
: XdgMimeAppsBackendInterface(parent),
mWatcher(nullptr)
{
// Make sure that we have glib support enabled.
qunsetenv("QT_NO_GLIB");
// This is a trick to init the database. Without it, the changed signal
// functionality doesn't work properly. Also make sure optimizaters can't
// make it go away.
volatile GAppInfo *fooApp = g_app_info_get_default_for_type("foo", FALSE);
if (fooApp)
g_object_unref(G_APP_INFO(fooApp));
mWatcher = g_app_info_monitor_get();
if (mWatcher != nullptr) {
g_signal_connect (mWatcher, "changed", G_CALLBACK (_changed), this);
}
}
XdgMimeAppsGLibBackend::~XdgMimeAppsGLibBackend()
{
g_object_unref(mWatcher);
}
void XdgMimeAppsGLibBackend::_changed(GAppInfoMonitor *monitor, XdgMimeAppsGLibBackend *_this)
{
Q_UNUSED(monitor);
Q_EMIT _this->changed();
}
bool XdgMimeAppsGLibBackend::addAssociation(const QString &mimeType, const XdgDesktopFile &app)
{
GDesktopAppInfo *gApp = XdgDesktopFileToGDesktopAppinfo(app);
if (gApp == nullptr)
return false;
GError *error = nullptr;
if (g_app_info_add_supports_type(G_APP_INFO(gApp),
mimeType.toUtf8().constData(), &error) == FALSE) {
qCWarning(QtXdgMimeAppsGLib, "Failed to associate '%s' with '%s'. %s",
qPrintable(mimeType), g_desktop_app_info_get_filename(gApp), error->message);
g_error_free(error);
g_object_unref(gApp);
return false;
}
return true;
}
QList<XdgDesktopFile *> XdgMimeAppsGLibBackend::allApps()
{
GList *list = g_app_info_get_all();
QList<XdgDesktopFile *> dl = GAppInfoGListToXdgDesktopQList(list);
g_list_free_full(list, g_object_unref);
return dl;
}
QList<XdgDesktopFile *> XdgMimeAppsGLibBackend::apps(const QString &mimeType)
{
QList<XdgDesktopFile *> dl = recommendedApps(mimeType);
dl.append(fallbackApps(mimeType));
return dl;
}
QList<XdgDesktopFile *> XdgMimeAppsGLibBackend::fallbackApps(const QString &mimeType)
{
// g_app_info_get_fallback_for_type() doesn't returns the ones in the
// recommended list
GList *list = g_app_info_get_fallback_for_type(mimeType.toUtf8().constData());
QList<XdgDesktopFile *> dl = GAppInfoGListToXdgDesktopQList(list);
g_list_free_full(list, g_object_unref);
return dl;
}
QList<XdgDesktopFile *> XdgMimeAppsGLibBackend::recommendedApps(const QString &mimeType)
{
QByteArray ba = mimeType.toUtf8();
const char *contentType = ba.constData();
GAppInfo *defaultApp = g_app_info_get_default_for_type(contentType, FALSE);
GList *list = g_app_info_get_recommended_for_type(contentType);
if (list != nullptr && defaultApp != nullptr) {
GAppInfo *first = G_APP_INFO(g_list_nth_data(list, 0));
GAppInfo *second = G_APP_INFO(g_list_nth_data(list, 1));
if (!g_app_info_equal(defaultApp, first) && g_app_info_equal(defaultApp, second)) {
// we are sure that the first element comes from
// g_app_info_set_as_last_used(). We remove it becouse it's not
// part on the standard
list = g_list_remove(list, first);
}
}
QList<XdgDesktopFile *> dl = GAppInfoGListToXdgDesktopQList(list);
g_list_free_full(list, g_object_unref);
return dl;
}
bool XdgMimeAppsGLibBackend::removeAssociation(const QString &mimeType, const XdgDesktopFile &app)
{
GDesktopAppInfo *gApp = XdgDesktopFileToGDesktopAppinfo(app);
if (gApp == nullptr)
return false;
GError *error = nullptr;
if (g_app_info_remove_supports_type(G_APP_INFO(gApp),
mimeType.toUtf8().constData(), &error) == FALSE) {
qCWarning(QtXdgMimeAppsGLib, "Failed to remove association between '%s' and '%s'. %s",
qPrintable(mimeType), g_desktop_app_info_get_filename(gApp), error->message);
g_error_free(error);
g_object_unref(gApp);
return false;
}
return true;
}
bool XdgMimeAppsGLibBackend::reset(const QString &mimeType)
{
g_app_info_reset_type_associations(mimeType.toUtf8().constData());
return true;
}
XdgDesktopFile *XdgMimeAppsGLibBackend::defaultApp(const QString &mimeType)
{
GAppInfo *appinfo = g_app_info_get_default_for_type(mimeType.toUtf8().constData(), false);
if (appinfo == nullptr || !G_IS_DESKTOP_APP_INFO(appinfo)) {
return nullptr;
}
const char *file = g_desktop_app_info_get_filename(G_DESKTOP_APP_INFO(appinfo));
if (file == nullptr) {
g_object_unref(appinfo);
return nullptr;
}
const QString s = QString::fromUtf8(file);
g_object_unref(appinfo);
XdgDesktopFile *f = new XdgDesktopFile;
if (f->load(s) && f->isValid())
return f;
delete f;
return nullptr;
}
bool XdgMimeAppsGLibBackend::setDefaultApp(const QString &mimeType, const XdgDesktopFile &app)
{
GDesktopAppInfo *gApp = XdgDesktopFileToGDesktopAppinfo(app);
if (gApp == nullptr)
return false;
GError *error = nullptr;
if (g_app_info_set_as_default_for_type(G_APP_INFO(gApp),
mimeType.toUtf8().constData(), &error) == FALSE) {
qCWarning(QtXdgMimeAppsGLib, "Failed to set '%s' as the default for '%s'. %s",
g_desktop_app_info_get_filename(gApp), qPrintable(mimeType), error->message);
g_error_free(error);
g_object_unref(gApp);
return false;
}
qCDebug(QtXdgMimeAppsGLib, "Set '%s' as the default for '%s'",
g_desktop_app_info_get_filename(gApp), qPrintable(mimeType));
g_object_unref(gApp);
return true;
}
<commit_msg>Respect code style<commit_after>/*
* libqtxdg - An Qt implementation of freedesktop.org xdg specs
* Copyright (C) 2018 Luís Pereira <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#include "xdgmimeappsglibbackend.h"
#include "xdgmimeapps.h"
#include "qtxdglogging.h"
#include "xdgdesktopfile.h"
#include <gio/gio.h>
#include <gio/gdesktopappinfo.h>
#include <QDebug>
#include <QLoggingCategory>
#include <QMimeDatabase>
static QList<XdgDesktopFile *> GAppInfoGListToXdgDesktopQList(GList *list)
{
QList<XdgDesktopFile *> dl;
for (GList *l = list; l != nullptr; l = l->next) {
if (l->data) {
const QString file = QString::fromUtf8(g_desktop_app_info_get_filename(G_DESKTOP_APP_INFO(l->data)));
if (!file.isEmpty()) {
XdgDesktopFile *df = new XdgDesktopFile;
if (df->load(file) && df->isValid()) {
dl.append(df);
} else {
delete df;
}
}
}
}
return dl;
}
static GDesktopAppInfo *XdgDesktopFileToGDesktopAppinfo(const XdgDesktopFile &app)
{
GDesktopAppInfo *gApp = g_desktop_app_info_new_from_filename(app.fileName().toUtf8().constData());
if (gApp == nullptr) {
qCWarning(QtXdgMimeAppsGLib, "Failed to load GDesktopAppInfo for '%s'",
qPrintable(app.fileName()));
return nullptr;
}
return gApp;
}
XdgMimeAppsGLibBackend::XdgMimeAppsGLibBackend(QObject *parent)
: XdgMimeAppsBackendInterface(parent),
mWatcher(nullptr)
{
// Make sure that we have glib support enabled.
qunsetenv("QT_NO_GLIB");
// This is a trick to init the database. Without it, the changed signal
// functionality doesn't work properly. Also make sure optimizaters can't
// make it go away.
volatile GAppInfo *fooApp = g_app_info_get_default_for_type("foo", FALSE);
if (fooApp)
g_object_unref(G_APP_INFO(fooApp));
mWatcher = g_app_info_monitor_get();
if (mWatcher != nullptr) {
g_signal_connect (mWatcher, "changed", G_CALLBACK (_changed), this);
}
}
XdgMimeAppsGLibBackend::~XdgMimeAppsGLibBackend()
{
g_object_unref(mWatcher);
}
void XdgMimeAppsGLibBackend::_changed(GAppInfoMonitor *monitor, XdgMimeAppsGLibBackend *_this)
{
Q_UNUSED(monitor);
Q_EMIT _this->changed();
}
bool XdgMimeAppsGLibBackend::addAssociation(const QString &mimeType, const XdgDesktopFile &app)
{
GDesktopAppInfo *gApp = XdgDesktopFileToGDesktopAppinfo(app);
if (gApp == nullptr)
return false;
GError *error = nullptr;
if (g_app_info_add_supports_type(G_APP_INFO(gApp),
mimeType.toUtf8().constData(), &error) == FALSE) {
qCWarning(QtXdgMimeAppsGLib, "Failed to associate '%s' with '%s'. %s",
qPrintable(mimeType), g_desktop_app_info_get_filename(gApp), error->message);
g_error_free(error);
g_object_unref(gApp);
return false;
}
return true;
}
QList<XdgDesktopFile *> XdgMimeAppsGLibBackend::allApps()
{
GList *list = g_app_info_get_all();
QList<XdgDesktopFile *> dl = GAppInfoGListToXdgDesktopQList(list);
g_list_free_full(list, g_object_unref);
return dl;
}
QList<XdgDesktopFile *> XdgMimeAppsGLibBackend::apps(const QString &mimeType)
{
QList<XdgDesktopFile *> dl = recommendedApps(mimeType);
dl.append(fallbackApps(mimeType));
return dl;
}
QList<XdgDesktopFile *> XdgMimeAppsGLibBackend::fallbackApps(const QString &mimeType)
{
// g_app_info_get_fallback_for_type() doesn't returns the ones in the
// recommended list
GList *list = g_app_info_get_fallback_for_type(mimeType.toUtf8().constData());
QList<XdgDesktopFile *> dl = GAppInfoGListToXdgDesktopQList(list);
g_list_free_full(list, g_object_unref);
return dl;
}
QList<XdgDesktopFile *> XdgMimeAppsGLibBackend::recommendedApps(const QString &mimeType)
{
QByteArray ba = mimeType.toUtf8();
const char *contentType = ba.constData();
GAppInfo *defaultApp = g_app_info_get_default_for_type(contentType, FALSE);
GList *list = g_app_info_get_recommended_for_type(contentType);
if (list != nullptr && defaultApp != nullptr) {
GAppInfo *first = G_APP_INFO(g_list_nth_data(list, 0));
GAppInfo *second = G_APP_INFO(g_list_nth_data(list, 1));
if (!g_app_info_equal(defaultApp, first) && g_app_info_equal(defaultApp, second)) {
// we are sure that the first element comes from
// g_app_info_set_as_last_used(). We remove it becouse it's not
// part on the standard
list = g_list_remove(list, first);
}
}
QList<XdgDesktopFile *> dl = GAppInfoGListToXdgDesktopQList(list);
g_list_free_full(list, g_object_unref);
return dl;
}
bool XdgMimeAppsGLibBackend::removeAssociation(const QString &mimeType, const XdgDesktopFile &app)
{
GDesktopAppInfo *gApp = XdgDesktopFileToGDesktopAppinfo(app);
if (gApp == nullptr)
return false;
GError *error = nullptr;
if (g_app_info_remove_supports_type(G_APP_INFO(gApp),
mimeType.toUtf8().constData(), &error) == FALSE) {
qCWarning(QtXdgMimeAppsGLib, "Failed to remove association between '%s' and '%s'. %s",
qPrintable(mimeType), g_desktop_app_info_get_filename(gApp), error->message);
g_error_free(error);
g_object_unref(gApp);
return false;
}
return true;
}
bool XdgMimeAppsGLibBackend::reset(const QString &mimeType)
{
g_app_info_reset_type_associations(mimeType.toUtf8().constData());
return true;
}
XdgDesktopFile *XdgMimeAppsGLibBackend::defaultApp(const QString &mimeType)
{
GAppInfo *appinfo = g_app_info_get_default_for_type(mimeType.toUtf8().constData(), false);
if (appinfo == nullptr || !G_IS_DESKTOP_APP_INFO(appinfo)) {
return nullptr;
}
const char *file = g_desktop_app_info_get_filename(G_DESKTOP_APP_INFO(appinfo));
if (file == nullptr) {
g_object_unref(appinfo);
return nullptr;
}
const QString s = QString::fromUtf8(file);
g_object_unref(appinfo);
XdgDesktopFile *f = new XdgDesktopFile;
if (f->load(s) && f->isValid())
return f;
delete f;
return nullptr;
}
bool XdgMimeAppsGLibBackend::setDefaultApp(const QString &mimeType, const XdgDesktopFile &app)
{
GDesktopAppInfo *gApp = XdgDesktopFileToGDesktopAppinfo(app);
if (gApp == nullptr)
return false;
GError *error = nullptr;
if (g_app_info_set_as_default_for_type(G_APP_INFO(gApp),
mimeType.toUtf8().constData(), &error) == FALSE) {
qCWarning(QtXdgMimeAppsGLib, "Failed to set '%s' as the default for '%s'. %s",
g_desktop_app_info_get_filename(gApp), qPrintable(mimeType), error->message);
g_error_free(error);
g_object_unref(gApp);
return false;
}
qCDebug(QtXdgMimeAppsGLib, "Set '%s' as the default for '%s'",
g_desktop_app_info_get_filename(gApp), qPrintable(mimeType));
g_object_unref(gApp);
return true;
}
<|endoftext|> |
<commit_before>#include "writer/verilog/self_shell.h"
#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "iroha/resource_params.h"
#include "writer/verilog/axi/axi_shell.h"
#include "writer/verilog/ext_task.h"
#include "writer/verilog/table.h"
namespace iroha {
namespace writer {
namespace verilog {
SelfShell::SelfShell(const IDesign *design, const PortSet *ports,
bool reset_polarity)
: design_(design), ports_(ports), reset_polarity_(reset_polarity) {
for (IModule *mod : design->modules_) {
ProcessModule(mod);
}
}
void SelfShell::WriteWireDecl(ostream &os) {
for (IResource *res : axi_) {
axi::AxiShell shell(res);
shell.WriteWireDecl(os);
}
for (IResource *res : ext_input_) {
auto *params = res->GetParams();
string input_port;
int width;
params->GetExtInputPort(&input_port, &width);
os << " wire " << Table::WidthSpec(width) << input_port << ";\n";
os << " assign " << input_port << " = 0;\n";
}
for (IResource *res : ext_task_entry_) {
string v = ExtTask::ReqValidPin(res);
os << " wire " << v << ";\n"
<< " assign " << v << " = 0;\n";
}
for (IResource *res : ext_task_call_) {
string req_ready = ExtTask::ReqReadyPin(res);
os << " wire " << req_ready << ";\n"
<< " assign " << req_ready << " = 1;\n";
}
for (IResource *res : ext_task_wait_) {
string res_valid = ExtTask::ResValidPin(res->GetParentResource());
os << " wire " << res_valid << ";\n"
<< " assign " << res_valid << " = 1;\n";
for (int i = 0; i < res->output_types_.size(); ++i) {
string d = ExtTask::DataPin(res, i);
os << " wire "
<< Table::WidthSpec(res->output_types_[i].GetWidth())
<< d << ";\n"
<< " assign " << d << " = 0;\n";
}
}
}
void SelfShell::WritePortConnection(ostream &os) {
for (IResource *res : axi_) {
axi::AxiShell shell(res);
shell.WritePortConnection(os);
}
for (IResource *res : ext_input_) {
auto *params = res->GetParams();
string input_port;
int width;
params->GetExtInputPort(&input_port, &width);
os << ", ." << input_port << "(" << input_port << ")";
}
for (IResource *res : ext_task_entry_) {
string v = ExtTask::ReqValidPin(res);
os << ", ." << v << "(" << v << ")";
}
for (IResource *res : ext_task_call_) {
string req_ready = ExtTask::ReqReadyPin(res);
os << ", ." << req_ready << "(" << req_ready << ")";
}
for (IResource *res : ext_task_wait_) {
string res_valid = ExtTask::ResValidPin(res->GetParentResource());
os << ", ." << res_valid << "(" << res_valid << ")";
for (int i = 0; i < res->output_types_.size(); ++i) {
string d = ExtTask::DataPin(res, i);
os << ", ." << d << "(" << d << ")";
}
}
}
void SelfShell::WriteShellFSM(ostream &os) {
for (IResource *res : axi_) {
axi::AxiShell shell(res);
shell.WriteFSM(ports_, reset_polarity_, os);
}
}
void SelfShell::ProcessModule(IModule *mod) {
for (ITable *tab : mod->tables_) {
for (IResource *res : tab->resources_) {
auto *klass = res->GetClass();
if (resource::IsAxiMasterPort(*klass) ||
resource::IsAxiSlavePort(*klass)) {
axi_.push_back(res);
}
if (resource::IsExtInput(*klass)) {
ext_input_.push_back(res);
}
if (resource::IsExtTask(*klass)) {
ext_task_entry_.push_back(res);
}
if (resource::IsExtTaskCall(*klass)) {
ext_task_call_.push_back(res);
}
if (resource::IsExtTaskWait(*klass)) {
ext_task_wait_.push_back(res);
}
}
}
}
} // namespace verilog
} // namespace writer
} // namespace iroha
<commit_msg>Don't generate signal for internal module.<commit_after>#include "writer/verilog/self_shell.h"
#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "iroha/resource_params.h"
#include "writer/verilog/axi/axi_shell.h"
#include "writer/verilog/ext_task.h"
#include "writer/verilog/table.h"
namespace iroha {
namespace writer {
namespace verilog {
SelfShell::SelfShell(const IDesign *design, const PortSet *ports,
bool reset_polarity)
: design_(design), ports_(ports), reset_polarity_(reset_polarity) {
for (IModule *mod : design->modules_) {
ProcessModule(mod);
}
}
void SelfShell::WriteWireDecl(ostream &os) {
for (IResource *res : axi_) {
axi::AxiShell shell(res);
shell.WriteWireDecl(os);
}
for (IResource *res : ext_input_) {
auto *params = res->GetParams();
string input_port;
int width;
params->GetExtInputPort(&input_port, &width);
os << " wire " << Table::WidthSpec(width) << input_port << ";\n";
os << " assign " << input_port << " = 0;\n";
}
for (IResource *res : ext_task_entry_) {
string v = ExtTask::ReqValidPin(res);
os << " wire " << v << ";\n"
<< " assign " << v << " = 0;\n";
}
for (IResource *res : ext_task_call_) {
string req_ready = ExtTask::ReqReadyPin(res);
os << " wire " << req_ready << ";\n"
<< " assign " << req_ready << " = 1;\n";
}
for (IResource *res : ext_task_wait_) {
string res_valid = ExtTask::ResValidPin(res->GetParentResource());
os << " wire " << res_valid << ";\n"
<< " assign " << res_valid << " = 1;\n";
for (int i = 0; i < res->output_types_.size(); ++i) {
string d = ExtTask::DataPin(res, i);
os << " wire "
<< Table::WidthSpec(res->output_types_[i].GetWidth())
<< d << ";\n"
<< " assign " << d << " = 0;\n";
}
}
}
void SelfShell::WritePortConnection(ostream &os) {
for (IResource *res : axi_) {
axi::AxiShell shell(res);
shell.WritePortConnection(os);
}
for (IResource *res : ext_input_) {
auto *params = res->GetParams();
string input_port;
int width;
params->GetExtInputPort(&input_port, &width);
os << ", ." << input_port << "(" << input_port << ")";
}
for (IResource *res : ext_task_entry_) {
string v = ExtTask::ReqValidPin(res);
os << ", ." << v << "(" << v << ")";
}
for (IResource *res : ext_task_call_) {
if (res->GetParams()->GetEmbeddedModuleFileName().empty()) {
string req_ready = ExtTask::ReqReadyPin(res);
os << ", ." << req_ready << "(" << req_ready << ")";
}
}
for (IResource *res : ext_task_wait_) {
string res_valid = ExtTask::ResValidPin(res->GetParentResource());
os << ", ." << res_valid << "(" << res_valid << ")";
for (int i = 0; i < res->output_types_.size(); ++i) {
string d = ExtTask::DataPin(res, i);
os << ", ." << d << "(" << d << ")";
}
}
}
void SelfShell::WriteShellFSM(ostream &os) {
for (IResource *res : axi_) {
axi::AxiShell shell(res);
shell.WriteFSM(ports_, reset_polarity_, os);
}
}
void SelfShell::ProcessModule(IModule *mod) {
for (ITable *tab : mod->tables_) {
for (IResource *res : tab->resources_) {
auto *klass = res->GetClass();
if (resource::IsAxiMasterPort(*klass) ||
resource::IsAxiSlavePort(*klass)) {
axi_.push_back(res);
}
if (resource::IsExtInput(*klass)) {
ext_input_.push_back(res);
}
if (resource::IsExtTask(*klass)) {
ext_task_entry_.push_back(res);
}
if (resource::IsExtTaskCall(*klass)) {
ext_task_call_.push_back(res);
}
if (resource::IsExtTaskWait(*klass)) {
ext_task_wait_.push_back(res);
}
}
}
}
} // namespace verilog
} // namespace writer
} // namespace iroha
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "utIterator.h"
int main( int argc , char **argv )
{
testing :: InitGoogleTest( &argc , argv ) ;
return RUN_ALL_TESTS( ) ;
}
<commit_msg>Delete mainIterator.cpp<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RemoveNullcheckStringArg.h"
#include "CFGMutation.h"
#include "Creators.h"
#include "DexClass.h"
#include "DexUtil.h"
#include "KotlinNullCheckMethods.h"
#include "PassManager.h"
#include "ReachingDefinitions.h"
#include "Show.h"
#include "Trace.h"
#include "Walkers.h"
using namespace kotlin_nullcheck_wrapper;
void RemoveNullcheckStringArg::run_pass(DexStoresVector& stores,
ConfigFiles& /*conf*/,
PassManager& mgr) {
TransferMap transfer_map;
std::unordered_set<DexMethod*> new_methods;
if (!setup(transfer_map, new_methods)) {
TRACE(NULLCHECK, 2, "RemoveNullcheckStringArgPass: setup failed");
return;
}
Scope scope = build_class_scope(stores);
Stats stats = walk::parallel::methods<Stats>(scope, [&](DexMethod* method) {
auto code = method->get_code();
if (method->rstate.no_optimizations() || code == nullptr ||
new_methods.count(method)) {
return Stats();
}
code->build_cfg();
auto local_stats =
change_in_cfg(code->cfg(), transfer_map, method->is_virtual());
code->clear_cfg();
return local_stats;
});
stats.report(mgr);
}
bool RemoveNullcheckStringArg::setup(
TransferMap& transfer_map, std::unordered_set<DexMethod*>& new_methods) {
bool is_param_check_V1_4 = false;
DexMethodRef* builtin_param =
DexMethod::get_method(CHECK_PARAM_NULL_SIGNATURE_V1_3);
if (!builtin_param) {
is_param_check_V1_4 = true;
builtin_param = DexMethod::get_method(CHECK_PARAM_NULL_SIGNATURE_V1_4);
}
/* If we didn't find the method, giveup. */
if (!builtin_param) {
return false;
}
bool is_expr_check_V1_4 = false;
DexMethodRef* builtin_expr =
DexMethod::get_method(CHECK_EXPR_NULL_SIGNATURE_V1_3);
if (!builtin_expr) {
is_expr_check_V1_4 = true;
builtin_expr = DexMethod::get_method(CHECK_EXPR_NULL_SIGNATURE_V1_4);
}
if (!builtin_expr) {
return false;
}
if (is_expr_check_V1_4 != is_param_check_V1_4) {
/* We have V1_3 and v1_4 mthods. */
TRACE(NULLCHECK, 1, "We have Kotlin 1.3 and 1.4 NULLCHECK assertions");
return false;
}
auto new_check_param_method = get_wrapper_method_with_int_index(
NEW_CHECK_PARAM_NULL_SIGNATURE, WRAPPER_CHECK_PARAM_NULL_METHOD,
builtin_param);
auto new_check_expr_method =
get_wrapper_method(NEW_CHECK_EXPR_NULL_SIGNATURE,
WRAPPER_CHECK_EXPR_NULL_METHOD, builtin_expr);
/* If we could not generate suitable wrapper method, giveup. */
if (!new_check_param_method || !new_check_expr_method) {
return false;
}
transfer_map[builtin_param] = std::make_pair(new_check_param_method, true);
transfer_map[builtin_expr] = std::make_pair(new_check_expr_method, false);
new_methods.insert(new_check_expr_method);
new_methods.insert(new_check_param_method);
return true;
}
DexMethod* RemoveNullcheckStringArg::get_wrapper_method(
const char* wrapper_signature,
const char* wrapper_name,
DexMethodRef* builtin) {
if (DexMethod::get_method(wrapper_signature)) {
/* Wrapper method already exist. */
return nullptr;
}
auto host_cls = type_class(builtin->get_class());
if (!host_cls) {
return nullptr;
}
DexTypeList* arg_signature =
DexTypeList::make_type_list({type::java_lang_Object()});
const auto proto = DexProto::make_proto(type::_void(), arg_signature);
MethodCreator method_creator(host_cls->get_type(),
DexString::make_string(wrapper_name),
proto,
ACC_PUBLIC | ACC_STATIC);
auto obj_arg = method_creator.get_local(0);
auto main_block = method_creator.get_main_block();
auto str_type = DexType::get_type("Ljava/lang/String;");
if (!str_type) {
return nullptr;
}
auto str_const = method_creator.make_local(str_type);
// const-string v2, "UNKNOWN"
main_block->load_const(str_const, DexString::make_string("UNKNOWN"));
main_block->invoke(OPCODE_INVOKE_STATIC, builtin, {obj_arg, str_const});
main_block->ret_void();
auto new_method = method_creator.create();
TRACE(NULLCHECK, 5, "Created Method : %s", SHOW(new_method->get_code()));
host_cls->add_method(new_method);
return new_method;
}
DexMethod* RemoveNullcheckStringArg::get_wrapper_method_with_int_index(
const char* wrapper_signature,
const char* wrapper_name,
DexMethodRef* builtin) {
if (DexMethod::get_method(wrapper_signature)) {
/* Wrapper method already exist. */
return nullptr;
}
auto host_cls = type_class(builtin->get_class());
if (!host_cls) {
return nullptr;
}
DexTypeList* arg_signature =
DexTypeList::make_type_list({type::java_lang_Object(), type::_int()});
const auto proto = DexProto::make_proto(type::_void(), arg_signature);
MethodCreator method_creator(host_cls->get_type(),
DexString::make_string(wrapper_name),
proto,
ACC_PUBLIC | ACC_STATIC);
auto obj_arg = method_creator.get_local(0);
// If the wrapper is going to print the index of the param as a string, we
// will have to construct a string from the index with additional
// information as part of the wrapper method.
auto main_block = method_creator.get_main_block();
auto int_ind = method_creator.get_local(1);
auto str_type = DexType::get_type("Ljava/lang/String;");
auto str_builder_type = DexType::get_type("Ljava/lang/StringBuilder;");
if (!str_type || !str_builder_type) {
return nullptr;
}
auto to_str_method = DexMethod::get_method(
"Ljava/lang/Integer;.toString:(I)Ljava/lang/String;");
auto str_builder_init_method =
DexMethod::get_method("Ljava/lang/StringBuilder;.<init>:()V");
auto append_method = DexMethod::get_method(
"Ljava/lang/StringBuilder;.append:(Ljava/lang/"
"String;)Ljava/lang/StringBuilder;");
auto str_builder_to_str_method = DexMethod::get_method(
"Ljava/lang/StringBuilder;.toString:()Ljava/lang/String;");
if (!to_str_method || !append_method || !str_builder_to_str_method) {
return nullptr;
}
auto str_ind = method_creator.make_local(str_type);
auto str_builder = method_creator.make_local(str_builder_type);
auto str_const = method_creator.make_local(str_type);
auto str_res = method_creator.make_local(str_type);
// invoke-static {v3}, Ljava/lang/Integer;.toString:(I)Ljava/lang/String;
main_block->invoke(OPCODE_INVOKE_STATIC, to_str_method, {int_ind});
// move-result-object v3
main_block->move_result(str_ind, str_type);
// new-instance v1, Ljava/lang/StringBuilder;
main_block->new_instance(str_builder_type, str_builder);
// invoke-direct {v1}, Ljava/lang/StringBuilder;.<init>:()V
main_block->invoke(OPCODE_INVOKE_DIRECT, str_builder_init_method,
{str_builder});
// const-string v2, "param index = "
main_block->load_const(str_const,
DexString::make_string("param at index = "));
// invoke-virtual {v1, v2},
// Ljava/lang/StringBuilder;.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
main_block->invoke(OPCODE_INVOKE_VIRTUAL, append_method,
{str_builder, str_const});
// invoke-virtual {v1, v3},
// Ljava/lang/StringBuilder;.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
main_block->invoke(OPCODE_INVOKE_VIRTUAL, append_method,
{str_builder, str_ind});
// invoke-virtual {v1},
// Ljava/lang/StringBuilder;.toString:()Ljava/lang/String;
main_block->invoke(OPCODE_INVOKE_VIRTUAL, str_builder_to_str_method,
{str_builder});
// move-result-object v3
main_block->move_result(str_res, str_type);
main_block->invoke(OPCODE_INVOKE_STATIC, builtin, {obj_arg, str_res});
main_block->ret_void();
auto new_method = method_creator.create();
TRACE(NULLCHECK, 5, "Created Method : %s", SHOW(new_method->get_code()));
host_cls->add_method(new_method);
return new_method;
}
RemoveNullcheckStringArg::Stats RemoveNullcheckStringArg::change_in_cfg(
cfg::ControlFlowGraph& cfg,
const TransferMap& transfer_map,
bool is_virtual) {
Stats stats{};
cfg::CFGMutation m(cfg);
auto params = cfg.get_param_instructions();
std::unordered_map<size_t, uint32_t> param_index;
uint32_t arg_index = is_virtual ? -1 : 0;
reaching_defs::MoveAwareFixpointIterator reaching_defs_iter(cfg);
reaching_defs_iter.run({});
for (const auto& mie : InstructionIterable(params)) {
auto load_insn = mie.insn;
always_assert(opcode::is_a_load_param(load_insn->opcode()));
param_index.insert(std::make_pair(load_insn->dest(), arg_index++));
}
for (cfg::Block* block : cfg.blocks()) {
auto env = reaching_defs_iter.get_entry_state_at(block);
if (env.is_bottom()) {
continue;
}
auto ii = InstructionIterable(block);
for (auto it = ii.begin(); it != ii.end();
reaching_defs_iter.analyze_instruction(it++->insn, &env)) {
auto insn = it->insn;
if (insn->opcode() != OPCODE_INVOKE_STATIC) {
continue;
}
auto iter = transfer_map.find(insn->get_method());
if (iter == transfer_map.end()) {
continue;
}
IRInstruction* new_insn = new IRInstruction(OPCODE_INVOKE_STATIC);
if (iter->second.second) {
// We could have params copied via intermediate registers.
auto defs = env.get(insn->src(0));
always_assert(!defs.is_bottom() && !defs.is_top());
always_assert(defs.elements().size() == 1);
auto def = *defs.elements().begin();
auto def_op = def->opcode();
always_assert(def_op == IOPCODE_LOAD_PARAM ||
def_op == IOPCODE_LOAD_PARAM_OBJECT ||
def_op == IOPCODE_LOAD_PARAM_OBJECT);
auto param_iter = param_index.find(def->dest());
always_assert(param_iter != param_index.end());
auto index = param_iter->second;
auto tmp_reg = cfg.allocate_temp();
IRInstruction* cst_insn = new IRInstruction(OPCODE_CONST);
cst_insn->set_literal(index)->set_dest(tmp_reg);
new_insn->set_method(iter->second.first)
->set_srcs_size(2)
->set_src(0, insn->src(0))
->set_src(1, tmp_reg);
m.replace(cfg.find_insn(insn), {cst_insn, new_insn});
} else {
new_insn->set_method(iter->second.first)
->set_srcs_size(1)
->set_src(0, insn->src(0));
m.replace(cfg.find_insn(insn), {new_insn});
}
stats.null_check_insns_changed++;
}
}
m.flush();
return stats;
}
void RemoveNullcheckStringArg::Stats::report(PassManager& mgr) const {
mgr.incr_metric("null_check_insns_changed", null_check_insns_changed);
TRACE(NULLCHECK, 2, "RemoveNullcheckStringArgPass Stats:");
TRACE(NULLCHECK,
2,
"RemoveNullcheckStringArgPass insns changed = %u",
null_check_insns_changed);
}
// Computes set of uninstantiable types, also looking at the type system to
// find non-external (and non-native)...
static RemoveNullcheckStringArg s_pass;
<commit_msg>Guard with check to null in wrapper<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "RemoveNullcheckStringArg.h"
#include "CFGMutation.h"
#include "Creators.h"
#include "DexClass.h"
#include "DexUtil.h"
#include "KotlinNullCheckMethods.h"
#include "PassManager.h"
#include "ReachingDefinitions.h"
#include "Show.h"
#include "Trace.h"
#include "Walkers.h"
using namespace kotlin_nullcheck_wrapper;
void RemoveNullcheckStringArg::run_pass(DexStoresVector& stores,
ConfigFiles& /*conf*/,
PassManager& mgr) {
TransferMap transfer_map;
std::unordered_set<DexMethod*> new_methods;
if (!setup(transfer_map, new_methods)) {
TRACE(NULLCHECK, 2, "RemoveNullcheckStringArgPass: setup failed");
return;
}
Scope scope = build_class_scope(stores);
Stats stats = walk::parallel::methods<Stats>(scope, [&](DexMethod* method) {
auto code = method->get_code();
if (method->rstate.no_optimizations() || code == nullptr ||
new_methods.count(method)) {
return Stats();
}
code->build_cfg();
auto local_stats =
change_in_cfg(code->cfg(), transfer_map, method->is_virtual());
code->clear_cfg();
return local_stats;
});
stats.report(mgr);
}
bool RemoveNullcheckStringArg::setup(
TransferMap& transfer_map, std::unordered_set<DexMethod*>& new_methods) {
bool is_param_check_V1_4 = false;
DexMethodRef* builtin_param =
DexMethod::get_method(CHECK_PARAM_NULL_SIGNATURE_V1_3);
if (!builtin_param) {
is_param_check_V1_4 = true;
builtin_param = DexMethod::get_method(CHECK_PARAM_NULL_SIGNATURE_V1_4);
}
/* If we didn't find the method, giveup. */
if (!builtin_param) {
return false;
}
bool is_expr_check_V1_4 = false;
DexMethodRef* builtin_expr =
DexMethod::get_method(CHECK_EXPR_NULL_SIGNATURE_V1_3);
if (!builtin_expr) {
is_expr_check_V1_4 = true;
builtin_expr = DexMethod::get_method(CHECK_EXPR_NULL_SIGNATURE_V1_4);
}
if (!builtin_expr) {
return false;
}
if (is_expr_check_V1_4 != is_param_check_V1_4) {
/* We have V1_3 and v1_4 mthods. */
TRACE(NULLCHECK, 1, "We have Kotlin 1.3 and 1.4 NULLCHECK assertions");
return false;
}
auto new_check_param_method = get_wrapper_method_with_int_index(
NEW_CHECK_PARAM_NULL_SIGNATURE, WRAPPER_CHECK_PARAM_NULL_METHOD,
builtin_param);
auto new_check_expr_method =
get_wrapper_method(NEW_CHECK_EXPR_NULL_SIGNATURE,
WRAPPER_CHECK_EXPR_NULL_METHOD, builtin_expr);
/* If we could not generate suitable wrapper method, giveup. */
if (!new_check_param_method || !new_check_expr_method) {
return false;
}
transfer_map[builtin_param] = std::make_pair(new_check_param_method, true);
transfer_map[builtin_expr] = std::make_pair(new_check_expr_method, false);
new_methods.insert(new_check_expr_method);
new_methods.insert(new_check_param_method);
return true;
}
DexMethod* RemoveNullcheckStringArg::get_wrapper_method(
const char* wrapper_signature,
const char* wrapper_name,
DexMethodRef* builtin) {
if (DexMethod::get_method(wrapper_signature)) {
/* Wrapper method already exist. */
return nullptr;
}
auto host_cls = type_class(builtin->get_class());
if (!host_cls) {
return nullptr;
}
DexTypeList* arg_signature =
DexTypeList::make_type_list({type::java_lang_Object()});
const auto proto = DexProto::make_proto(type::_void(), arg_signature);
MethodCreator method_creator(host_cls->get_type(),
DexString::make_string(wrapper_name),
proto,
ACC_PUBLIC | ACC_STATIC);
auto obj_arg = method_creator.get_local(0);
auto main_block = method_creator.get_main_block();
auto if_block = main_block->if_testz(OPCODE_IF_NEZ, obj_arg);
auto str_type = DexType::get_type("Ljava/lang/String;");
if (!str_type) {
return nullptr;
}
auto str_const = method_creator.make_local(str_type);
// const-string v2, "UNKNOWN"
if_block->load_const(str_const, DexString::make_string("UNKNOWN"));
if_block->invoke(OPCODE_INVOKE_STATIC, builtin, {obj_arg, str_const});
if_block->ret_void();
main_block->ret_void();
auto new_method = method_creator.create();
TRACE(NULLCHECK, 5, "Created Method : %s", SHOW(new_method->get_code()));
host_cls->add_method(new_method);
return new_method;
}
DexMethod* RemoveNullcheckStringArg::get_wrapper_method_with_int_index(
const char* wrapper_signature,
const char* wrapper_name,
DexMethodRef* builtin) {
if (DexMethod::get_method(wrapper_signature)) {
/* Wrapper method already exist. */
return nullptr;
}
auto host_cls = type_class(builtin->get_class());
if (!host_cls) {
return nullptr;
}
DexTypeList* arg_signature =
DexTypeList::make_type_list({type::java_lang_Object(), type::_int()});
const auto proto = DexProto::make_proto(type::_void(), arg_signature);
MethodCreator method_creator(host_cls->get_type(),
DexString::make_string(wrapper_name),
proto,
ACC_PUBLIC | ACC_STATIC);
auto obj_arg = method_creator.get_local(0);
// If the wrapper is going to print the index of the param as a string, we
// will have to construct a string from the index with additional
// information as part of the wrapper method.
auto main_block = method_creator.get_main_block();
auto int_ind = method_creator.get_local(1);
auto str_type = DexType::get_type("Ljava/lang/String;");
auto str_builder_type = DexType::get_type("Ljava/lang/StringBuilder;");
if (!str_type || !str_builder_type) {
return nullptr;
}
auto to_str_method = DexMethod::get_method(
"Ljava/lang/Integer;.toString:(I)Ljava/lang/String;");
auto str_builder_init_method =
DexMethod::get_method("Ljava/lang/StringBuilder;.<init>:()V");
auto append_method = DexMethod::get_method(
"Ljava/lang/StringBuilder;.append:(Ljava/lang/"
"String;)Ljava/lang/StringBuilder;");
auto str_builder_to_str_method = DexMethod::get_method(
"Ljava/lang/StringBuilder;.toString:()Ljava/lang/String;");
if (!to_str_method || !append_method || !str_builder_to_str_method) {
return nullptr;
}
auto str_ind = method_creator.make_local(str_type);
auto str_builder = method_creator.make_local(str_builder_type);
auto str_const = method_creator.make_local(str_type);
auto str_res = method_creator.make_local(str_type);
auto if_block = main_block->if_testz(OPCODE_IF_NEZ, obj_arg);
// invoke-static {v3}, Ljava/lang/Integer;.toString:(I)Ljava/lang/String;
if_block->invoke(OPCODE_INVOKE_STATIC, to_str_method, {int_ind});
// move-result-object v3
if_block->move_result(str_ind, str_type);
// new-instance v1, Ljava/lang/StringBuilder;
if_block->new_instance(str_builder_type, str_builder);
// invoke-direct {v1}, Ljava/lang/StringBuilder;.<init>:()V
if_block->invoke(OPCODE_INVOKE_DIRECT, str_builder_init_method,
{str_builder});
// const-string v2, "param index = "
if_block->load_const(str_const, DexString::make_string("param at index = "));
// invoke-virtual {v1, v2},
// Ljava/lang/StringBuilder;.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
if_block->invoke(OPCODE_INVOKE_VIRTUAL, append_method,
{str_builder, str_const});
// invoke-virtual {v1, v3},
// Ljava/lang/StringBuilder;.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
if_block->invoke(OPCODE_INVOKE_VIRTUAL, append_method,
{str_builder, str_ind});
// invoke-virtual {v1},
// Ljava/lang/StringBuilder;.toString:()Ljava/lang/String;
if_block->invoke(OPCODE_INVOKE_VIRTUAL, str_builder_to_str_method,
{str_builder});
// move-result-object v3
if_block->move_result(str_res, str_type);
if_block->invoke(OPCODE_INVOKE_STATIC, builtin, {obj_arg, str_res});
if_block->ret_void();
main_block->ret_void();
auto new_method = method_creator.create();
TRACE(NULLCHECK, 5, "Created Method : %s", SHOW(new_method->get_code()));
host_cls->add_method(new_method);
return new_method;
}
RemoveNullcheckStringArg::Stats RemoveNullcheckStringArg::change_in_cfg(
cfg::ControlFlowGraph& cfg,
const TransferMap& transfer_map,
bool is_virtual) {
Stats stats{};
cfg::CFGMutation m(cfg);
auto params = cfg.get_param_instructions();
std::unordered_map<size_t, uint32_t> param_index;
uint32_t arg_index = is_virtual ? -1 : 0;
reaching_defs::MoveAwareFixpointIterator reaching_defs_iter(cfg);
reaching_defs_iter.run({});
for (const auto& mie : InstructionIterable(params)) {
auto load_insn = mie.insn;
always_assert(opcode::is_a_load_param(load_insn->opcode()));
param_index.insert(std::make_pair(load_insn->dest(), arg_index++));
}
for (cfg::Block* block : cfg.blocks()) {
auto env = reaching_defs_iter.get_entry_state_at(block);
if (env.is_bottom()) {
continue;
}
auto ii = InstructionIterable(block);
for (auto it = ii.begin(); it != ii.end();
reaching_defs_iter.analyze_instruction(it++->insn, &env)) {
auto insn = it->insn;
if (insn->opcode() != OPCODE_INVOKE_STATIC) {
continue;
}
auto iter = transfer_map.find(insn->get_method());
if (iter == transfer_map.end()) {
continue;
}
IRInstruction* new_insn = new IRInstruction(OPCODE_INVOKE_STATIC);
if (iter->second.second) {
// We could have params copied via intermediate registers.
auto defs = env.get(insn->src(0));
always_assert(!defs.is_bottom() && !defs.is_top());
always_assert(defs.elements().size() == 1);
auto def = *defs.elements().begin();
auto def_op = def->opcode();
always_assert(def_op == IOPCODE_LOAD_PARAM ||
def_op == IOPCODE_LOAD_PARAM_OBJECT ||
def_op == IOPCODE_LOAD_PARAM_OBJECT);
auto param_iter = param_index.find(def->dest());
always_assert(param_iter != param_index.end());
auto index = param_iter->second;
auto tmp_reg = cfg.allocate_temp();
IRInstruction* cst_insn = new IRInstruction(OPCODE_CONST);
cst_insn->set_literal(index)->set_dest(tmp_reg);
new_insn->set_method(iter->second.first)
->set_srcs_size(2)
->set_src(0, insn->src(0))
->set_src(1, tmp_reg);
m.replace(cfg.find_insn(insn), {cst_insn, new_insn});
} else {
new_insn->set_method(iter->second.first)
->set_srcs_size(1)
->set_src(0, insn->src(0));
m.replace(cfg.find_insn(insn), {new_insn});
}
stats.null_check_insns_changed++;
}
}
m.flush();
return stats;
}
void RemoveNullcheckStringArg::Stats::report(PassManager& mgr) const {
mgr.incr_metric("null_check_insns_changed", null_check_insns_changed);
TRACE(NULLCHECK, 2, "RemoveNullcheckStringArgPass Stats:");
TRACE(NULLCHECK,
2,
"RemoveNullcheckStringArgPass insns changed = %u",
null_check_insns_changed);
}
// Computes set of uninstantiable types, also looking at the type system to
// find non-external (and non-native)...
static RemoveNullcheckStringArg s_pass;
<|endoftext|> |
<commit_before>/*
* nghttp2 - HTTP/2.0 C Library
*
* Copyright (c) 2013 Tatsuhiro Tsujikawa
*
* 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 "shrpx_ssl_test.h"
#include <CUnit/CUnit.h>
#include "shrpx_ssl.h"
namespace shrpx {
void test_shrpx_ssl_create_lookup_tree(void)
{
ssl::CertLookupTree* tree = ssl::cert_lookup_tree_new();
SSL_CTX *ctxs[] = {SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method())};
const char *hostnames[] = { "example.com",
"www.example.org",
"*www.example.org",
"x*.host.domain",
"*yy.host.domain",
"nghttp2.sourceforge.net",
"sourceforge.net",
"sourceforge.net", // duplicate
"*.foo.bar", // oo.bar is suffix of *.foo.bar
"oo.bar"
};
int num = sizeof(ctxs)/sizeof(ctxs[0]);
for(int i = 0; i < num; ++i) {
ssl::cert_lookup_tree_add_cert(tree, ctxs[i], hostnames[i],
strlen(hostnames[i]));
}
CU_ASSERT(ctxs[0] == ssl::cert_lookup_tree_lookup(tree, hostnames[0],
strlen(hostnames[0])));
CU_ASSERT(ctxs[1] == ssl::cert_lookup_tree_lookup(tree, hostnames[1],
strlen(hostnames[1])));
const char h1[] = "2www.example.org";
CU_ASSERT(ctxs[2] == ssl::cert_lookup_tree_lookup(tree, h1, strlen(h1)));
const char h2[] = "www2.example.org";
CU_ASSERT(0 == ssl::cert_lookup_tree_lookup(tree, h2, strlen(h2)));
const char h3[] = "x1.host.domain";
CU_ASSERT(ctxs[3] == ssl::cert_lookup_tree_lookup(tree, h3, strlen(h3)));
// Does not match *yy.host.domain, because * must match at least 1
// character.
const char h4[] = "yy.Host.domain";
CU_ASSERT(0 == ssl::cert_lookup_tree_lookup(tree, h4, strlen(h4)));
const char h5[] = "zyy.host.domain";
CU_ASSERT(ctxs[4] == ssl::cert_lookup_tree_lookup(tree, h5, strlen(h5)));
CU_ASSERT(0 == ssl::cert_lookup_tree_lookup(tree, "", 0));
CU_ASSERT(ctxs[5] == ssl::cert_lookup_tree_lookup(tree, hostnames[5],
strlen(hostnames[5])));
CU_ASSERT(ctxs[6] == ssl::cert_lookup_tree_lookup(tree, hostnames[6],
strlen(hostnames[6])));
const char h6[] = "pdylay.sourceforge.net";
for(int i = 0; i < 7; ++i) {
CU_ASSERT(0 == ssl::cert_lookup_tree_lookup(tree, h6 + i, strlen(h6) - i));
}
const char h7[] = "x.foo.bar";
CU_ASSERT(ctxs[8] == ssl::cert_lookup_tree_lookup(tree, h7, strlen(h7)));
CU_ASSERT(ctxs[9] == ssl::cert_lookup_tree_lookup(tree, hostnames[9],
strlen(hostnames[9])));
ssl::cert_lookup_tree_del(tree);
for(int i = 0; i < num; ++i) {
SSL_CTX_free(ctxs[i]);
}
SSL_CTX *ctxs2[] = {SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method()),
SSL_CTX_new(TLSv1_method())};
const char *names[] = { "rab", "zab", "zzub", "ab" };
num = sizeof(ctxs2)/sizeof(ctxs2[0]);
tree = ssl::cert_lookup_tree_new();
for(int i = 0; i < num; ++i) {
ssl::cert_lookup_tree_add_cert(tree, ctxs2[i], names[i], strlen(names[i]));
}
for(int i = 0; i < num; ++i) {
CU_ASSERT(ctxs2[i] == ssl::cert_lookup_tree_lookup(tree, names[i],
strlen(names[i])));
}
ssl::cert_lookup_tree_del(tree);
for(int i = 0; i < num; ++i) {
SSL_CTX_free(ctxs2[i]);
}
}
void test_shrpx_ssl_cert_lookup_tree_add_cert_from_file(void)
{
int rv;
ssl::CertLookupTree* tree = ssl::cert_lookup_tree_new();
SSL_CTX *ssl_ctx = SSL_CTX_new(TLSv1_method());
const char certfile[] = NGHTTP2_TESTS_DIR"/testdata/cacert.pem";
rv = ssl::cert_lookup_tree_add_cert_from_file(tree, ssl_ctx, certfile);
CU_ASSERT(0 == rv);
const char localhost[] = "localhost";
CU_ASSERT(ssl_ctx == ssl::cert_lookup_tree_lookup(tree, localhost,
sizeof(localhost)-1));
ssl::cert_lookup_tree_del(tree);
SSL_CTX_free(ssl_ctx);
}
} // namespace shrpx
<commit_msg>src: Use SSLv23_method for tests<commit_after>/*
* nghttp2 - HTTP/2.0 C Library
*
* Copyright (c) 2013 Tatsuhiro Tsujikawa
*
* 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 "shrpx_ssl_test.h"
#include <CUnit/CUnit.h>
#include "shrpx_ssl.h"
namespace shrpx {
void test_shrpx_ssl_create_lookup_tree(void)
{
ssl::CertLookupTree* tree = ssl::cert_lookup_tree_new();
SSL_CTX *ctxs[] = {SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method())};
const char *hostnames[] = { "example.com",
"www.example.org",
"*www.example.org",
"x*.host.domain",
"*yy.host.domain",
"nghttp2.sourceforge.net",
"sourceforge.net",
"sourceforge.net", // duplicate
"*.foo.bar", // oo.bar is suffix of *.foo.bar
"oo.bar"
};
int num = sizeof(ctxs)/sizeof(ctxs[0]);
for(int i = 0; i < num; ++i) {
ssl::cert_lookup_tree_add_cert(tree, ctxs[i], hostnames[i],
strlen(hostnames[i]));
}
CU_ASSERT(ctxs[0] == ssl::cert_lookup_tree_lookup(tree, hostnames[0],
strlen(hostnames[0])));
CU_ASSERT(ctxs[1] == ssl::cert_lookup_tree_lookup(tree, hostnames[1],
strlen(hostnames[1])));
const char h1[] = "2www.example.org";
CU_ASSERT(ctxs[2] == ssl::cert_lookup_tree_lookup(tree, h1, strlen(h1)));
const char h2[] = "www2.example.org";
CU_ASSERT(0 == ssl::cert_lookup_tree_lookup(tree, h2, strlen(h2)));
const char h3[] = "x1.host.domain";
CU_ASSERT(ctxs[3] == ssl::cert_lookup_tree_lookup(tree, h3, strlen(h3)));
// Does not match *yy.host.domain, because * must match at least 1
// character.
const char h4[] = "yy.Host.domain";
CU_ASSERT(0 == ssl::cert_lookup_tree_lookup(tree, h4, strlen(h4)));
const char h5[] = "zyy.host.domain";
CU_ASSERT(ctxs[4] == ssl::cert_lookup_tree_lookup(tree, h5, strlen(h5)));
CU_ASSERT(0 == ssl::cert_lookup_tree_lookup(tree, "", 0));
CU_ASSERT(ctxs[5] == ssl::cert_lookup_tree_lookup(tree, hostnames[5],
strlen(hostnames[5])));
CU_ASSERT(ctxs[6] == ssl::cert_lookup_tree_lookup(tree, hostnames[6],
strlen(hostnames[6])));
const char h6[] = "pdylay.sourceforge.net";
for(int i = 0; i < 7; ++i) {
CU_ASSERT(0 == ssl::cert_lookup_tree_lookup(tree, h6 + i, strlen(h6) - i));
}
const char h7[] = "x.foo.bar";
CU_ASSERT(ctxs[8] == ssl::cert_lookup_tree_lookup(tree, h7, strlen(h7)));
CU_ASSERT(ctxs[9] == ssl::cert_lookup_tree_lookup(tree, hostnames[9],
strlen(hostnames[9])));
ssl::cert_lookup_tree_del(tree);
for(int i = 0; i < num; ++i) {
SSL_CTX_free(ctxs[i]);
}
SSL_CTX *ctxs2[] = {SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method()),
SSL_CTX_new(SSLv23_method())};
const char *names[] = { "rab", "zab", "zzub", "ab" };
num = sizeof(ctxs2)/sizeof(ctxs2[0]);
tree = ssl::cert_lookup_tree_new();
for(int i = 0; i < num; ++i) {
ssl::cert_lookup_tree_add_cert(tree, ctxs2[i], names[i], strlen(names[i]));
}
for(int i = 0; i < num; ++i) {
CU_ASSERT(ctxs2[i] == ssl::cert_lookup_tree_lookup(tree, names[i],
strlen(names[i])));
}
ssl::cert_lookup_tree_del(tree);
for(int i = 0; i < num; ++i) {
SSL_CTX_free(ctxs2[i]);
}
}
void test_shrpx_ssl_cert_lookup_tree_add_cert_from_file(void)
{
int rv;
ssl::CertLookupTree* tree = ssl::cert_lookup_tree_new();
SSL_CTX *ssl_ctx = SSL_CTX_new(SSLv23_method());
const char certfile[] = NGHTTP2_TESTS_DIR"/testdata/cacert.pem";
rv = ssl::cert_lookup_tree_add_cert_from_file(tree, ssl_ctx, certfile);
CU_ASSERT(0 == rv);
const char localhost[] = "localhost";
CU_ASSERT(ssl_ctx == ssl::cert_lookup_tree_lookup(tree, localhost,
sizeof(localhost)-1));
ssl::cert_lookup_tree_del(tree);
SSL_CTX_free(ssl_ctx);
}
} // namespace shrpx
<|endoftext|> |
<commit_before>#include "net/resolve.h"
#include "base/logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#ifdef _WIN32
#include <WinSock2.h>
#include <Ws2tcpip.h>
#undef min
#undef max
#else
#if defined(__FreeBSD__) || defined(__SYMBIAN32__)
#include <netinet/in.h>
#else
#include <arpa/inet.h>
#endif
#include <netdb.h>
#include <sys/socket.h>
#endif
namespace net {
void Init()
{
#ifdef _WIN32
// WSA does its own internal reference counting, no need to keep track of if we inited or not.
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
}
void Shutdown()
{
#ifdef _WIN32
WSACleanup();
#endif
}
char *DNSResolveTry(const char *host, const char **err)
{
struct hostent *hent;
if((hent = gethostbyname(host)) == NULL)
{
*err = "Can't get IP";
return NULL;
}
int iplen = 15; //XXX.XXX.XXX.XXX
char *ip = (char *)malloc(iplen+1);
memset(ip, 0, iplen+1);
char *iptoa = inet_ntoa(*(in_addr *)hent->h_addr_list[0]);
if (iptoa == NULL)
{
*err = "Can't resolve host";
free(ip);
return NULL;
}
strncpy(ip, iptoa, iplen);
return ip;
}
char *DNSResolve(const char *host)
{
const char *err;
char *ip = DNSResolveTry(host, &err);
if (ip == NULL)
{
perror(err);
exit(1);
}
return ip;
}
bool DNSResolve(const std::string &host, const std::string &service, addrinfo **res, std::string &error)
{
addrinfo hints = {0};
// TODO: Might be uses to lookup other values.
hints.ai_socktype = SOCK_STREAM;
#ifdef BLACKBERRY
hints.ai_flags = 0;
#else
hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
#endif
hints.ai_protocol = IPPROTO_TCP;
const char *servicep = service.length() == 0 ? NULL : service.c_str();
*res = NULL;
int result = getaddrinfo(host.c_str(), servicep, &hints, res);
if (result == EAI_AGAIN)
{
// Temporary failure. Since this already blocks, let's just try once more.
#ifdef _WIN32
Sleep(1);
#else
sleep(1);
#endif
result = getaddrinfo(host.c_str(), servicep, &hints, res);
}
if (result != 0)
{
error = gai_strerror(result);
if (*res != NULL)
freeaddrinfo(*res);
*res = NULL;
return false;
}
return true;
}
void DNSResolveFree(addrinfo *res)
{
freeaddrinfo(res);
}
int inet_pton(int af, const char* src, void* dst)
{
if (af == AF_INET)
{
unsigned char *ip = (unsigned char *)dst;
int k = 0, x = 0;
char ch;
for (int i = 0; (ch = src[i]) != 0; i++)
{
if (ch == '.')
{
ip[k++] = x;
if (k == 4)
return 0;
x = 0;
}
else if (ch < '0' || ch > '9')
return 0;
else
x = x * 10 + ch - '0';
if (x > 255)
return 0;
}
ip[k++] = x;
if (k != 4)
return 0;
}
else if (af == AF_INET6)
{
unsigned short* ip = ( unsigned short* )dst;
int i;
for (i = 0; i < 8; i++) ip[i] = 0;
int k = 0;
unsigned int x = 0;
char ch;
int marknum = 0;
for (i = 0; src[i] != 0; i++)
{
if (src[i] == ':')
marknum++;
}
for (i = 0; (ch = src[i]) != 0; i++)
{
if (ch == ':')
{
x = ((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8);
ip[k++] = x;
if (k == 8)
return 0;
x = 0;
if (i > 0 && src[i - 1] == ':')
k += 7 - marknum;
}
else if (ch >= '0' && ch <= '9')
x = x * 16 + ch - '0';
else if (ch >= 'a' && ch <= 'f')
x = x * 16 + ch - 'a' + 10;
else if (ch >= 'A' && ch <= 'F')
x = x * 16 + ch - 'A' + 10;
else
return 0;
if (x > 0xFFFF)
return 0;
}
x = ((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8);
ip[k++] = x;
if (k != 8)
return 0;
}
return 1;
}
}
<commit_msg>Buildfix for Symbian, Linux.<commit_after>#include "net/resolve.h"
#include "base/logging.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#ifdef _WIN32
#include <WinSock2.h>
#include <Ws2tcpip.h>
#undef min
#undef max
#else
#if defined(__FreeBSD__) || defined(__SYMBIAN32__)
#include <netinet/in.h>
#else
#include <arpa/inet.h>
#endif
#include <netdb.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
namespace net {
void Init()
{
#ifdef _WIN32
// WSA does its own internal reference counting, no need to keep track of if we inited or not.
WSADATA wsaData = {0};
WSAStartup(MAKEWORD(2, 2), &wsaData);
#endif
}
void Shutdown()
{
#ifdef _WIN32
WSACleanup();
#endif
}
char *DNSResolveTry(const char *host, const char **err)
{
struct hostent *hent;
if((hent = gethostbyname(host)) == NULL)
{
*err = "Can't get IP";
return NULL;
}
int iplen = 15; //XXX.XXX.XXX.XXX
char *ip = (char *)malloc(iplen+1);
memset(ip, 0, iplen+1);
char *iptoa = inet_ntoa(*(in_addr *)hent->h_addr_list[0]);
if (iptoa == NULL)
{
*err = "Can't resolve host";
free(ip);
return NULL;
}
strncpy(ip, iptoa, iplen);
return ip;
}
char *DNSResolve(const char *host)
{
const char *err;
char *ip = DNSResolveTry(host, &err);
if (ip == NULL)
{
perror(err);
exit(1);
}
return ip;
}
bool DNSResolve(const std::string &host, const std::string &service, addrinfo **res, std::string &error)
{
addrinfo hints = {0};
// TODO: Might be uses to lookup other values.
hints.ai_socktype = SOCK_STREAM;
#ifdef BLACKBERRY
hints.ai_flags = 0;
#else
hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
#endif
hints.ai_protocol = IPPROTO_TCP;
const char *servicep = service.length() == 0 ? NULL : service.c_str();
*res = NULL;
int result = getaddrinfo(host.c_str(), servicep, &hints, res);
if (result == EAI_AGAIN)
{
// Temporary failure. Since this already blocks, let's just try once more.
#ifdef _WIN32
Sleep(1);
#else
sleep(1);
#endif
result = getaddrinfo(host.c_str(), servicep, &hints, res);
}
if (result != 0)
{
error = gai_strerror(result);
if (*res != NULL)
freeaddrinfo(*res);
*res = NULL;
return false;
}
return true;
}
void DNSResolveFree(addrinfo *res)
{
freeaddrinfo(res);
}
int inet_pton(int af, const char* src, void* dst)
{
if (af == AF_INET)
{
unsigned char *ip = (unsigned char *)dst;
int k = 0, x = 0;
char ch;
for (int i = 0; (ch = src[i]) != 0; i++)
{
if (ch == '.')
{
ip[k++] = x;
if (k == 4)
return 0;
x = 0;
}
else if (ch < '0' || ch > '9')
return 0;
else
x = x * 10 + ch - '0';
if (x > 255)
return 0;
}
ip[k++] = x;
if (k != 4)
return 0;
}
else if (af == AF_INET6)
{
unsigned short* ip = ( unsigned short* )dst;
int i;
for (i = 0; i < 8; i++) ip[i] = 0;
int k = 0;
unsigned int x = 0;
char ch;
int marknum = 0;
for (i = 0; src[i] != 0; i++)
{
if (src[i] == ':')
marknum++;
}
for (i = 0; (ch = src[i]) != 0; i++)
{
if (ch == ':')
{
x = ((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8);
ip[k++] = x;
if (k == 8)
return 0;
x = 0;
if (i > 0 && src[i - 1] == ':')
k += 7 - marknum;
}
else if (ch >= '0' && ch <= '9')
x = x * 16 + ch - '0';
else if (ch >= 'a' && ch <= 'f')
x = x * 16 + ch - 'a' + 10;
else if (ch >= 'A' && ch <= 'F')
x = x * 16 + ch - 'A' + 10;
else
return 0;
if (x > 0xFFFF)
return 0;
}
x = ((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8);
ip[k++] = x;
if (k != 8)
return 0;
}
return 1;
}
}
<|endoftext|> |
<commit_before>#include "lw/memory/buffer.h"
#include <cstring>
#include "lw/err/macros.h"
namespace lw {
void Buffer::_xor(const Buffer& lhs, const Buffer& rhs, Buffer* out) {
LW_CHECK_NULL(out);
for (std::size_t i = 0; i < out->size(); ++i) {
out->_data[i] = lhs._data[i] ^ rhs._data[i];
}
}
Buffer& Buffer::operator=(Buffer&& other) {
// If own our current data, delete it first.
if (_own_data && _data) {
delete[] _data;
}
// Copy the information over.
_data = other._data;
_capacity = other._capacity;
_own_data = other._own_data;
// Remove ownership of the buffer from the other one.
other._own_data = false;
// Return self.
return *this;
}
void Buffer::set_memory(std::uint8_t val) {
std::memset(_data, val, _capacity);
}
bool Buffer::operator==(const Buffer& other) const {
if (size() != other.size()) {
return false;
}
if (data() == other.data()) {
return true;
}
return std::memcmp(data(), other.data(), size()) == 0;
}
Buffer& Buffer::operator^=(const Buffer& other) {
// Stupid Windows defines a "min" macro that conflicts with std::min.
using namespace std;
Buffer tmp(_data, min(this->size(), other.size()), false);
_xor(*this, other, &tmp);
return *this;
}
std::uint8_t& Buffer::front() {
LW_CHECK_NULL(_data) << "Buffer does not contain any data.";
return *_data;
}
const std::uint8_t& Buffer::front() const {
LW_CHECK_NULL(_data) << "Buffer does not contain any data.";
return *_data;
}
std::uint8_t& Buffer::back() {
LW_CHECK_NULL(_data) << "Buffer does not contain any data.";
return *(_capacity ? _data + _capacity - 1 : _data);
}
const std::uint8_t& Buffer::back() const {
LW_CHECK_NULL(_data) << "Buffer does not contain any data.";
return *(_capacity ? _data + _capacity - 1 : _data);
}
Buffer Buffer::trim_prefix(std::size_t n) const {
if (n >= _capacity) {
throw InvalidArgument()
<< "Cannot trim " << n << " bytes from buffer with " << _capacity
<< " bytes.";
}
return Buffer{_data + n, _capacity - n};
}
Buffer Buffer::trim_suffix(std::size_t n) const {
if (n >= _capacity) {
throw InvalidArgument()
<< "Cannot trim " << n << " bytes from buffer with " << _capacity
<< " bytes.";
}
return Buffer{_data, _capacity - n};
}
}
<commit_msg>Allow trimming to 0 bytes.<commit_after>#include "lw/memory/buffer.h"
#include <cstring>
#include "lw/err/macros.h"
namespace lw {
void Buffer::_xor(const Buffer& lhs, const Buffer& rhs, Buffer* out) {
LW_CHECK_NULL(out);
for (std::size_t i = 0; i < out->size(); ++i) {
out->_data[i] = lhs._data[i] ^ rhs._data[i];
}
}
Buffer& Buffer::operator=(Buffer&& other) {
// If own our current data, delete it first.
if (_own_data && _data) {
delete[] _data;
}
// Copy the information over.
_data = other._data;
_capacity = other._capacity;
_own_data = other._own_data;
// Remove ownership of the buffer from the other one.
other._own_data = false;
// Return self.
return *this;
}
void Buffer::set_memory(std::uint8_t val) {
std::memset(_data, val, _capacity);
}
bool Buffer::operator==(const Buffer& other) const {
if (size() != other.size()) {
return false;
}
if (data() == other.data()) {
return true;
}
return std::memcmp(data(), other.data(), size()) == 0;
}
Buffer& Buffer::operator^=(const Buffer& other) {
// Stupid Windows defines a "min" macro that conflicts with std::min.
using namespace std;
Buffer tmp(_data, min(this->size(), other.size()), false);
_xor(*this, other, &tmp);
return *this;
}
std::uint8_t& Buffer::front() {
LW_CHECK_NULL(_data) << "Buffer does not contain any data.";
return *_data;
}
const std::uint8_t& Buffer::front() const {
LW_CHECK_NULL(_data) << "Buffer does not contain any data.";
return *_data;
}
std::uint8_t& Buffer::back() {
LW_CHECK_NULL(_data) << "Buffer does not contain any data.";
return *(_capacity ? _data + _capacity - 1 : _data);
}
const std::uint8_t& Buffer::back() const {
LW_CHECK_NULL(_data) << "Buffer does not contain any data.";
return *(_capacity ? _data + _capacity - 1 : _data);
}
Buffer Buffer::trim_prefix(std::size_t n) const {
if (n > _capacity) {
throw InvalidArgument()
<< "Cannot trim " << n << " bytes from buffer with " << _capacity
<< " bytes.";
}
return Buffer{_data + n, _capacity - n};
}
Buffer Buffer::trim_suffix(std::size_t n) const {
if (n > _capacity) {
throw InvalidArgument()
<< "Cannot trim " << n << " bytes from buffer with " << _capacity
<< " bytes.";
}
return Buffer{_data, _capacity - n};
}
}
<|endoftext|> |
<commit_before>/** @file
*
* @ingroup dspSoundFileLib
*
* @brief Tests for the #TTSoundfileLoader class
*
* @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n
* IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class.
*
* @authors Nathan Wolek
*
* @copyright Copyright © 2013 by Nathan Wolek @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTSoundfileLoader.h"
#include "TTUnitTest.h"
#include "TTBuffer.h"
/*
It is possible to change the target sound file for this test using the macros below.
Both sound files are included in the Jamoma respository at the following path:
{JAMOMA_ROOT}/Core/DSP/extensions/SoundfileLib/
The test should look for the named TESTFILE at this path.
*/
/* */
#define TESTFILE "geese_clip.aif"
#define TESTNUMCHANNELS 2
#define TESTSAMPLERATE 44100
#define TESTDURATIONINSAMPLES 88202
#define TESTDURATIONINSECONDS 2.00004535
#define TESTTITLE ""
#define TESTARTIST ""
#define TESTDATE ""
#define TESTANNOTATION ""
/* */
/*
#define TESTFILE "ding_b2.aiff"
#define TESTNUMCHANNELS 1
#define TESTSAMPLERATE 44100
#define TESTDURATIONINSAMPLES 39493
#define TESTDURATIONINSECONDS 0.89553288
#define TESTTITLE ""
#define TESTARTIST ""
#define TESTDATE ""
#define TESTANNOTATION ""
*/
TTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
// assemble the full path of the target sound file
TTString testSoundPath = TTFoundationBinaryPath;
int pos = testSoundPath.find_last_of('/');
testSoundPath = testSoundPath.substr(0,pos+1);
testSoundPath += TESTFILE;
std::cout << "We will be using the following path for testing: " << testSoundPath << "\n";
try {
TTTestLog("\n");
TTTestLog("Testing TTSoundfileLoader Basics...");
// TEST 0: establish our objects & pointers
TTObject* testTargetMatrix = new TTObject("samplematrix");
TTObject* testNonSampleMatrix = new TTObject("delay");
TTObjectBase* objectBasePtrToSampleMatrix;
TTObjectBase* ptrToNonSampleMatrix;
// TEST 1: set the filepath
TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone };
TTTestAssertion("setFilePath operates successfully",
result1,
testAssertionCount,
errorCount);
// TEST 2: set up the samplematrix first
int channelsSend = 1; // compiler complained about TTInt32 being ambiguous here
int lengthSend = 22050; // compiler complained about TTInt32 being ambiguous here
testTargetMatrix->set("numChannels", channelsSend);
testTargetMatrix->set("lengthInSamples", lengthSend);
TTInt32 channelsReturn, lengthReturn;
testTargetMatrix->get("numChannels", channelsReturn);
testTargetMatrix->get("lengthInSamples", lengthReturn);
// now for the actual test
TTBoolean result2a = { channelsSend == channelsReturn };
TTTestAssertion("numChannels attribute set successfully",
result2a,
testAssertionCount,
errorCount);
TTBoolean result2b = { lengthSend == lengthReturn };
TTTestAssertion("lengthInSamples attribute set successfully",
result2b,
testAssertionCount,
errorCount);
//
// TEST 3: set the target via an objectBasePtr
objectBasePtrToSampleMatrix = testTargetMatrix->instance(); // is there a better syntax for this?
TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };
TTTestAssertion("setTargetMatrix via ObjectBasePtr operates successfully",
result3,
testAssertionCount,
errorCount);
// TEST 4: set the target to a non-SampleMatrix, should FAIL
ptrToNonSampleMatrix = testNonSampleMatrix->instance();
TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };
TTTestAssertion("setTargetMatrix returns error when not a SampleMatrix",
result4,
testAssertionCount,
errorCount);
// TEST 5: copy samplevalues until samplematrix is filled
TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone };
TTTestAssertion("copyUntilFilled operates successfully",
result5,
testAssertionCount,
errorCount);
// TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence
// create a new TTSampleMatrix
TTObject newTargetMatrix("samplematrix");
// set the length and channel count
newTargetMatrix.set("numChannels", TESTNUMCHANNELS);
newTargetMatrix.set("lengthInSamples", TESTDURATIONINSAMPLES);
// prepare necessary TTValues
TTValue loadInput6 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue
TTValue aReturnWeDontCareAbout6;
// send message
TTBoolean result6a = { newTargetMatrix.send("load", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone };
TTTestAssertion("TTSampleMatrix load operates successfully",
result6a,
testAssertionCount,
errorCount);
// now let's test some values!
int randomIndex6;
TTSampleValue randomValueSoundFile6;
TTBoolean result6 = true;
for (int i = 0; i<5; i++)
{
randomIndex6 = lengthReturn * TTRandom64();
std::cout << "let's look at index " << randomIndex6 << "\n";
TTValue peekInput6(randomIndex6);
peekInput6.append(0);
TTValue peekOutput6;
this->peek(randomIndex6,0,randomValueSoundFile6);
newTargetMatrix.send("peek",peekInput6,peekOutput6);
std::cout << "Does " << randomValueSoundFile6 << " = " << double(peekOutput6) << " ?\n";
if (result6) // allows test to keep variable false once it is false
result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001);
}
TTTestAssertion("comparing 5 random values for equivalence",
result6,
testAssertionCount,
errorCount);
//
// TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence
// create a new TTBuffer
TTObject newTargetBuffer("buffer");
// set the length and channel count
newTargetBuffer.set("numChannels", TESTNUMCHANNELS);
newTargetBuffer.set("lengthInSamples", TESTDURATIONINSAMPLES);
// prepare necessary TTValues
TTValue loadInput7 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue
TTValue aSendWeDontCareAbout7, aReturnWeDontCareAbout7;
TTValue checkOutValue;
// send message
TTBoolean result7a = { newTargetBuffer.send("load", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone };
TTTestAssertion("TTBuffer load operates successfully",
result7a,
testAssertionCount,
errorCount);
// check out samplematrix
newTargetBuffer.send("checkOutMatrix",aSendWeDontCareAbout7,checkOutValue);
TTObjectBase* checkedOutMatrix = checkOutValue[0];
// now let's test some values!
int randomIndex7;
TTSampleValue randomValueSoundFile7;
TTBoolean result7 = true;
for (int i = 0; i<5; i++)
{
randomIndex7 = lengthReturn * TTRandom64();
std::cout << "let's look at index " << randomIndex7 << "\n";
TTValue peekInput7(randomIndex7);
peekInput7.append(0);
TTValue peekOutput7;
this->peek(randomIndex7,0,randomValueSoundFile7);
checkedOutMatrix->sendMessage("peek",peekInput7,peekOutput7);
std::cout << "Does " << randomValueSoundFile7 << " = " << double(peekOutput7) << " ?\n";
if (result7) // allows test to keep variable false once it is false
result7 = TTTestFloatEquivalence(randomValueSoundFile7, double(peekOutput7), true, 0.0000001);
}
TTTestAssertion("comparing 5 random values for equivalence",
result7,
testAssertionCount,
errorCount);
// check in samplematrix
TTBoolean result7c = { newTargetBuffer.send("checkInMatrix",checkOutValue,aReturnWeDontCareAbout7) == kTTErrNone };
TTTestAssertion("TTBuffer checks in SampleMatrix successfully",
result7c,
testAssertionCount,
errorCount);
// releasing objects
objectBasePtrToSampleMatrix = NULL;
ptrToNonSampleMatrix = NULL;
delete testTargetMatrix;
delete testNonSampleMatrix;
} catch (...) {
TTTestAssertion("FAILED to run tests -- likely that necessary objects did not instantiate",
0,
testAssertionCount,
errorCount);
}
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
<commit_msg>attempting to cast TTObject* to TTBuffer*, causes build to fail<commit_after>/** @file
*
* @ingroup dspSoundFileLib
*
* @brief Tests for the #TTSoundfileLoader class
*
* @details Tests the core functions of the TTSoundfileLoader class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n
* IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, this test will attempt to find the path to the SoundfileLib extension using the TTFoundationBinaryPath environment variable. If you wish to test with a different sound file, you will need to place in that extension folder and change the relevant macros in the header of this class.
*
* @authors Nathan Wolek
*
* @copyright Copyright © 2013 by Nathan Wolek @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTSoundfileLoader.h"
#include "TTUnitTest.h"
#include "TTBuffer.h"
/*
It is possible to change the target sound file for this test using the macros below.
Both sound files are included in the Jamoma respository at the following path:
{JAMOMA_ROOT}/Core/DSP/extensions/SoundfileLib/
The test should look for the named TESTFILE at this path.
*/
/* */
#define TESTFILE "geese_clip.aif"
#define TESTNUMCHANNELS 2
#define TESTSAMPLERATE 44100
#define TESTDURATIONINSAMPLES 88202
#define TESTDURATIONINSECONDS 2.00004535
#define TESTTITLE ""
#define TESTARTIST ""
#define TESTDATE ""
#define TESTANNOTATION ""
/* */
/*
#define TESTFILE "ding_b2.aiff"
#define TESTNUMCHANNELS 1
#define TESTSAMPLERATE 44100
#define TESTDURATIONINSAMPLES 39493
#define TESTDURATIONINSECONDS 0.89553288
#define TESTTITLE ""
#define TESTARTIST ""
#define TESTDATE ""
#define TESTANNOTATION ""
*/
TTErr TTSoundfileLoader::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
// assemble the full path of the target sound file
TTString testSoundPath = TTFoundationBinaryPath;
int pos = testSoundPath.find_last_of('/');
testSoundPath = testSoundPath.substr(0,pos+1);
testSoundPath += TESTFILE;
std::cout << "We will be using the following path for testing: " << testSoundPath << "\n";
try {
TTTestLog("\n");
TTTestLog("Testing TTSoundfileLoader Basics...");
// TEST 0: establish our objects & pointers
TTObject* testTargetMatrix = new TTObject("samplematrix");
TTObject* testNonSampleMatrix = new TTObject("delay");
TTObjectBase* objectBasePtrToSampleMatrix;
TTObjectBase* ptrToNonSampleMatrix;
// TEST 1: set the filepath
TTBoolean result1 = { this->setFilePath(TT(testSoundPath)) == kTTErrNone };
TTTestAssertion("setFilePath operates successfully",
result1,
testAssertionCount,
errorCount);
// TEST 2: set up the samplematrix first
int channelsSend = 1; // compiler complained about TTInt32 being ambiguous here
int lengthSend = 22050; // compiler complained about TTInt32 being ambiguous here
testTargetMatrix->set("numChannels", channelsSend);
testTargetMatrix->set("lengthInSamples", lengthSend);
TTInt32 channelsReturn, lengthReturn;
testTargetMatrix->get("numChannels", channelsReturn);
testTargetMatrix->get("lengthInSamples", lengthReturn);
// now for the actual test
TTBoolean result2a = { channelsSend == channelsReturn };
TTTestAssertion("numChannels attribute set successfully",
result2a,
testAssertionCount,
errorCount);
TTBoolean result2b = { lengthSend == lengthReturn };
TTTestAssertion("lengthInSamples attribute set successfully",
result2b,
testAssertionCount,
errorCount);
//
// TEST 3: set the target via an objectBasePtr
objectBasePtrToSampleMatrix = testTargetMatrix->instance(); // is there a better syntax for this?
TTBoolean result3 = { this->setTargetMatrix(objectBasePtrToSampleMatrix) == kTTErrNone };
TTTestAssertion("setTargetMatrix via ObjectBasePtr operates successfully",
result3,
testAssertionCount,
errorCount);
// TEST 4: set the target to a non-SampleMatrix, should FAIL
ptrToNonSampleMatrix = testNonSampleMatrix->instance();
TTBoolean result4 = { this->setTargetMatrix(ptrToNonSampleMatrix) == kTTErrInvalidValue };
TTTestAssertion("setTargetMatrix returns error when not a SampleMatrix",
result4,
testAssertionCount,
errorCount);
// TEST 5: copy samplevalues until samplematrix is filled
TTBoolean result5 = { this->copyUntilFilled() == kTTErrNone };
TTTestAssertion("copyUntilFilled operates successfully",
result5,
testAssertionCount,
errorCount);
// TEST 6: use TTSampleMatrix's load message, then compare 5 random sample values for equivalence
// create a new TTSampleMatrix
TTObject newTargetMatrix("samplematrix");
// set the length and channel count
newTargetMatrix.set("numChannels", TESTNUMCHANNELS);
newTargetMatrix.set("lengthInSamples", TESTDURATIONINSAMPLES);
// prepare necessary TTValues
TTValue loadInput6 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue
TTValue aReturnWeDontCareAbout6;
// send message
TTBoolean result6a = { newTargetMatrix.send("load", loadInput6, aReturnWeDontCareAbout6) == kTTErrNone };
TTTestAssertion("TTSampleMatrix load operates successfully",
result6a,
testAssertionCount,
errorCount);
// now let's test some values!
int randomIndex6;
TTSampleValue randomValueSoundFile6;
TTBoolean result6 = true;
for (int i = 0; i<5; i++)
{
randomIndex6 = lengthReturn * TTRandom64();
std::cout << "let's look at index " << randomIndex6 << "\n";
TTValue peekInput6(randomIndex6);
peekInput6.append(0);
TTValue peekOutput6;
this->peek(randomIndex6,0,randomValueSoundFile6);
newTargetMatrix.send("peek",peekInput6,peekOutput6);
std::cout << "Does " << randomValueSoundFile6 << " = " << double(peekOutput6) << " ?\n";
if (result6) // allows test to keep variable false once it is false
result6 = TTTestFloatEquivalence(randomValueSoundFile6, double(peekOutput6), true, 0.0000001);
}
TTTestAssertion("comparing 5 random values for equivalence",
result6,
testAssertionCount,
errorCount);
//
// TEST 7: now use TTBuffer's load message, and again compare 5 random sample values for equivalence
// create a new TTBuffer
TTObject newTargetBuffer("buffer");
// set the length and channel count
newTargetBuffer.set("numChannels", TESTNUMCHANNELS);
newTargetBuffer.set("lengthInSamples", TESTDURATIONINSAMPLES);
// create a new TTBuffer
TTBuffer* aBufferByAnotherName = (TTBuffer*)(new TTObject("buffer"));
// set the length and channel count
aBufferByAnotherName->setAttributeValue("numChannels", TESTNUMCHANNELS);
aBufferByAnotherName->setAttributeValue("lengthInSamples", TESTDURATIONINSAMPLES);
// prepare necessary TTValues
TTValue loadInput7 = TT(testSoundPath); // we cannot pass the naked TTString, it needs to be part of a TTValue
TTValue aSendWeDontCareAbout7, aReturnWeDontCareAbout7;
TTValue checkOutValue;
// send message
TTBoolean result7a = { newTargetBuffer.send("load", loadInput7, aReturnWeDontCareAbout7) == kTTErrNone };
TTTestAssertion("TTBuffer load operates successfully",
result7a,
testAssertionCount,
errorCount);
// check out samplematrix
newTargetBuffer.send("checkOutMatrix",aSendWeDontCareAbout7,checkOutValue);
TTObjectBase* checkedOutMatrix = checkOutValue[0];
// now let's test some values!
int randomIndex7;
TTSampleValue randomValueSoundFile7;
TTBoolean result7 = true;
for (int i = 0; i<5; i++)
{
randomIndex7 = lengthReturn * TTRandom64();
std::cout << "let's look at index " << randomIndex7 << "\n";
TTValue peekInput7(randomIndex7);
peekInput7.append(0);
TTValue peekOutput7;
this->peek(randomIndex7,0,randomValueSoundFile7);
checkedOutMatrix->sendMessage("peek",peekInput7,peekOutput7);
std::cout << "Does " << randomValueSoundFile7 << " = " << double(peekOutput7) << " ?\n";
if (result7) // allows test to keep variable false once it is false
result7 = TTTestFloatEquivalence(randomValueSoundFile7, double(peekOutput7), true, 0.0000001);
}
TTTestAssertion("comparing 5 random values for equivalence",
result7,
testAssertionCount,
errorCount);
// check in samplematrix
TTBoolean result7c = { newTargetBuffer.send("checkInMatrix",checkOutValue,aReturnWeDontCareAbout7) == kTTErrNone };
TTTestAssertion("TTBuffer checks in SampleMatrix successfully",
result7c,
testAssertionCount,
errorCount);
// releasing objects
objectBasePtrToSampleMatrix = NULL;
ptrToNonSampleMatrix = NULL;
delete testTargetMatrix;
delete testNonSampleMatrix;
} catch (...) {
TTTestAssertion("FAILED to run tests -- likely that necessary objects did not instantiate",
0,
testAssertionCount,
errorCount);
}
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
<|endoftext|> |
<commit_before>/*
* This file is part of telepathy-common-internals
*
* Copyright (C) 2012 David Edmundson <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "global-contact-manager.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/Account>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingReady>
#include "KTp/types.h"
#include <KDebug>
namespace KTp {
class GlobalContactManagerPrivate {
public:
Tp::AccountManagerPtr accountManager;
};
}
using namespace KTp;
GlobalContactManager::GlobalContactManager(const Tp::AccountManagerPtr &accountManager, QObject *parent) :
QObject(parent),
d(new GlobalContactManagerPrivate())
{
d->accountManager = accountManager;
connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
GlobalContactManager::~GlobalContactManager()
{
delete d;
}
Tp::Contacts GlobalContactManager::allKnownContacts() const
{
Tp::Contacts allContacts;
if (d->accountManager.isNull()) {
return allContacts;
}
Q_FOREACH(const Tp::AccountPtr &account, d->accountManager->allAccounts()) {
if (!account->connection().isNull() && account->connection()->contactManager()->state() == Tp::ContactListStateSuccess) {
allContacts.unite(account->connection()->contactManager()->allKnownContacts());
}
}
return allContacts;
}
void GlobalContactManager::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Account Manager becomeReady failed";
}
Q_FOREACH(const Tp::AccountPtr &account, d->accountManager->allAccounts()) {
onNewAccount(account);
}
connect(d->accountManager.data(), SIGNAL(newAccount(Tp::AccountPtr)), SLOT(onNewAccount(Tp::AccountPtr)));
}
void GlobalContactManager::onNewAccount(const Tp::AccountPtr &account)
{
onConnectionChanged(account->connection());
connect(account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onConnectionChanged(Tp::ConnectionPtr)));
}
void GlobalContactManager::onConnectionChanged(const Tp::ConnectionPtr &connection)
{
if (connection.isNull()) {
return;
}
//fetch the roster
//only request roster groups if we support it. Otherwise it can error and not finish becoming ready
//this is needed to fetch contacts from Salut which do not support groups
Tp::Features connectionFeatures;
connectionFeatures << Tp::Connection::FeatureRoster;
if (connection->hasInterface(TP_QT_IFACE_CHANNEL + QLatin1String(".ContactGroups"))) {
connectionFeatures << Tp::Connection::FeatureRosterGroups;
}
Tp::PendingReady *op = connection->becomeReady(connectionFeatures);
op->setProperty("connection", QVariant::fromValue<Tp::ConnectionPtr>(connection));
connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onConnectionReady(Tp::PendingOperation*)));
}
void GlobalContactManager::onConnectionReady(Tp::PendingOperation *op)
{
Tp::ConnectionPtr connection = op->property("connection").value<Tp::ConnectionPtr>();
if (!connection) {
return;
}
onContactManagerStateChanged(connection->contactManager(), connection->contactManager()->state());
connect(connection->contactManager().data(), SIGNAL(stateChanged(Tp::ContactListState)), SLOT(onContactManagerStateChanged(Tp::ContactListState)));
}
void GlobalContactManager::onContactManagerStateChanged(Tp::ContactListState state)
{
Tp::ContactManager* contactManager = qobject_cast<Tp::ContactManager*>(sender());
Q_ASSERT(contactManager);
onContactManagerStateChanged(Tp::ContactManagerPtr(contactManager), state);
}
void GlobalContactManager::onContactManagerStateChanged(const Tp::ContactManagerPtr &contactManager, Tp::ContactListState state)
{
//contact manager still isn't ready. Do nothing.
if (state != Tp::ContactListStateSuccess) {
return;
}
//contact manager connected, inform everyone of potential new contacts
Q_EMIT allKnownContactsChanged(contactManager->allKnownContacts(), Tp::Contacts());
connect(contactManager.data(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,Tp::Channel::GroupMemberChangeDetails)), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
}
Tp::AccountPtr GlobalContactManager::accountForContact(const Tp::ContactPtr &contact) const
{
return accountForConnection(contact->manager()->connection());
}
Tp::AccountPtr GlobalContactManager::accountForConnection(const Tp::ConnectionPtr &connection) const
{
//loop through all accounts looking for a matching connection.
//arguably inneficient, but no. of accounts is normally very low, and it's not called very often.
Q_FOREACH(const Tp::AccountPtr &account, d->accountManager->allAccounts()) {
if (account->connection() == connection) {
return account;
}
}
return Tp::AccountPtr();
}
Tp::AccountPtr GlobalContactManager::accountForAccountId(const QString &accountId) const
{
if (!d->accountManager.isNull() && d->accountManager->isReady()) {
Q_FOREACH(const Tp::AccountPtr &account, d->accountManager->allAccounts()) {
if (account->uniqueIdentifier() == accountId) {
return account;
}
}
}
return Tp::AccountPtr();
}
<commit_msg>Fix contact groups broken by last commit<commit_after>/*
* This file is part of telepathy-common-internals
*
* Copyright (C) 2012 David Edmundson <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "global-contact-manager.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/Account>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingReady>
#include "KTp/types.h"
#include <KDebug>
namespace KTp {
class GlobalContactManagerPrivate {
public:
Tp::AccountManagerPtr accountManager;
};
}
using namespace KTp;
GlobalContactManager::GlobalContactManager(const Tp::AccountManagerPtr &accountManager, QObject *parent) :
QObject(parent),
d(new GlobalContactManagerPrivate())
{
d->accountManager = accountManager;
connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady(Tp::PendingOperation*)));
}
GlobalContactManager::~GlobalContactManager()
{
delete d;
}
Tp::Contacts GlobalContactManager::allKnownContacts() const
{
Tp::Contacts allContacts;
if (d->accountManager.isNull()) {
return allContacts;
}
Q_FOREACH(const Tp::AccountPtr &account, d->accountManager->allAccounts()) {
if (!account->connection().isNull() && account->connection()->contactManager()->state() == Tp::ContactListStateSuccess) {
allContacts.unite(account->connection()->contactManager()->allKnownContacts());
}
}
return allContacts;
}
void GlobalContactManager::onAccountManagerReady(Tp::PendingOperation *op)
{
if (op->isError()) {
kWarning() << "Account Manager becomeReady failed";
}
Q_FOREACH(const Tp::AccountPtr &account, d->accountManager->allAccounts()) {
onNewAccount(account);
}
connect(d->accountManager.data(), SIGNAL(newAccount(Tp::AccountPtr)), SLOT(onNewAccount(Tp::AccountPtr)));
}
void GlobalContactManager::onNewAccount(const Tp::AccountPtr &account)
{
onConnectionChanged(account->connection());
connect(account.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onConnectionChanged(Tp::ConnectionPtr)));
}
void GlobalContactManager::onConnectionChanged(const Tp::ConnectionPtr &connection)
{
if (connection.isNull()) {
return;
}
//fetch the roster
//only request roster groups if we support it. Otherwise it can error and not finish becoming ready
//this is needed to fetch contacts from Salut which do not support groups
Tp::Features connectionFeatures;
connectionFeatures << Tp::Connection::FeatureRoster;
if (connection->hasInterface(TP_QT_IFACE_CONNECTION_INTERFACE_CONTACT_GROUPS)) {
connectionFeatures << Tp::Connection::FeatureRosterGroups;
}
Tp::PendingReady *op = connection->becomeReady(connectionFeatures);
op->setProperty("connection", QVariant::fromValue<Tp::ConnectionPtr>(connection));
connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onConnectionReady(Tp::PendingOperation*)));
}
void GlobalContactManager::onConnectionReady(Tp::PendingOperation *op)
{
Tp::ConnectionPtr connection = op->property("connection").value<Tp::ConnectionPtr>();
if (!connection) {
return;
}
onContactManagerStateChanged(connection->contactManager(), connection->contactManager()->state());
connect(connection->contactManager().data(), SIGNAL(stateChanged(Tp::ContactListState)), SLOT(onContactManagerStateChanged(Tp::ContactListState)));
}
void GlobalContactManager::onContactManagerStateChanged(Tp::ContactListState state)
{
Tp::ContactManager* contactManager = qobject_cast<Tp::ContactManager*>(sender());
Q_ASSERT(contactManager);
onContactManagerStateChanged(Tp::ContactManagerPtr(contactManager), state);
}
void GlobalContactManager::onContactManagerStateChanged(const Tp::ContactManagerPtr &contactManager, Tp::ContactListState state)
{
//contact manager still isn't ready. Do nothing.
if (state != Tp::ContactListStateSuccess) {
return;
}
//contact manager connected, inform everyone of potential new contacts
Q_EMIT allKnownContactsChanged(contactManager->allKnownContacts(), Tp::Contacts());
connect(contactManager.data(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts,Tp::Channel::GroupMemberChangeDetails)), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)));
}
Tp::AccountPtr GlobalContactManager::accountForContact(const Tp::ContactPtr &contact) const
{
return accountForConnection(contact->manager()->connection());
}
Tp::AccountPtr GlobalContactManager::accountForConnection(const Tp::ConnectionPtr &connection) const
{
//loop through all accounts looking for a matching connection.
//arguably inneficient, but no. of accounts is normally very low, and it's not called very often.
Q_FOREACH(const Tp::AccountPtr &account, d->accountManager->allAccounts()) {
if (account->connection() == connection) {
return account;
}
}
return Tp::AccountPtr();
}
Tp::AccountPtr GlobalContactManager::accountForAccountId(const QString &accountId) const
{
if (!d->accountManager.isNull() && d->accountManager->isReady()) {
Q_FOREACH(const Tp::AccountPtr &account, d->accountManager->allAccounts()) {
if (account->uniqueIdentifier() == accountId) {
return account;
}
}
}
return Tp::AccountPtr();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Thomas Fidler
*
* 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 "stromx/raspi/Config.h"
#include "stromx/raspi/RaspiCam.h"
#include <stromx/cvsupport/Image.h>
#include <stromx/runtime/Image.h>
#include <stromx/runtime/DataProvider.h>
#include <stromx/runtime/Id2DataPair.h>
#include <stromx/runtime/OperatorException.h>
#include <opencv2/core/core.hpp>
#include <bcm_host.h>
#include <interface/mmal/mmal_component.h>
#include <interface/mmal/util/mmal_default_components.h>
#include <interface/mmal/mmal_pool.h>
#include <interface/mmal/mmal_port.h>
#include <interface/mmal/mmal_parameters_camera.h>
#include <interface/mmal/util/mmal_util.h>
#include <interface/mmal/util/mmal_util_params.h>
#define MMAL_CAMERA_VIDEO_PORT 1
#define MMAL_CAMERA_PREVIEW_PORT 0
#define MMAL_CAMERA_CAPTURE_PORT 2
namespace stromx
{
namespace raspi
{
const std::string RaspiCam::TYPE("RaspiCam");
const std::string RaspiCam::PACKAGE(STROMX_RASPI_PACKAGE_NAME);
const runtime::Version RaspiCam::VERSION(STROMX_RASPI_VERSION_MAJOR,STROMX_RASPI_VERSION_MINOR,STROMX_RASPI_VERSION_PATCH);
const std::vector< const runtime::Description* > RaspiCam::setupInputs()
{
return std::vector<const runtime::Description*>();
}
const std::vector< const runtime::Description* > RaspiCam::setupOutputs()
{
std::vector<const runtime::Description*> outputs;
runtime::Description* output = new runtime::Description(OUTPUT, runtime::DataVariant::RGB_IMAGE);
output->setTitle("Output");
outputs.push_back(output);
return outputs;
}
const std::vector< const runtime::Parameter* > RaspiCam::setupInitParameters()
{
return std::vector<const runtime::Parameter*>();
}
RaspiCam::RaspiCam()
: OperatorKernel(TYPE, PACKAGE, VERSION, setupInputs(), setupOutputs(), setupInitParameters()),
m_raspicam(NULL)
{
}
void RaspiCam::initialize()
{
try
{
MMAL_STATUS_T status;
bcm_host_init();
status = mmal_component_create(MMAL_COMPONENT_DEFAULT_CAMERA, &m_raspicam);
if(status != MMAL_SUCCESS)
{
std::cout << "MMAL: Could not create default camera." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
if(!m_raspicam->output_num)
{
std::cout << "MMAL: Default camera doesn't have output ports." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
MMAL_PORT_T *raspicamVideoPort = m_raspicam->output[MMAL_CAMERA_VIDEO_PORT];
//MMAL_PORT_T *raspicamPreviewPort = m_raspicam->output[MMAL_CAMERA_PREVIEW_PORT];
//MMAL_PORT_T *raspicamCapturePort = m_raspicam->output[MMAL_CAMERA_CAPTURE_PORT];
MMAL_PARAMETER_CAMERA_CONFIG_T raspicamConfig;
raspicamConfig.hdr.id = MMAL_PARAMETER_CAMERA_CONFIG;
raspicamConfig.hdr.size = sizeof(raspicamConfig);
raspicamConfig.max_stills_w = 1280;
raspicamConfig.max_stills_h = 720;
raspicamConfig.stills_yuv422 = 0;
raspicamConfig.one_shot_stills = 0;
raspicamConfig.max_preview_video_w = 1280;
raspicamConfig.max_preview_video_h = 720;
raspicamConfig.num_preview_video_frames = 3;
raspicamConfig.stills_capture_circular_buffer_height = 0;
raspicamConfig.fast_preview_resume = 0;
raspicamConfig.use_stc_timestamp = MMAL_PARAM_TIMESTAMP_MODE_RESET_STC;
mmal_port_parameter_set(m_raspicam->control, &raspicamConfig.hdr);
//Get the pointer to each port format
MMAL_ES_FORMAT_T* raspicamVideoFormat = raspicamVideoPort->format;
//MMAL_ES_FORMAT_T* raspicamPreviewFormat = raspicamPreviewPort->format;
//Set up the formats on each port
raspicamVideoFormat->encoding_variant = MMAL_ENCODING_BGR24;//MMAL_ENCODING_I420;
raspicamVideoFormat->encoding = MMAL_ENCODING_BGR24;//MMAL_ENCODING_OPAQUE;
raspicamVideoFormat->es->video.width = 1280;
raspicamVideoFormat->es->video.height = 720;
raspicamVideoFormat->es->video.crop.x = 0;
raspicamVideoFormat->es->video.crop.y = 0;
raspicamVideoFormat->es->video.crop.width = 1280;
raspicamVideoFormat->es->video.crop.height = 720;
raspicamVideoFormat->es->video.frame_rate.num = 30;
raspicamVideoFormat->es->video.frame_rate.den = 1;
//raspicamVideoPort->buffer_size = 1280*720*12/8;
raspicamVideoPort->buffer_num = 10;
// raspicamPreviewFormat->encoding_variant = MMAL_ENCODING_I420;
// raspicamPreviewFormat->encoding = MMAL_ENCODING_OPAQUE;
// raspicamPreviewFormat->es->video.width = 1280;
// raspicamPreviewFormat->es->video.height = 720;
// raspicamPreviewFormat->es->video.crop.x = 0;
// raspicamPreviewFormat->es->video.crop.y = 0;
// raspicamPreviewFormat->es->video.crop.width = 1280;
// raspicamPreviewFormat->es->video.crop.height = 720;
// raspicamPreviewFormat->es->video.frame_rate.num = 30;
// raspicamPreviewFormat->es->video.frame_rate.den = 1;
// raspicamPreviewPort->buffer_size = 1280*720*12/8;
// raspicamPreviewPort->buffer_num = 3;
//Commit port formats
if(mmal_port_format_commit(raspicamVideoPort) != MMAL_SUCCESS)
{
std::cout << "MMAL: could not commit camera video port format." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
// if(mmal_port_format_commit(raspicamPreviewPort) != MMAL_SUCCESS)
// {
// std::cout << "MMAL: could not commit camera preview port format." << std::endl;
// this->~RaspiCam();
// throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
// }
m_outBufferPool = mmal_port_pool_create(raspicamVideoPort, raspicamVideoPort->buffer_num, raspicamVideoPort->buffer_size_recommended);
if(m_outBufferPool == NULL)
{
std::cout << "MMAL: could not create buffer pool for video port." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
m_outQueue = mmal_queue_create();
if(m_outQueue == NULL)
{
std::cout << "MMAL: could not create queue for video port." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
raspicamVideoPort->userdata = (MMAL_PORT_USERDATA_T*)m_outQueue;
status = mmal_port_enable(raspicamVideoPort, callbackOutVideoPort);
if(status != MMAL_SUCCESS)
{
std::cout << "MMAL: could not enable video port." << std::endl;
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
status = mmal_component_enable(m_raspicam);
if(status != MMAL_SUCCESS)
{
std::cout << "MMAL: could not enable camera." << std::endl;
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
}
catch(runtime::OperatorAllocationFailed &)
{}
}
RaspiCam::~RaspiCam()
{
if(m_raspicam)
mmal_component_destroy(m_raspicam);
if(m_outBufferPool)
mmal_pool_destroy(m_outBufferPool);
if(m_outQueue)
mmal_queue_destroy(m_outQueue);
}
void RaspiCam::execute(runtime::DataProvider& provider)
{
MMAL_BUFFER_HEADER_T* buffer;
MMAL_BUFFER_HEADER_T* bufferNew;
if(m_raspicam->output[MMAL_CAMERA_VIDEO_PORT]->is_enabled)
{
unsigned int bufferCounter = 0;
while((bufferNew = mmal_queue_get(m_outBufferPool->queue)) != NULL)
{
mmal_port_send_buffer(m_raspicam->output[MMAL_CAMERA_VIDEO_PORT], bufferNew);
bufferCounter++;
std::cout << bufferCounter << std::endl;
}
if(bufferCounter == 0)
{
std::cout << "MMAL: Cannot return a new buffer to video port." << std::endl;
}
mmal_port_parameter_set_boolean(m_raspicam->output[MMAL_CAMERA_VIDEO_PORT],MMAL_PARAMETER_CAPTURE, 1);
if((buffer = mmal_queue_get(m_outQueue)) != NULL)
{
std::cout << "DEBUG: Entering buffer processing" << std::endl;
if(buffer->cmd)
{
mmal_buffer_header_release(buffer);
}
else
{
cv::Mat bufferCopy(1280,720,CV_32FC3);
mmal_buffer_header_mem_lock(buffer);
std::cout << "Debug: before memcpy" << std::endl;
memcpy(&bufferCopy, buffer->data, 1280*720*3);
std::cout << "Debug: after memcpy" << std::endl;
mmal_buffer_header_mem_unlock(buffer);
std::cout << "Debug: buffer unlocked" << std::endl;
//mmal_buffer_header_release(buffer);
std::cout << "Debug: try to create outImage" << std::endl;
cvsupport::Image* outImage = new cvsupport::Image(bufferCopy);
std::cout << "Debug: outImage created" << std::endl;
try
{
std::cout << "Debug: before outImage initialization" << std::endl;
outImage->initializeImage(1280, 720, outImage->stride(), outImage->data(), cvsupport::Image::BGR_24);
std::cout << "Debug: after outImage initialization" << std::endl;
}
catch(runtime::WrongArgument&)
{
}
runtime::DataContainer outContainer = runtime::DataContainer(outImage);
runtime::Id2DataPair outputDataMapper(OUTPUT, outContainer);
provider.sendOutputData(outputDataMapper);
}
}
}
}
void RaspiCam::callbackOutVideoPort(MMAL_PORT_T* port, MMAL_BUFFER_HEADER_T* buffer)
{
std::cout << "DEBUG: Entering callbackOutVideoPort" << std::endl;
MMAL_QUEUE_T* queue = (MMAL_QUEUE_T*)port->userdata;
mmal_queue_put(queue,buffer);
}
}
}
<commit_msg>Raspi cam test does not crash<commit_after>/*
* Copyright 2014 Thomas Fidler
*
* 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 "stromx/raspi/Config.h"
#include "stromx/raspi/RaspiCam.h"
#include <stromx/cvsupport/Image.h>
#include <stromx/runtime/Image.h>
#include <stromx/runtime/DataProvider.h>
#include <stromx/runtime/Id2DataPair.h>
#include <stromx/runtime/OperatorException.h>
#include <opencv2/core/core.hpp>
#include <bcm_host.h>
#include <interface/mmal/mmal_component.h>
#include <interface/mmal/util/mmal_default_components.h>
#include <interface/mmal/mmal_pool.h>
#include <interface/mmal/mmal_port.h>
#include <interface/mmal/mmal_parameters_camera.h>
#include <interface/mmal/util/mmal_util.h>
#include <interface/mmal/util/mmal_util_params.h>
#define MMAL_CAMERA_VIDEO_PORT 1
#define MMAL_CAMERA_PREVIEW_PORT 0
#define MMAL_CAMERA_CAPTURE_PORT 2
namespace stromx
{
namespace raspi
{
const std::string RaspiCam::TYPE("RaspiCam");
const std::string RaspiCam::PACKAGE(STROMX_RASPI_PACKAGE_NAME);
const runtime::Version RaspiCam::VERSION(STROMX_RASPI_VERSION_MAJOR,STROMX_RASPI_VERSION_MINOR,STROMX_RASPI_VERSION_PATCH);
const std::vector< const runtime::Description* > RaspiCam::setupInputs()
{
return std::vector<const runtime::Description*>();
}
const std::vector< const runtime::Description* > RaspiCam::setupOutputs()
{
std::vector<const runtime::Description*> outputs;
runtime::Description* output = new runtime::Description(OUTPUT, runtime::DataVariant::RGB_IMAGE);
output->setTitle("Output");
outputs.push_back(output);
return outputs;
}
const std::vector< const runtime::Parameter* > RaspiCam::setupInitParameters()
{
return std::vector<const runtime::Parameter*>();
}
RaspiCam::RaspiCam()
: OperatorKernel(TYPE, PACKAGE, VERSION, setupInputs(), setupOutputs(), setupInitParameters()),
m_raspicam(NULL)
{
}
void RaspiCam::initialize()
{
try
{
MMAL_STATUS_T status;
bcm_host_init();
status = mmal_component_create(MMAL_COMPONENT_DEFAULT_CAMERA, &m_raspicam);
if(status != MMAL_SUCCESS)
{
std::cout << "MMAL: Could not create default camera." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
if(!m_raspicam->output_num)
{
std::cout << "MMAL: Default camera doesn't have output ports." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
MMAL_PORT_T *raspicamVideoPort = m_raspicam->output[MMAL_CAMERA_VIDEO_PORT];
//MMAL_PORT_T *raspicamPreviewPort = m_raspicam->output[MMAL_CAMERA_PREVIEW_PORT];
//MMAL_PORT_T *raspicamCapturePort = m_raspicam->output[MMAL_CAMERA_CAPTURE_PORT];
MMAL_PARAMETER_CAMERA_CONFIG_T raspicamConfig;
raspicamConfig.hdr.id = MMAL_PARAMETER_CAMERA_CONFIG;
raspicamConfig.hdr.size = sizeof(raspicamConfig);
raspicamConfig.max_stills_w = 1280;
raspicamConfig.max_stills_h = 720;
raspicamConfig.stills_yuv422 = 0;
raspicamConfig.one_shot_stills = 0;
raspicamConfig.max_preview_video_w = 1280;
raspicamConfig.max_preview_video_h = 720;
raspicamConfig.num_preview_video_frames = 3;
raspicamConfig.stills_capture_circular_buffer_height = 0;
raspicamConfig.fast_preview_resume = 0;
raspicamConfig.use_stc_timestamp = MMAL_PARAM_TIMESTAMP_MODE_RESET_STC;
mmal_port_parameter_set(m_raspicam->control, &raspicamConfig.hdr);
//Get the pointer to each port format
MMAL_ES_FORMAT_T* raspicamVideoFormat = raspicamVideoPort->format;
//MMAL_ES_FORMAT_T* raspicamPreviewFormat = raspicamPreviewPort->format;
//Set up the formats on each port
raspicamVideoFormat->encoding_variant = MMAL_ENCODING_BGR24;//MMAL_ENCODING_I420;
raspicamVideoFormat->encoding = MMAL_ENCODING_BGR24;//MMAL_ENCODING_OPAQUE;
raspicamVideoFormat->es->video.width = 1280;
raspicamVideoFormat->es->video.height = 720;
raspicamVideoFormat->es->video.crop.x = 0;
raspicamVideoFormat->es->video.crop.y = 0;
raspicamVideoFormat->es->video.crop.width = 1280;
raspicamVideoFormat->es->video.crop.height = 720;
raspicamVideoFormat->es->video.frame_rate.num = 30;
raspicamVideoFormat->es->video.frame_rate.den = 1;
//raspicamVideoPort->buffer_size = 1280*720*12/8;
raspicamVideoPort->buffer_num = 10;
// raspicamPreviewFormat->encoding_variant = MMAL_ENCODING_I420;
// raspicamPreviewFormat->encoding = MMAL_ENCODING_OPAQUE;
// raspicamPreviewFormat->es->video.width = 1280;
// raspicamPreviewFormat->es->video.height = 720;
// raspicamPreviewFormat->es->video.crop.x = 0;
// raspicamPreviewFormat->es->video.crop.y = 0;
// raspicamPreviewFormat->es->video.crop.width = 1280;
// raspicamPreviewFormat->es->video.crop.height = 720;
// raspicamPreviewFormat->es->video.frame_rate.num = 30;
// raspicamPreviewFormat->es->video.frame_rate.den = 1;
// raspicamPreviewPort->buffer_size = 1280*720*12/8;
// raspicamPreviewPort->buffer_num = 3;
//Commit port formats
if(mmal_port_format_commit(raspicamVideoPort) != MMAL_SUCCESS)
{
std::cout << "MMAL: could not commit camera video port format." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
// if(mmal_port_format_commit(raspicamPreviewPort) != MMAL_SUCCESS)
// {
// std::cout << "MMAL: could not commit camera preview port format." << std::endl;
// this->~RaspiCam();
// throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
// }
m_outBufferPool = mmal_port_pool_create(raspicamVideoPort, raspicamVideoPort->buffer_num, raspicamVideoPort->buffer_size_recommended);
if(m_outBufferPool == NULL)
{
std::cout << "MMAL: could not create buffer pool for video port." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
m_outQueue = mmal_queue_create();
if(m_outQueue == NULL)
{
std::cout << "MMAL: could not create queue for video port." << std::endl;
this->~RaspiCam();
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
raspicamVideoPort->userdata = (MMAL_PORT_USERDATA_T*)m_outQueue;
status = mmal_port_enable(raspicamVideoPort, callbackOutVideoPort);
if(status != MMAL_SUCCESS)
{
std::cout << "MMAL: could not enable video port." << std::endl;
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
status = mmal_component_enable(m_raspicam);
if(status != MMAL_SUCCESS)
{
std::cout << "MMAL: could not enable camera." << std::endl;
throw runtime::OperatorAllocationFailed("Raspi","RaspiCam");
}
}
catch(runtime::OperatorAllocationFailed &)
{}
}
RaspiCam::~RaspiCam()
{
if(m_raspicam)
mmal_component_destroy(m_raspicam);
if(m_outBufferPool)
mmal_pool_destroy(m_outBufferPool);
if(m_outQueue)
mmal_queue_destroy(m_outQueue);
}
void RaspiCam::execute(runtime::DataProvider& provider)
{
MMAL_BUFFER_HEADER_T* buffer;
MMAL_BUFFER_HEADER_T* bufferNew;
if(m_raspicam->output[MMAL_CAMERA_VIDEO_PORT]->is_enabled)
{
unsigned int bufferCounter = 0;
while((bufferNew = mmal_queue_get(m_outBufferPool->queue)) != NULL)
{
mmal_port_send_buffer(m_raspicam->output[MMAL_CAMERA_VIDEO_PORT], bufferNew);
bufferCounter++;
std::cout << bufferCounter << std::endl;
}
if(bufferCounter == 0)
{
std::cout << "MMAL: Cannot return a new buffer to video port." << std::endl;
}
mmal_port_parameter_set_boolean(m_raspicam->output[MMAL_CAMERA_VIDEO_PORT],MMAL_PARAMETER_CAPTURE, 1);
if((buffer = mmal_queue_get(m_outQueue)) != NULL)
{
std::cout << "DEBUG: Entering buffer processing" << std::endl;
if(buffer->cmd)
{
mmal_buffer_header_release(buffer);
}
else
{
cv::Mat bufferCopy(1280,720,CV_8UC3);
mmal_buffer_header_mem_lock(buffer);
std::cout << "Debug: before memcpy" << std::endl;
memcpy(bufferCopy.data, buffer->data, 1280*720*3);
std::cout << "Debug: after memcpy" << std::endl;
mmal_buffer_header_mem_unlock(buffer);
std::cout << "Debug: buffer unlocked" << std::endl;
mmal_buffer_header_release(buffer);
std::cout << "Debug: try to create outImage" << std::endl;
cvsupport::Image* outImage = new cvsupport::Image(bufferCopy);
std::cout << "Debug: outImage created" << std::endl;
try
{
std::cout << "Debug: before outImage initialization" << std::endl;
outImage->initializeImage(1280, 720, outImage->stride(), outImage->data(), cvsupport::Image::BGR_24);
std::cout << "Debug: after outImage initialization" << std::endl;
}
catch(runtime::WrongArgument&)
{
}
runtime::DataContainer outContainer = runtime::DataContainer(outImage);
runtime::Id2DataPair outputDataMapper(OUTPUT, outContainer);
provider.sendOutputData(outputDataMapper);
}
}
}
}
void RaspiCam::callbackOutVideoPort(MMAL_PORT_T* port, MMAL_BUFFER_HEADER_T* buffer)
{
std::cout << "DEBUG: Entering callbackOutVideoPort" << std::endl;
MMAL_QUEUE_T* queue = (MMAL_QUEUE_T*)port->userdata;
mmal_queue_put(queue,buffer);
}
}
}
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.