text
stringlengths 54
60.6k
|
|---|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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 "aboutwidget.h"
#include <QGraphicsLinearLayout>
#include <MImageWidget>
#include <MLabel>
#include <MSeparator>
#include <QGraphicsLinearLayout>
#include <MStylableWidget>
#include <MLinearLayoutPolicy>
#include <MContainer>
#include <MLayout>
#undef DEBUG
#include "../debug.h"
AboutWidget::AboutWidget (
AboutBusinessLogic *aboutBusinessLogic,
QGraphicsWidget *parent) :
DcpWidget (parent),
m_AboutBusinessLogic (aboutBusinessLogic),
m_MainLayout (0),
m_TitleLabel (0),
m_InfoLabel (0),
m_LicenseLabel (0)
{
createContent ();
connect (m_AboutBusinessLogic, SIGNAL (refreshNeeded ()),
SLOT (refresh ()));
retranslateUi ();
}
AboutWidget::~AboutWidget ()
{
}
void
AboutWidget::createContent ()
{
MLayout *layout;
/*
* Creating a layout that holds the rows of the internal widgets.
*/
layout = new MLayout (this);
m_MainLayout = new MLinearLayoutPolicy (layout, Qt::Vertical);
m_MainLayout->setContentsMargins (0., 0., 0., 0.);
m_MainLayout->setSpacing (0.);
setLayout (layout);
// Row 1: the title
addHeaderContainer ();
addStretcher ("CommonSmallSpacerInverted");
// Row 3: the logo
addLogoContainer ();
addStretcher ("CommonSpacerInverted");
// Row 5: the info label
addInfoLabelContainer ();
addStretcher ("CommonGroupDividerInverted");
// Row 7: the license label
addLicenseLabelContainer ();
addStretcher ("CommonSmallSpacerInverted");
//m_MainLayout->addStretch ();
}
void
AboutWidget::addHeaderContainer ()
{
MContainer *container;
QGraphicsLinearLayout *layout;
Q_ASSERT (m_MainLayout);
/*
* Creating a lcontainer and a layout.
*/
container = new MContainer (this);
container->setStyleName ("CommonXLargeGroupHeaderPanelInverted");
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
container->centralWidget()->setLayout (layout);
/*
* The label that we use as title.
*/
//% "About product"
m_TitleLabel = new MLabel (qtTrId("qtn_prod_about_product"));
m_TitleLabel->setStyleName ("CommonXLargeGroupHeaderInverted");
layout->addItem (m_TitleLabel);
layout->setAlignment (m_TitleLabel, Qt::AlignLeft);
/*
* Adding the whole row to the main container.
*/
m_MainLayout->addItem (container);
m_MainLayout->setStretchFactor (container, 0);
}
void
AboutWidget::addLogoContainer ()
{
MContainer *container;
QGraphicsLinearLayout *layout;
MImageWidget *logo;
Q_ASSERT (m_MainLayout);
/*
* Creating a lcontainer and a layout.
*/
container = new MContainer (this);
container->setStyleName ("CommonPanelInverted");
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
container->centralWidget()->setLayout (layout);
/*
* The logo
*/
logo = new MImageWidget;
logo->setImage ("icon-l-about-nokia-logo");
logo->setObjectName ("AboutAppletLogoImage");
layout->addItem (logo);
layout->setAlignment (logo, Qt::AlignLeft);
layout->addStretch ();
/*
* Adding the whole row to the main container.
*/
m_MainLayout->addItem (container);
m_MainLayout->setStretchFactor (container, 0);
}
void
AboutWidget::addInfoLabelContainer ()
{
MContainer *container;
QGraphicsLinearLayout *layout;
Q_ASSERT (m_MainLayout);
/*
* Creating a lcontainer and a layout.
*/
container = new MContainer (this);
container->setStyleName ("CommonLargePanelInverted");
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
container->centralWidget()->setLayout (layout);
/*
* The logo
*/
m_InfoLabel = new MLabel;
m_InfoLabel->setObjectName ("AboutAppletInfoLabel");
//m_InfoLabel->setStyleName ("CommonSubTitleInverted");
layout->addItem (m_InfoLabel);
/*
* Adding the whole row to the main container.
*/
m_MainLayout->addItem (container);
m_MainLayout->setStretchFactor (container, 0);
}
void
AboutWidget::addLicenseLabelContainer ()
{
MContainer *container;
QGraphicsLinearLayout *layout;
Q_ASSERT (m_MainLayout);
/*
* Creating a lcontainer and a layout.
*/
container = new MContainer (this);
container->setStyleName ("CommonLargePanelInverted");
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
container->centralWidget()->setLayout (layout);
/*
* The label
*/
m_LicenseLabel = new MLabel;
m_LicenseLabel->setWordWrap (true);
// this text is not translated!
m_LicenseLabel->setText (licenseText ());
//m_LicenseLabel->setStyleName ("CommonSubTitleInverted");
m_LicenseLabel->setObjectName ("AboutAppletLicenseLabel");
layout->addItem (m_LicenseLabel);
/*
* Adding the whole row to the main container.
*/
m_MainLayout->addItem (container);
m_MainLayout->setStretchFactor (container, 0);
}
void
AboutWidget::addStretcher (
const QString &styleName)
{
MStylableWidget *stretcher;
Q_ASSERT (m_MainLayout);
stretcher = new MStylableWidget ();
stretcher->setStyleName (styleName);
m_MainLayout->addItem (stretcher);
}
QString
AboutWidget::labelText()
{
QString retval;
QString tmp;
retval += "<h3>" + m_AboutBusinessLogic->osName () + "</h3>";
//% "Version"
retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_version"));
retval += m_AboutBusinessLogic->osVersion();
tmp = m_AboutBusinessLogic->WiFiAddress ();
if (tmp.isEmpty () == false)
{
//% "WLAN MAC address"
retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_wlan_mac_address"));
retval += tmp;
}
tmp = m_AboutBusinessLogic->BluetoothAddress ();
if (tmp.isEmpty () == false)
{
//% "Bluetooth address"
retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_bt_address"));
retval += tmp;
}
tmp = m_AboutBusinessLogic->IMEI ();
if (tmp.isEmpty () == false)
{
//% "IMEI"
retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_imei"));
retval += tmp;
}
// retval += "<hr />";
return retval;
}
QString
AboutWidget::licenseText()
{
QString retval;
// TODO: make this customizable [eg.: for meego.com]
retval += "<p>This product includes certain free/open source software</p>";
retval += "<p>The exact terms of the licenses, disclaimers, "
"aknowledgements and notices are provided in the "
"following document/through the following links:"
"<a href=\"http://somethink.here\">[insert document/link]</a>. "
"You may obtain the source code of the relevant free and open "
"source software at "
"<a href=\"http://somethink.here\">[insert the URL]</a>. "
"Alternatively, Nokia offers to provide such source code to you "
"on a CD-ROM upon written request to Nokia at:</p>";
retval += "<p>MeeGo Source Code Requests<br>";
retval += "Nokia Corporation<br>";
retval += "P.O.Box 407<br>";
retval += "FI-00045 Nokia Group<br>";
retval += "Finland<br>";
retval += "<p>This offer is valid for a period of three (3) years "
"from the date of the distribution of t his product by "
"Nokia.</p>";
retval += "<p>The Graphics Interchange Format (c) is the Copyright "
"property of CompuServe Incorporated. GIF(sm) is a "
"Service Mark property of Compuserve Incorporated.</p>";
retval += "<p>AdobeAE FlashAE Player. Copyright (c) 1996 - 2007 "
"Adobe Systems Incorporated. All Rights Reserved. "
"Protected by U.S. Patent 6,879,327; Patents Pending in the "
"United States and other countries. Adobe and Flas are either "
"trademarks or registered trademarks in the United States "
"and/or other countries.</p>";
return retval;
}
void
AboutWidget::refresh ()
{
m_InfoLabel->setText (labelText ());
}
void
AboutWidget::retranslateUi ()
{
//% "About product"
if (m_TitleLabel)
m_TitleLabel->setText (qtTrId("qtn_prod_about_product"));
refresh ();
}
<commit_msg>AboutApplet: proper spacers.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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 "aboutwidget.h"
#include <QGraphicsLinearLayout>
#include <MImageWidget>
#include <MLabel>
#include <MSeparator>
#include <QGraphicsLinearLayout>
#include <MSeparator>
#include <MLinearLayoutPolicy>
#include <MContainer>
#include <MLayout>
#undef DEBUG
#include "../debug.h"
AboutWidget::AboutWidget (
AboutBusinessLogic *aboutBusinessLogic,
QGraphicsWidget *parent) :
DcpWidget (parent),
m_AboutBusinessLogic (aboutBusinessLogic),
m_MainLayout (0),
m_TitleLabel (0),
m_InfoLabel (0),
m_LicenseLabel (0)
{
createContent ();
connect (m_AboutBusinessLogic, SIGNAL (refreshNeeded ()),
SLOT (refresh ()));
retranslateUi ();
}
AboutWidget::~AboutWidget ()
{
}
void
AboutWidget::createContent ()
{
MLayout *layout;
/*
* Creating a layout that holds the rows of the internal widgets.
*/
layout = new MLayout (this);
m_MainLayout = new MLinearLayoutPolicy (layout, Qt::Vertical);
m_MainLayout->setContentsMargins (0., 0., 0., 0.);
m_MainLayout->setSpacing (0.);
setLayout (layout);
// Row 1: the title
addHeaderContainer ();
addStretcher ("CommonSmallSpacerInverted");
// Row 3: the logo
addLogoContainer ();
addStretcher ("CommonSpacerInverted");
// Row 5: the info label
addInfoLabelContainer ();
addStretcher ("CommonGroupDividerInverted");
// Row 7: the license label
addLicenseLabelContainer ();
addStretcher ("CommonSmallSpacerInverted");
//m_MainLayout->addStretch ();
}
void
AboutWidget::addHeaderContainer ()
{
MContainer *container;
QGraphicsLinearLayout *layout;
Q_ASSERT (m_MainLayout);
/*
* Creating a lcontainer and a layout.
*/
container = new MContainer (this);
container->setStyleName ("CommonXLargeGroupHeaderPanelInverted");
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
container->centralWidget()->setLayout (layout);
/*
* The label that we use as title.
*/
//% "About product"
m_TitleLabel = new MLabel (qtTrId("qtn_prod_about_product"));
m_TitleLabel->setStyleName ("CommonXLargeGroupHeaderInverted");
layout->addItem (m_TitleLabel);
layout->setAlignment (m_TitleLabel, Qt::AlignLeft);
/*
* Adding the whole row to the main container.
*/
m_MainLayout->addItem (container);
m_MainLayout->setStretchFactor (container, 0);
}
void
AboutWidget::addLogoContainer ()
{
MContainer *container;
QGraphicsLinearLayout *layout;
MImageWidget *logo;
Q_ASSERT (m_MainLayout);
/*
* Creating a lcontainer and a layout.
*/
container = new MContainer (this);
container->setStyleName ("CommonPanelInverted");
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
container->centralWidget()->setLayout (layout);
/*
* The logo
*/
logo = new MImageWidget;
logo->setImage ("icon-l-about-nokia-logo");
logo->setObjectName ("AboutAppletLogoImage");
layout->addItem (logo);
layout->setAlignment (logo, Qt::AlignLeft);
layout->addStretch ();
/*
* Adding the whole row to the main container.
*/
m_MainLayout->addItem (container);
m_MainLayout->setStretchFactor (container, 0);
}
void
AboutWidget::addInfoLabelContainer ()
{
MContainer *container;
QGraphicsLinearLayout *layout;
Q_ASSERT (m_MainLayout);
/*
* Creating a lcontainer and a layout.
*/
container = new MContainer (this);
container->setStyleName ("CommonLargePanelInverted");
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
container->centralWidget()->setLayout (layout);
/*
* The logo
*/
m_InfoLabel = new MLabel;
m_InfoLabel->setObjectName ("AboutAppletInfoLabel");
//m_InfoLabel->setStyleName ("CommonSubTitleInverted");
layout->addItem (m_InfoLabel);
/*
* Adding the whole row to the main container.
*/
m_MainLayout->addItem (container);
m_MainLayout->setStretchFactor (container, 0);
}
void
AboutWidget::addLicenseLabelContainer ()
{
MContainer *container;
QGraphicsLinearLayout *layout;
Q_ASSERT (m_MainLayout);
/*
* Creating a lcontainer and a layout.
*/
container = new MContainer (this);
container->setStyleName ("CommonLargePanelInverted");
container->setHeaderVisible (false);
layout = new QGraphicsLinearLayout (Qt::Horizontal);
container->centralWidget()->setLayout (layout);
/*
* The label
*/
m_LicenseLabel = new MLabel;
m_LicenseLabel->setWordWrap (true);
// this text is not translated!
m_LicenseLabel->setText (licenseText ());
//m_LicenseLabel->setStyleName ("CommonSubTitleInverted");
m_LicenseLabel->setObjectName ("AboutAppletLicenseLabel");
layout->addItem (m_LicenseLabel);
/*
* Adding the whole row to the main container.
*/
m_MainLayout->addItem (container);
m_MainLayout->setStretchFactor (container, 0);
}
void
AboutWidget::addStretcher (
const QString &styleName)
{
MSeparator *stretcher;
Q_ASSERT (m_MainLayout);
stretcher = new MSeparator ();
stretcher->setStyleName (styleName);
m_MainLayout->addItem (stretcher);
}
QString
AboutWidget::labelText()
{
QString retval;
QString tmp;
retval += "<h3>" + m_AboutBusinessLogic->osName () + "</h3>";
//% "Version"
retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_version"));
retval += m_AboutBusinessLogic->osVersion();
tmp = m_AboutBusinessLogic->WiFiAddress ();
if (tmp.isEmpty () == false)
{
//% "WLAN MAC address"
retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_wlan_mac_address"));
retval += tmp;
}
tmp = m_AboutBusinessLogic->BluetoothAddress ();
if (tmp.isEmpty () == false)
{
//% "Bluetooth address"
retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_bt_address"));
retval += tmp;
}
tmp = m_AboutBusinessLogic->IMEI ();
if (tmp.isEmpty () == false)
{
//% "IMEI"
retval += QString ("<h3>%1</h3>").arg (qtTrId ("qtn_prod_imei"));
retval += tmp;
}
// retval += "<hr />";
return retval;
}
QString
AboutWidget::licenseText()
{
QString retval;
// TODO: make this customizable [eg.: for meego.com]
retval += "<p>This product includes certain free/open source software</p>";
retval += "<p>The exact terms of the licenses, disclaimers, "
"aknowledgements and notices are provided in the "
"following document/through the following links:"
"<a href=\"http://somethink.here\">[insert document/link]</a>. "
"You may obtain the source code of the relevant free and open "
"source software at "
"<a href=\"http://somethink.here\">[insert the URL]</a>. "
"Alternatively, Nokia offers to provide such source code to you "
"on a CD-ROM upon written request to Nokia at:</p>";
retval += "<p>MeeGo Source Code Requests<br>";
retval += "Nokia Corporation<br>";
retval += "P.O.Box 407<br>";
retval += "FI-00045 Nokia Group<br>";
retval += "Finland<br>";
retval += "<p>This offer is valid for a period of three (3) years "
"from the date of the distribution of t his product by "
"Nokia.</p>";
retval += "<p>The Graphics Interchange Format (c) is the Copyright "
"property of CompuServe Incorporated. GIF(sm) is a "
"Service Mark property of Compuserve Incorporated.</p>";
retval += "<p>AdobeAE FlashAE Player. Copyright (c) 1996 - 2007 "
"Adobe Systems Incorporated. All Rights Reserved. "
"Protected by U.S. Patent 6,879,327; Patents Pending in the "
"United States and other countries. Adobe and Flas are either "
"trademarks or registered trademarks in the United States "
"and/or other countries.</p>";
return retval;
}
void
AboutWidget::refresh ()
{
m_InfoLabel->setText (labelText ());
}
void
AboutWidget::retranslateUi ()
{
//% "About product"
if (m_TitleLabel)
m_TitleLabel->setText (qtTrId("qtn_prod_about_product"));
refresh ();
}
<|endoftext|>
|
<commit_before>// Module: Log4CPLUS
// File: threads.cxx
// Created: 6/2001
// Author: Tad E. Smith
//
//
// Copyright (C) Tad E. Smith All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $
// Revision 1.14 2003/08/04 01:10:12 tcsmith
// Modified the getCurrentThreadName() method to use convertIntegerToString().
//
// Revision 1.13 2003/07/19 15:41:04 tcsmith
// Cleaned up the threadStartFunc() method.
//
// Revision 1.12 2003/06/29 16:48:25 tcsmith
// Modified to support that move of the getLogLog() method into the LogLog
// class.
//
// Revision 1.11 2003/06/13 15:25:07 tcsmith
// Added the getCurrentThreadName() function.
//
// Revision 1.10 2003/06/04 18:56:41 tcsmith
// Modified to use the new timehelper.h header.
//
// Revision 1.9 2003/05/22 21:17:32 tcsmith
// Moved the sleep() method into sleep.cxx
//
// Revision 1.8 2003/04/29 17:38:45 tcsmith
// Added "return NULL" to the threadStartFunc() method to make the Sun Forte
// compiler happy.
//
// Revision 1.7 2003/04/18 21:58:47 tcsmith
// Converted from std::string to log4cplus::tstring.
//
// Revision 1.6 2003/04/03 01:31:43 tcsmith
// Standardized the formatting.
//
#ifndef LOG4CPLUS_SINGLE_THREADED
#include <log4cplus/helpers/threads.h>
#include <log4cplus/streams.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/timehelper.h>
#include <exception>
#include <stdexcept>
#include <errno.h>
#if defined(LOG4CPLUS_USE_PTHREADS)
# include <sched.h>
#endif
using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;
///////////////////////////////////////////////////////////////////////////////
// public methods
///////////////////////////////////////////////////////////////////////////////
LOG4CPLUS_MUTEX_PTR_DECLARE
log4cplus::thread::createNewMutex()
{
#if defined(LOG4CPLUS_USE_PTHREADS)
pthread_mutex_t* m = new pthread_mutex_t();
pthread_mutex_init(m, NULL);
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
CRITICAL_SECTION* m = new CRITICAL_SECTION();
InitializeCriticalSection(m);
#endif
return m;
}
void
log4cplus::thread::deleteMutex(LOG4CPLUS_MUTEX_PTR_DECLARE m)
{
#if defined(LOG4CPLUS_USE_PTHREADS)
pthread_mutex_destroy(m);
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
DeleteCriticalSection(m);
#endif
delete m;
}
#if defined(LOG4CPLUS_USE_PTHREADS)
pthread_key_t*
log4cplus::thread::createPthreadKey()
{
pthread_key_t* key = new pthread_key_t();
pthread_key_create(key, NULL);
return key;
}
#endif
void
log4cplus::thread::yield()
{
#if defined(LOG4CPLUS_USE_PTHREADS)
sched_yield();
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
Sleep(0);
#endif
}
log4cplus::tstring
log4cplus::thread::getCurrentThreadName()
{
#if (defined(__APPLE__) || (defined(__MWERKS__) && defined(__MACOS__)))
return convertIntegerToString(long(LOG4CPLUS_GET_CURRENT_THREAD));
#else
return convertIntegerToString(LOG4CPLUS_GET_CURRENT_THREAD);
#endif
}
#if defined(LOG4CPLUS_USE_PTHREADS)
void*
log4cplus::thread::threadStartFunc(void* arg)
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
DWORD WINAPI
log4cplus::thread::threadStartFunc(LPVOID arg)
#endif
{
SharedObjectPtr<LogLog> loglog = LogLog::getLogLog();
if(arg == NULL) {
loglog->error(LOG4CPLUS_TEXT("log4cplus::thread::threadStartFunc()- arg is NULL"));
}
else {
AbstractThread* ptr = static_cast<AbstractThread*>(arg);
log4cplus::helpers::SharedObjectPtr<AbstractThread> thread(ptr);
try {
thread->run();
}
catch(std::exception& e) {
tstring err = LOG4CPLUS_TEXT("log4cplus::thread::threadStartFunc()- run() terminated with an exception: ");
err += LOG4CPLUS_C_STR_TO_TSTRING(e.what());
loglog->warn(err);
}
catch(...) {
loglog->warn(LOG4CPLUS_TEXT("log4cplus::thread::threadStartFunc()- run() terminated with an exception."));
}
thread->running = false;
getNDC().remove();
}
#if defined(LOG4CPLUS_USE_PTHREADS)
pthread_exit(NULL);
#endif
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
// log4cplus::thread::AbstractThread ctor and dtor
///////////////////////////////////////////////////////////////////////////////
log4cplus::thread::AbstractThread::AbstractThread()
: running(false)
{
}
log4cplus::thread::AbstractThread::~AbstractThread()
{
}
///////////////////////////////////////////////////////////////////////////////
// log4cplus::thread::AbstractThread public methods
///////////////////////////////////////////////////////////////////////////////
void
log4cplus::thread::AbstractThread::start()
{
running = true;
#if defined(LOG4CPLUS_USE_PTHREADS)
if( pthread_create(&threadId, NULL, threadStartFunc, this) ) {
throw std::runtime_error(LOG4CPLUS_TEXT("Thread creation was not successful"));
}
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
HANDLE h = CreateThread(NULL, 0, threadStartFunc, (LPVOID)this, 0, &threadId);
CloseHandle(h);
#endif
}
#endif // LOG4CPLUS_SINGLE_THREADED
<commit_msg>Corrected the getCurrentThreadName() method for MacOS X and DEC cxx.<commit_after>// Module: Log4CPLUS
// File: threads.cxx
// Created: 6/2001
// Author: Tad E. Smith
//
//
// Copyright (C) Tad E. Smith All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
// $Log: not supported by cvs2svn $
// Revision 1.15 2003/08/09 06:58:21 tcsmith
// Fixed the getCurrentThreadName() method for MacOS X.
//
// Revision 1.14 2003/08/04 01:10:12 tcsmith
// Modified the getCurrentThreadName() method to use convertIntegerToString().
//
// Revision 1.13 2003/07/19 15:41:04 tcsmith
// Cleaned up the threadStartFunc() method.
//
// Revision 1.12 2003/06/29 16:48:25 tcsmith
// Modified to support that move of the getLogLog() method into the LogLog
// class.
//
// Revision 1.11 2003/06/13 15:25:07 tcsmith
// Added the getCurrentThreadName() function.
//
// Revision 1.10 2003/06/04 18:56:41 tcsmith
// Modified to use the new timehelper.h header.
//
// Revision 1.9 2003/05/22 21:17:32 tcsmith
// Moved the sleep() method into sleep.cxx
//
// Revision 1.8 2003/04/29 17:38:45 tcsmith
// Added "return NULL" to the threadStartFunc() method to make the Sun Forte
// compiler happy.
//
// Revision 1.7 2003/04/18 21:58:47 tcsmith
// Converted from std::string to log4cplus::tstring.
//
// Revision 1.6 2003/04/03 01:31:43 tcsmith
// Standardized the formatting.
//
#ifndef LOG4CPLUS_SINGLE_THREADED
#include <log4cplus/helpers/threads.h>
#include <log4cplus/streams.h>
#include <log4cplus/ndc.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/timehelper.h>
#include <exception>
#include <stdexcept>
#include <errno.h>
#if defined(LOG4CPLUS_USE_PTHREADS)
# include <sched.h>
#endif
using namespace std;
using namespace log4cplus;
using namespace log4cplus::helpers;
///////////////////////////////////////////////////////////////////////////////
// public methods
///////////////////////////////////////////////////////////////////////////////
LOG4CPLUS_MUTEX_PTR_DECLARE
log4cplus::thread::createNewMutex()
{
#if defined(LOG4CPLUS_USE_PTHREADS)
pthread_mutex_t* m = new pthread_mutex_t();
pthread_mutex_init(m, NULL);
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
CRITICAL_SECTION* m = new CRITICAL_SECTION();
InitializeCriticalSection(m);
#endif
return m;
}
void
log4cplus::thread::deleteMutex(LOG4CPLUS_MUTEX_PTR_DECLARE m)
{
#if defined(LOG4CPLUS_USE_PTHREADS)
pthread_mutex_destroy(m);
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
DeleteCriticalSection(m);
#endif
delete m;
}
#if defined(LOG4CPLUS_USE_PTHREADS)
pthread_key_t*
log4cplus::thread::createPthreadKey()
{
pthread_key_t* key = new pthread_key_t();
pthread_key_create(key, NULL);
return key;
}
#endif
void
log4cplus::thread::yield()
{
#if defined(LOG4CPLUS_USE_PTHREADS)
sched_yield();
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
Sleep(0);
#endif
}
log4cplus::tstring
log4cplus::thread::getCurrentThreadName()
{
#if defined(__DECCXX) || defined(__APPLE__) || ((defined(__MWERKS__) && defined(__MACOS__)))
log4cplus::tostringstream tmp;
tmp << LOG4CPLUS_GET_CURRENT_THREAD;
return tmp.str();
#else
return convertIntegerToString(LOG4CPLUS_GET_CURRENT_THREAD);
#endif
}
#if defined(LOG4CPLUS_USE_PTHREADS)
void*
log4cplus::thread::threadStartFunc(void* arg)
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
DWORD WINAPI
log4cplus::thread::threadStartFunc(LPVOID arg)
#endif
{
SharedObjectPtr<LogLog> loglog = LogLog::getLogLog();
if(arg == NULL) {
loglog->error(LOG4CPLUS_TEXT("log4cplus::thread::threadStartFunc()- arg is NULL"));
}
else {
AbstractThread* ptr = static_cast<AbstractThread*>(arg);
log4cplus::helpers::SharedObjectPtr<AbstractThread> thread(ptr);
try {
thread->run();
}
catch(std::exception& e) {
tstring err = LOG4CPLUS_TEXT("log4cplus::thread::threadStartFunc()- run() terminated with an exception: ");
err += LOG4CPLUS_C_STR_TO_TSTRING(e.what());
loglog->warn(err);
}
catch(...) {
loglog->warn(LOG4CPLUS_TEXT("log4cplus::thread::threadStartFunc()- run() terminated with an exception."));
}
thread->running = false;
getNDC().remove();
}
#if defined(LOG4CPLUS_USE_PTHREADS)
pthread_exit(NULL);
#endif
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
// log4cplus::thread::AbstractThread ctor and dtor
///////////////////////////////////////////////////////////////////////////////
log4cplus::thread::AbstractThread::AbstractThread()
: running(false)
{
}
log4cplus::thread::AbstractThread::~AbstractThread()
{
}
///////////////////////////////////////////////////////////////////////////////
// log4cplus::thread::AbstractThread public methods
///////////////////////////////////////////////////////////////////////////////
void
log4cplus::thread::AbstractThread::start()
{
running = true;
#if defined(LOG4CPLUS_USE_PTHREADS)
if( pthread_create(&threadId, NULL, threadStartFunc, this) ) {
throw std::runtime_error(LOG4CPLUS_TEXT("Thread creation was not successful"));
}
#elif defined(LOG4CPLUS_USE_WIN32_THREADS)
HANDLE h = CreateThread(NULL, 0, threadStartFunc, (LPVOID)this, 0, &threadId);
CloseHandle(h);
#endif
}
#endif // LOG4CPLUS_SINGLE_THREADED
<|endoftext|>
|
<commit_before>/*
* This file is part of Poedit (http://www.poedit.net)
*
* Copyright (C) 2001-2008 Vaclav Slavik
*
* 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.
*
* $Id$
*
* Search frame
*
*/
#include <wx/wxprec.h>
#include <wx/xrc/xmlres.h>
#include <wx/config.h>
#include <wx/button.h>
#include <wx/textctrl.h>
#include <wx/checkbox.h>
#include "catalog.h"
#include "findframe.h"
#include "edlistctrl.h"
// The word separators used when doing a "Whole words only" search
// FIXME-ICU: use ICU to separate words
static const wxString SEPARATORS = wxT(" \t\r\n\\/:;.,?!\"'_|-+=(){}[]<>&#@");
wxString FindFrame::ms_text;
BEGIN_EVENT_TABLE(FindFrame, wxFrame)
EVT_BUTTON(XRCID("find_next"), FindFrame::OnNext)
EVT_BUTTON(XRCID("find_prev"), FindFrame::OnPrev)
EVT_BUTTON(wxID_CLOSE, FindFrame::OnClose)
EVT_TEXT(XRCID("string_to_find"), FindFrame::OnTextChange)
EVT_CHECKBOX(-1, FindFrame::OnCheckbox)
END_EVENT_TABLE()
FindFrame::FindFrame(wxWindow *parent,
PoeditListCtrl *list,
Catalog *c,
wxTextCtrl *textCtrlOrig,
wxTextCtrl *textCtrlTrans,
wxTextCtrl *textCtrlComments,
wxTextCtrl *textCtrlAutoComments)
: m_listCtrl(list),
m_catalog(c),
m_position(-1),
m_textCtrlOrig(textCtrlOrig),
m_textCtrlTrans(textCtrlTrans),
m_textCtrlComments(textCtrlComments),
m_textCtrlAutoComments(textCtrlAutoComments)
{
wxPoint p(wxConfig::Get()->Read(_T("find_pos_x"), -1),
wxConfig::Get()->Read(_T("find_pos_y"), -1));
wxXmlResource::Get()->LoadFrame(this, parent, _T("find_frame"));
if (p.x != -1)
Move(p);
m_btnNext = XRCCTRL(*this, "find_next", wxButton);
m_btnPrev = XRCCTRL(*this, "find_prev", wxButton);
if ( !ms_text.empty() )
{
wxTextCtrl *t = XRCCTRL(*this, "string_to_find", wxTextCtrl);
t->SetValue(ms_text);
t->SetSelection(0, ms_text.length()-1);
}
Reset(c);
XRCCTRL(*this, "in_orig", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_in_orig"), (long)true));
XRCCTRL(*this, "in_trans", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_in_trans"), (long)true));
XRCCTRL(*this, "in_comments", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_in_comments"), (long)true));
XRCCTRL(*this, "in_auto_comments", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_in_auto_comments"), (long)true));
XRCCTRL(*this, "case_sensitive", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_case_sensitive"), (long)false));
XRCCTRL(*this, "from_first", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_from_first"), (long)true));
XRCCTRL(*this, "whole_words", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("whole_words"), (long)false));
}
FindFrame::~FindFrame()
{
wxConfig::Get()->Write(_T("find_pos_x"), (long)GetPosition().x);
wxConfig::Get()->Write(_T("find_pos_y"), (long)GetPosition().y);
wxConfig::Get()->Write(_T("find_in_orig"),
XRCCTRL(*this, "in_orig", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_in_trans"),
XRCCTRL(*this, "in_trans", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_in_comments"),
XRCCTRL(*this, "in_comments", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_in_auto_comments"),
XRCCTRL(*this, "in_auto_comments", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_case_sensitive"),
XRCCTRL(*this, "case_sensitive", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_from_first"),
XRCCTRL(*this, "from_first", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("whole_words"),
XRCCTRL(*this, "whole_words", wxCheckBox)->GetValue());
}
void FindFrame::Reset(Catalog *c)
{
bool fromFirst = XRCCTRL(*this, "from_first", wxCheckBox)->GetValue();
m_catalog = c;
m_position = -1;
if (!fromFirst)
m_position = m_listCtrl->GetNextItem(-1,
wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED);
m_btnPrev->Enable(!ms_text.empty());
m_btnNext->Enable(!ms_text.empty());
}
void FindFrame::OnClose(wxCommandEvent &event)
{
Destroy();
}
void FindFrame::OnTextChange(wxCommandEvent &event)
{
ms_text = XRCCTRL(*this, "string_to_find", wxTextCtrl)->GetValue();
Reset(m_catalog);
}
void FindFrame::OnCheckbox(wxCommandEvent &event)
{
Reset(m_catalog);
}
void FindFrame::OnPrev(wxCommandEvent &event)
{
if (!DoFind(-1))
m_btnPrev->Enable(false);
else
m_btnNext->Enable(true);
}
void FindFrame::OnNext(wxCommandEvent &event)
{
if (!DoFind(+1))
m_btnNext->Enable(false);
else
m_btnPrev->Enable(true);
}
enum FoundState
{
Found_Not = 0,
Found_InOrig,
Found_InTrans,
Found_InComments,
Found_InAutoComments
};
bool TextInString(const wxString& str, const wxString& text, bool wholeWords)
{
int index = str.Find(text);
if (index >= 0)
{
if (wholeWords)
{
unsigned textLen = text.Length();
bool result = true;
if (index >0)
result = result && SEPARATORS.Contains(str[index-1]);
if (index+textLen < str.Length())
result = result && SEPARATORS.Contains(str[index+textLen]);
return result;
}
else
{
return true;
}
}
else
{
return false;
}
}
bool FindFrame::DoFind(int dir)
{
int cnt = m_listCtrl->GetItemCount();
bool inStr = XRCCTRL(*this, "in_orig", wxCheckBox)->GetValue();
bool inTrans = XRCCTRL(*this, "in_trans", wxCheckBox)->GetValue();
bool inComments = XRCCTRL(*this, "in_comments", wxCheckBox)->GetValue();
bool inAutoComments = XRCCTRL(*this, "in_auto_comments", wxCheckBox)->GetValue();
bool caseSens = XRCCTRL(*this, "case_sensitive", wxCheckBox)->GetValue();
bool wholeWords = XRCCTRL(*this, "whole_words", wxCheckBox)->GetValue();
int posOrig = m_position;
FoundState found = Found_Not;
wxString textc;
wxString text(ms_text);
if (!caseSens)
text.MakeLower();
m_position += dir;
while (m_position >= 0 && m_position < cnt)
{
CatalogItem &dt = (*m_catalog)[m_listCtrl->GetIndexInCatalog(m_position)];
if (inStr)
{
textc = dt.GetString();
if (!caseSens)
textc.MakeLower();
if (TextInString(textc, text, wholeWords))
{
found = Found_InOrig;
break;
}
}
if (inTrans)
{
// concatenate all translations:
size_t cnt = dt.GetNumberOfTranslations();
textc = wxEmptyString;
for (size_t i = 0; i < cnt; i++)
{
textc += dt.GetTranslation(i);
}
// and search for the substring in them:
if (!caseSens)
textc.MakeLower();
if (TextInString(textc, text, wholeWords)) { found = Found_InTrans; break; }
}
if (inComments)
{
textc = dt.GetComment();
if (!caseSens)
textc.MakeLower();
if (TextInString(textc, text, wholeWords)) { found = Found_InComments; break; }
}
if (inAutoComments)
{
wxArrayString autoComments = dt.GetAutoComments();
textc = wxEmptyString;
for (unsigned i = 0; i < autoComments.GetCount(); i++)
textc += autoComments[i];
if (!caseSens)
textc.MakeLower();
if (TextInString(textc, text, wholeWords)) { found = Found_InAutoComments; break; }
}
m_position += dir;
}
if (found != Found_Not)
{
m_listCtrl->SetItemState(m_position,
wxLIST_STATE_FOCUSED, wxLIST_STATE_FOCUSED);
m_listCtrl->SetItemState(m_position,
wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
m_listCtrl->EnsureVisible(m_position);
// find the text on the control and select it:
wxTextCtrl* txt;
switch (found)
{
case Found_InOrig:
txt = m_textCtrlOrig;
break;
case Found_InTrans:
txt = m_textCtrlTrans;
break;
case Found_InComments:
txt = m_textCtrlComments;
break;
case Found_InAutoComments:
txt = m_textCtrlAutoComments;
break;
case Found_Not: // silence compiler warning, can't get here
break;
}
textc = txt->GetValue();
if (!caseSens)
textc.MakeLower();
int pos = textc.Find(text);
if (pos != wxNOT_FOUND)
txt->SetSelection(pos, pos + text.length());
return true;
}
m_position = posOrig;
return false;
}
<commit_msg>fixed pre-selecting in Find dialog to work on all platforms<commit_after>/*
* This file is part of Poedit (http://www.poedit.net)
*
* Copyright (C) 2001-2008 Vaclav Slavik
*
* 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.
*
* $Id$
*
* Search frame
*
*/
#include <wx/wxprec.h>
#include <wx/xrc/xmlres.h>
#include <wx/config.h>
#include <wx/button.h>
#include <wx/textctrl.h>
#include <wx/checkbox.h>
#include "catalog.h"
#include "findframe.h"
#include "edlistctrl.h"
// The word separators used when doing a "Whole words only" search
// FIXME-ICU: use ICU to separate words
static const wxString SEPARATORS = wxT(" \t\r\n\\/:;.,?!\"'_|-+=(){}[]<>&#@");
wxString FindFrame::ms_text;
BEGIN_EVENT_TABLE(FindFrame, wxFrame)
EVT_BUTTON(XRCID("find_next"), FindFrame::OnNext)
EVT_BUTTON(XRCID("find_prev"), FindFrame::OnPrev)
EVT_BUTTON(wxID_CLOSE, FindFrame::OnClose)
EVT_TEXT(XRCID("string_to_find"), FindFrame::OnTextChange)
EVT_CHECKBOX(-1, FindFrame::OnCheckbox)
END_EVENT_TABLE()
FindFrame::FindFrame(wxWindow *parent,
PoeditListCtrl *list,
Catalog *c,
wxTextCtrl *textCtrlOrig,
wxTextCtrl *textCtrlTrans,
wxTextCtrl *textCtrlComments,
wxTextCtrl *textCtrlAutoComments)
: m_listCtrl(list),
m_catalog(c),
m_position(-1),
m_textCtrlOrig(textCtrlOrig),
m_textCtrlTrans(textCtrlTrans),
m_textCtrlComments(textCtrlComments),
m_textCtrlAutoComments(textCtrlAutoComments)
{
wxPoint p(wxConfig::Get()->Read(_T("find_pos_x"), -1),
wxConfig::Get()->Read(_T("find_pos_y"), -1));
wxXmlResource::Get()->LoadFrame(this, parent, _T("find_frame"));
if (p.x != -1)
Move(p);
m_btnNext = XRCCTRL(*this, "find_next", wxButton);
m_btnPrev = XRCCTRL(*this, "find_prev", wxButton);
if ( !ms_text.empty() )
{
wxTextCtrl *t = XRCCTRL(*this, "string_to_find", wxTextCtrl);
t->SetValue(ms_text);
t->SetSelection(-1, -1);
}
Reset(c);
XRCCTRL(*this, "in_orig", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_in_orig"), (long)true));
XRCCTRL(*this, "in_trans", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_in_trans"), (long)true));
XRCCTRL(*this, "in_comments", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_in_comments"), (long)true));
XRCCTRL(*this, "in_auto_comments", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_in_auto_comments"), (long)true));
XRCCTRL(*this, "case_sensitive", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_case_sensitive"), (long)false));
XRCCTRL(*this, "from_first", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("find_from_first"), (long)true));
XRCCTRL(*this, "whole_words", wxCheckBox)->SetValue(
wxConfig::Get()->Read(_T("whole_words"), (long)false));
}
FindFrame::~FindFrame()
{
wxConfig::Get()->Write(_T("find_pos_x"), (long)GetPosition().x);
wxConfig::Get()->Write(_T("find_pos_y"), (long)GetPosition().y);
wxConfig::Get()->Write(_T("find_in_orig"),
XRCCTRL(*this, "in_orig", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_in_trans"),
XRCCTRL(*this, "in_trans", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_in_comments"),
XRCCTRL(*this, "in_comments", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_in_auto_comments"),
XRCCTRL(*this, "in_auto_comments", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_case_sensitive"),
XRCCTRL(*this, "case_sensitive", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("find_from_first"),
XRCCTRL(*this, "from_first", wxCheckBox)->GetValue());
wxConfig::Get()->Write(_T("whole_words"),
XRCCTRL(*this, "whole_words", wxCheckBox)->GetValue());
}
void FindFrame::Reset(Catalog *c)
{
bool fromFirst = XRCCTRL(*this, "from_first", wxCheckBox)->GetValue();
m_catalog = c;
m_position = -1;
if (!fromFirst)
m_position = m_listCtrl->GetNextItem(-1,
wxLIST_NEXT_ALL,
wxLIST_STATE_SELECTED);
m_btnPrev->Enable(!ms_text.empty());
m_btnNext->Enable(!ms_text.empty());
}
void FindFrame::OnClose(wxCommandEvent &event)
{
Destroy();
}
void FindFrame::OnTextChange(wxCommandEvent &event)
{
ms_text = XRCCTRL(*this, "string_to_find", wxTextCtrl)->GetValue();
Reset(m_catalog);
}
void FindFrame::OnCheckbox(wxCommandEvent &event)
{
Reset(m_catalog);
}
void FindFrame::OnPrev(wxCommandEvent &event)
{
if (!DoFind(-1))
m_btnPrev->Enable(false);
else
m_btnNext->Enable(true);
}
void FindFrame::OnNext(wxCommandEvent &event)
{
if (!DoFind(+1))
m_btnNext->Enable(false);
else
m_btnPrev->Enable(true);
}
enum FoundState
{
Found_Not = 0,
Found_InOrig,
Found_InTrans,
Found_InComments,
Found_InAutoComments
};
bool TextInString(const wxString& str, const wxString& text, bool wholeWords)
{
int index = str.Find(text);
if (index >= 0)
{
if (wholeWords)
{
unsigned textLen = text.Length();
bool result = true;
if (index >0)
result = result && SEPARATORS.Contains(str[index-1]);
if (index+textLen < str.Length())
result = result && SEPARATORS.Contains(str[index+textLen]);
return result;
}
else
{
return true;
}
}
else
{
return false;
}
}
bool FindFrame::DoFind(int dir)
{
int cnt = m_listCtrl->GetItemCount();
bool inStr = XRCCTRL(*this, "in_orig", wxCheckBox)->GetValue();
bool inTrans = XRCCTRL(*this, "in_trans", wxCheckBox)->GetValue();
bool inComments = XRCCTRL(*this, "in_comments", wxCheckBox)->GetValue();
bool inAutoComments = XRCCTRL(*this, "in_auto_comments", wxCheckBox)->GetValue();
bool caseSens = XRCCTRL(*this, "case_sensitive", wxCheckBox)->GetValue();
bool wholeWords = XRCCTRL(*this, "whole_words", wxCheckBox)->GetValue();
int posOrig = m_position;
FoundState found = Found_Not;
wxString textc;
wxString text(ms_text);
if (!caseSens)
text.MakeLower();
m_position += dir;
while (m_position >= 0 && m_position < cnt)
{
CatalogItem &dt = (*m_catalog)[m_listCtrl->GetIndexInCatalog(m_position)];
if (inStr)
{
textc = dt.GetString();
if (!caseSens)
textc.MakeLower();
if (TextInString(textc, text, wholeWords))
{
found = Found_InOrig;
break;
}
}
if (inTrans)
{
// concatenate all translations:
size_t cnt = dt.GetNumberOfTranslations();
textc = wxEmptyString;
for (size_t i = 0; i < cnt; i++)
{
textc += dt.GetTranslation(i);
}
// and search for the substring in them:
if (!caseSens)
textc.MakeLower();
if (TextInString(textc, text, wholeWords)) { found = Found_InTrans; break; }
}
if (inComments)
{
textc = dt.GetComment();
if (!caseSens)
textc.MakeLower();
if (TextInString(textc, text, wholeWords)) { found = Found_InComments; break; }
}
if (inAutoComments)
{
wxArrayString autoComments = dt.GetAutoComments();
textc = wxEmptyString;
for (unsigned i = 0; i < autoComments.GetCount(); i++)
textc += autoComments[i];
if (!caseSens)
textc.MakeLower();
if (TextInString(textc, text, wholeWords)) { found = Found_InAutoComments; break; }
}
m_position += dir;
}
if (found != Found_Not)
{
m_listCtrl->SetItemState(m_position,
wxLIST_STATE_FOCUSED, wxLIST_STATE_FOCUSED);
m_listCtrl->SetItemState(m_position,
wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED);
m_listCtrl->EnsureVisible(m_position);
// find the text on the control and select it:
wxTextCtrl* txt;
switch (found)
{
case Found_InOrig:
txt = m_textCtrlOrig;
break;
case Found_InTrans:
txt = m_textCtrlTrans;
break;
case Found_InComments:
txt = m_textCtrlComments;
break;
case Found_InAutoComments:
txt = m_textCtrlAutoComments;
break;
case Found_Not: // silence compiler warning, can't get here
break;
}
textc = txt->GetValue();
if (!caseSens)
textc.MakeLower();
int pos = textc.Find(text);
if (pos != wxNOT_FOUND)
txt->SetSelection(pos, pos + text.length());
return true;
}
m_position = posOrig;
return false;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/google_update_client.h"
#include <shlobj.h>
#include <strsafe.h>
#include "chrome/app/client_util.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/install_util.h"
namespace {
const wchar_t kEnvProductVersionKey[] = L"CHROME_VERSION";
// Allocates the out param on success.
bool GoogleUpdateEnvQueryStr(const wchar_t* key_name, wchar_t** out) {
DWORD count = ::GetEnvironmentVariableW(key_name, NULL, 0);
if (!count) {
return false;
}
wchar_t* value = new wchar_t[count + 1];
if (!::GetEnvironmentVariableW(key_name, value, count)) {
delete[] value;
return false;
}
*out = value;
return true;
}
} // anonymous namespace
namespace google_update {
GoogleUpdateClient::GoogleUpdateClient() : version_(NULL) {
}
GoogleUpdateClient::~GoogleUpdateClient() {
delete[] version_;
}
std::wstring GoogleUpdateClient::GetDLLPath() {
return client_util::GetDLLPath(dll_, dll_path_);
}
const wchar_t* GoogleUpdateClient::GetVersion() const {
return version_;
}
bool GoogleUpdateClient::Launch(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox,
wchar_t* command_line,
int show_command,
const char* entry_name,
int* ret) {
if (client_util::FileExists(dll_path_)) {
::SetCurrentDirectory(dll_path_);
// Setting the version on the environment block is a 'best effort' deal.
// It enables Google Update running on a child to load the same DLL version.
::SetEnvironmentVariableW(kEnvProductVersionKey, version_);
}
// The dll can be in the exe's directory or in the current directory.
// Use the alternate search path to be sure that it's not trying to load it
// calling application's directory.
HINSTANCE dll_handle = ::LoadLibraryEx(dll_.c_str(), NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (NULL == dll_handle) {
unsigned long err = GetLastError();
if (err) {
WCHAR message[500] = {0};
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
reinterpret_cast<LPWSTR>(&message), 500, NULL);
::OutputDebugStringW(message);
}
return false;
}
bool did_launch = false;
client_util::DLL_MAIN entry = reinterpret_cast<client_util::DLL_MAIN>(
::GetProcAddress(dll_handle, entry_name));
if (NULL != entry) {
// record did_run "dr" in client state
std::wstring key_path = google_update::kRegPathClientState + guid_;
HKEY reg_key;
if (::RegOpenKeyEx(HKEY_CURRENT_USER, key_path.c_str(), 0,
KEY_WRITE, ®_key) == ERROR_SUCCESS) {
const wchar_t kVal[] = L"1";
::RegSetValueEx(reg_key, google_update::kRegDidRunField, 0, REG_SZ,
reinterpret_cast<const BYTE *>(kVal), sizeof(kVal));
::RegCloseKey(reg_key);
}
int rc = (entry)(instance, sandbox, command_line, show_command);
if (ret) {
*ret = rc;
}
did_launch = true;
}
#ifdef PURIFY
// We should never unload the dll. There is only risk and no gain from
// doing so. The singleton dtors have been already run by AtExitManager.
::FreeLibrary(dll_handle);
#endif
return did_launch;
}
bool GoogleUpdateClient::Init(const wchar_t* client_guid,
const wchar_t* client_dll) {
client_util::GetExecutablePath(dll_path_);
guid_.assign(client_guid);
dll_.assign(client_dll);
bool ret = false;
if (!guid_.empty()) {
if (GoogleUpdateEnvQueryStr(kEnvProductVersionKey, &version_)) {
ret = true;
} else {
std::wstring key(google_update::kRegPathClients);
key.append(guid_);
if (client_util::GetChromiumVersion(dll_path_, key.c_str(), &version_))
ret = true;
}
}
if (version_) {
::StringCchCat(dll_path_, MAX_PATH, version_);
}
return ret;
}
} // namespace google_update
<commit_msg>Fix Chrome do not launch problem.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/google_update_client.h"
#include <shlobj.h>
#include <strsafe.h>
#include "chrome/app/client_util.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/install_util.h"
namespace {
const wchar_t kEnvProductVersionKey[] = L"CHROME_VERSION";
// Allocates the out param on success.
bool GoogleUpdateEnvQueryStr(const wchar_t* key_name, wchar_t** out) {
DWORD count = ::GetEnvironmentVariableW(key_name, NULL, 0);
if (!count) {
return false;
}
wchar_t* value = new wchar_t[count + 1];
if (!::GetEnvironmentVariableW(key_name, value, count)) {
delete[] value;
return false;
}
*out = value;
return true;
}
} // anonymous namespace
namespace google_update {
GoogleUpdateClient::GoogleUpdateClient() : version_(NULL) {
}
GoogleUpdateClient::~GoogleUpdateClient() {
delete[] version_;
}
std::wstring GoogleUpdateClient::GetDLLPath() {
return client_util::GetDLLPath(dll_, dll_path_);
}
const wchar_t* GoogleUpdateClient::GetVersion() const {
return version_;
}
bool GoogleUpdateClient::Launch(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox,
wchar_t* command_line,
int show_command,
const char* entry_name,
int* ret) {
if (client_util::FileExists(dll_path_)) {
::SetCurrentDirectory(dll_path_);
// Setting the version on the environment block is a 'best effort' deal.
// It enables Google Update running on a child to load the same DLL version.
::SetEnvironmentVariableW(kEnvProductVersionKey, version_);
}
// The dll can be in the exe's directory or in the current directory.
// Use the alternate search path to be sure that it's not trying to load it
// calling application's directory.
HINSTANCE dll_handle = ::LoadLibraryEx(dll_.c_str(), NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (NULL == dll_handle) {
unsigned long err = GetLastError();
if (err) {
WCHAR message[500] = {0};
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
reinterpret_cast<LPWSTR>(&message), 500, NULL);
::OutputDebugStringW(message);
}
return false;
}
bool did_launch = false;
client_util::DLL_MAIN entry = reinterpret_cast<client_util::DLL_MAIN>(
::GetProcAddress(dll_handle, entry_name));
if (NULL != entry) {
// record did_run "dr" in client state
std::wstring key_path(google_update::kRegPathClientState);
key_path.append(L"\\" + guid_);
HKEY reg_key;
if (::RegOpenKeyEx(HKEY_CURRENT_USER, key_path.c_str(), 0,
KEY_WRITE, ®_key) == ERROR_SUCCESS) {
const wchar_t kVal[] = L"1";
::RegSetValueEx(reg_key, google_update::kRegDidRunField, 0, REG_SZ,
reinterpret_cast<const BYTE *>(kVal), sizeof(kVal));
::RegCloseKey(reg_key);
}
int rc = (entry)(instance, sandbox, command_line, show_command);
if (ret) {
*ret = rc;
}
did_launch = true;
}
#ifdef PURIFY
// We should never unload the dll. There is only risk and no gain from
// doing so. The singleton dtors have been already run by AtExitManager.
::FreeLibrary(dll_handle);
#endif
return did_launch;
}
bool GoogleUpdateClient::Init(const wchar_t* client_guid,
const wchar_t* client_dll) {
client_util::GetExecutablePath(dll_path_);
guid_.assign(client_guid);
dll_.assign(client_dll);
bool ret = false;
if (!guid_.empty()) {
if (GoogleUpdateEnvQueryStr(kEnvProductVersionKey, &version_)) {
ret = true;
} else {
std::wstring key(google_update::kRegPathClients);
key.append(L"\\");
key.append(guid_);
if (client_util::GetChromiumVersion(dll_path_, key.c_str(), &version_))
ret = true;
}
}
if (version_) {
::StringCchCat(dll_path_, MAX_PATH, version_);
}
return ret;
}
} // namespace google_update
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/nacl_ui.h"
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/plugins/webplugininfo.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
using content::PluginService;
using content::UserMetricsAction;
using content::WebUIMessageHandler;
namespace {
content::WebUIDataSource* CreateNaClUIHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUINaClHost);
source->SetUseJsonJSFormatV2();
source->AddLocalizedString("loadingMessage", IDS_NACL_LOADING_MESSAGE);
source->AddLocalizedString("naclLongTitle", IDS_NACL_TITLE_MESSAGE);
source->SetJsonPath("strings.js");
source->AddResourcePath("about_nacl.css", IDR_ABOUT_NACL_CSS);
source->AddResourcePath("about_nacl.js", IDR_ABOUT_NACL_JS);
source->SetDefaultResource(IDR_ABOUT_NACL_HTML);
return source;
}
////////////////////////////////////////////////////////////////////////////////
//
// NaClDOMHandler
//
////////////////////////////////////////////////////////////////////////////////
// The handler for JavaScript messages for the about:flags page.
class NaClDOMHandler : public WebUIMessageHandler {
public:
NaClDOMHandler();
virtual ~NaClDOMHandler();
// WebUIMessageHandler implementation.
virtual void RegisterMessages() OVERRIDE;
// Callback for the "requestNaClInfo" message.
void HandleRequestNaClInfo(const ListValue* args);
// Callback for the NaCl plugin information.
void OnGotPlugins(const std::vector<webkit::WebPluginInfo>& plugins);
private:
// Called when enough information is gathered to return data back to the page.
void MaybeRespondToPage();
// Helper for MaybeRespondToPage -- called after enough information
// is gathered.
void PopulatePageInformation(DictionaryValue* naclInfo);
// Factory for the creating refs in callbacks.
base::WeakPtrFactory<NaClDOMHandler> weak_ptr_factory_;
// Whether the page has requested data.
bool page_has_requested_data_;
// Whether the plugin information is ready.
bool has_plugin_info_;
DISALLOW_COPY_AND_ASSIGN(NaClDOMHandler);
};
NaClDOMHandler::NaClDOMHandler()
: weak_ptr_factory_(this),
page_has_requested_data_(false),
has_plugin_info_(false) {
PluginService::GetInstance()->GetPlugins(base::Bind(
&NaClDOMHandler::OnGotPlugins, weak_ptr_factory_.GetWeakPtr()));
}
NaClDOMHandler::~NaClDOMHandler() {
}
void NaClDOMHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"requestNaClInfo",
base::Bind(&NaClDOMHandler::HandleRequestNaClInfo,
base::Unretained(this)));
}
// Helper functions for collecting a list of key-value pairs that will
// be displayed.
void AddPair(ListValue* list, const string16& key, const string16& value) {
DictionaryValue* results = new DictionaryValue();
results->SetString("key", key);
results->SetString("value", value);
list->Append(results);
}
// Generate an empty data-pair which acts as a line break.
void AddLineBreak(ListValue* list) {
AddPair(list, ASCIIToUTF16(""), ASCIIToUTF16(""));
}
// Check whether a commandline switch is turned on or off.
void ListFlagStatus(ListValue* list, const std::string& flag_label,
const std::string& flag_name) {
if (CommandLine::ForCurrentProcess()->HasSwitch(flag_name))
AddPair(list, ASCIIToUTF16(flag_label), ASCIIToUTF16("On"));
else
AddPair(list, ASCIIToUTF16(flag_label), ASCIIToUTF16("Off"));
}
void NaClDOMHandler::HandleRequestNaClInfo(const ListValue* args) {
page_has_requested_data_ = true;
MaybeRespondToPage();
}
void NaClDOMHandler::OnGotPlugins(
const std::vector<webkit::WebPluginInfo>& plugins) {
has_plugin_info_ = true;
MaybeRespondToPage();
}
void NaClDOMHandler::PopulatePageInformation(DictionaryValue* naclInfo) {
// Store Key-Value pairs of about-information.
scoped_ptr<ListValue> list(new ListValue());
// Obtain the Chrome version info.
chrome::VersionInfo version_info;
AddPair(list.get(),
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
ASCIIToUTF16(version_info.Version() + " (" +
chrome::VersionInfo::GetVersionStringModifier() + ")"));
// OS version information.
// TODO(jvoung): refactor this to share the extra windows labeling
// with about:flash, or something.
std::string os_label = version_info.OSType();
#if defined(OS_WIN)
base::win::OSInfo* os = base::win::OSInfo::GetInstance();
switch (os->version()) {
case base::win::VERSION_XP: os_label += " XP"; break;
case base::win::VERSION_SERVER_2003:
os_label += " Server 2003 or XP Pro 64 bit";
break;
case base::win::VERSION_VISTA: os_label += " Vista or Server 2008"; break;
case base::win::VERSION_WIN7: os_label += " 7 or Server 2008 R2"; break;
case base::win::VERSION_WIN8: os_label += " 8 or Server 2012"; break;
default: os_label += " UNKNOWN"; break;
}
os_label += " SP" + base::IntToString(os->service_pack().major);
if (os->service_pack().minor > 0)
os_label += "." + base::IntToString(os->service_pack().minor);
if (os->architecture() == base::win::OSInfo::X64_ARCHITECTURE)
os_label += " 64 bit";
#endif
AddPair(list.get(),
l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_OS),
ASCIIToUTF16(os_label));
AddLineBreak(list.get());
// Obtain the version of the NaCl plugin.
std::vector<webkit::WebPluginInfo> info_array;
PluginService::GetInstance()->GetPluginInfoArray(
GURL(), "application/x-nacl", false, &info_array, NULL);
string16 nacl_version;
string16 nacl_key = ASCIIToUTF16("NaCl plugin");
if (info_array.empty()) {
AddPair(list.get(), nacl_key, ASCIIToUTF16("Disabled"));
} else {
PluginPrefs* plugin_prefs =
PluginPrefs::GetForProfile(Profile::FromWebUI(web_ui()));
// Only the 0th plugin is used.
nacl_version = info_array[0].version + ASCIIToUTF16(" ") +
info_array[0].path.LossyDisplayName();
if (!plugin_prefs->IsPluginEnabled(info_array[0])) {
nacl_version += ASCIIToUTF16(" (Disabled in profile prefs)");
AddPair(list.get(), nacl_key, nacl_version);
}
AddPair(list.get(), nacl_key, nacl_version);
// Mark the rest as not used.
for (size_t i = 1; i < info_array.size(); ++i) {
nacl_version = info_array[i].version + ASCIIToUTF16(" ") +
info_array[i].path.LossyDisplayName();
nacl_version += ASCIIToUTF16(" (not used)");
if (!plugin_prefs->IsPluginEnabled(info_array[i]))
nacl_version += ASCIIToUTF16(" (Disabled in profile prefs)");
AddPair(list.get(), nacl_key, nacl_version);
}
}
// Check that commandline flags are enabled.
ListFlagStatus(list.get(), "Flag '--enable-nacl'", switches::kEnableNaCl);
AddLineBreak(list.get());
// Obtain the version of the PNaCl translator.
base::FilePath pnacl_path;
bool got_path = PathService::Get(chrome::DIR_PNACL_COMPONENT, &pnacl_path);
// The PathService may return an empty string if PNaCl is not yet installed.
// However, do not trust that the path returned by the PathService exists.
// Check for existence here.
if (!got_path || pnacl_path.empty() || !file_util::PathExists(pnacl_path)) {
AddPair(list.get(),
ASCIIToUTF16("PNaCl translator"),
ASCIIToUTF16("Not installed"));
} else {
AddPair(list.get(),
ASCIIToUTF16("PNaCl translator path"),
pnacl_path.LossyDisplayName());
AddPair(list.get(),
ASCIIToUTF16("PNaCl translator version"),
pnacl_path.BaseName().LossyDisplayName());
}
ListFlagStatus(list.get(), "Flag '--enable-pnacl'", switches::kEnablePnacl);
// naclInfo will take ownership of list, and clean it up on destruction.
naclInfo->Set("naclInfo", list.release());
}
void NaClDOMHandler::MaybeRespondToPage() {
// Don't reply until everything is ready. The page will show a 'loading'
// message until then.
if (!page_has_requested_data_ || !has_plugin_info_)
return;
DictionaryValue naclInfo;
PopulatePageInformation(&naclInfo);
web_ui()->CallJavascriptFunction("nacl.returnNaClInfo", naclInfo);
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
//
// NaClUI
//
///////////////////////////////////////////////////////////////////////////////
NaClUI::NaClUI(content::WebUI* web_ui) : WebUIController(web_ui) {
content::RecordAction(UserMetricsAction("ViewAboutNaCl"));
web_ui->AddMessageHandler(new NaClDOMHandler());
// Set up the about:nacl source.
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource::Add(profile, CreateNaClUIHTMLSource());
}
<commit_msg>chrome://nacl asserts<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/nacl_ui.h"
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/weak_ptr.h"
#include "base/path_service.h"
#include "base/string16.h"
#include "base/strings/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/plugins/webplugininfo.h"
#if defined(OS_WIN)
#include "base/win/windows_version.h"
#endif
using content::BrowserThread;
using content::PluginService;
using content::UserMetricsAction;
using content::WebUIMessageHandler;
namespace {
content::WebUIDataSource* CreateNaClUIHTMLSource() {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUINaClHost);
source->SetUseJsonJSFormatV2();
source->AddLocalizedString("loadingMessage", IDS_NACL_LOADING_MESSAGE);
source->AddLocalizedString("naclLongTitle", IDS_NACL_TITLE_MESSAGE);
source->SetJsonPath("strings.js");
source->AddResourcePath("about_nacl.css", IDR_ABOUT_NACL_CSS);
source->AddResourcePath("about_nacl.js", IDR_ABOUT_NACL_JS);
source->SetDefaultResource(IDR_ABOUT_NACL_HTML);
return source;
}
////////////////////////////////////////////////////////////////////////////////
//
// NaClDOMHandler
//
////////////////////////////////////////////////////////////////////////////////
class NaClDOMHandler;
// This class performs a check that the PNaCl path which was returned by
// PathService is valid. One class instance is created per NaClDOMHandler
// and it is destroyed after the check is completed.
class NaClDOMHandlerProxy : public
base::RefCountedThreadSafe<NaClDOMHandlerProxy> {
public:
explicit NaClDOMHandlerProxy(NaClDOMHandler* handler);
// A helper to check if PNaCl path exists.
void ValidatePnaclPath();
void set_handler(NaClDOMHandler* handler) {
handler_ = handler;
}
private:
// A helper callback that receives the result of checking if PNaCl path
// exists.
void ValidatePnaclPathCallback(bool is_valid);
virtual ~NaClDOMHandlerProxy() {}
friend class base::RefCountedThreadSafe<NaClDOMHandlerProxy>;
// The handler that requested checking PNaCl file path.
NaClDOMHandler* handler_;
DISALLOW_COPY_AND_ASSIGN(NaClDOMHandlerProxy);
};
// The handler for JavaScript messages for the about:flags page.
class NaClDOMHandler : public WebUIMessageHandler {
public:
NaClDOMHandler();
virtual ~NaClDOMHandler();
// WebUIMessageHandler implementation.
virtual void RegisterMessages() OVERRIDE;
// Callback for the "requestNaClInfo" message.
void HandleRequestNaClInfo(const ListValue* args);
// Callback for the NaCl plugin information.
void OnGotPlugins(const std::vector<webkit::WebPluginInfo>& plugins);
// A helper callback that receives the result of checking if PNaCl path
// exists. is_valid is true if the PNaCl path that was returned by
// PathService is valid, and false otherwise.
void DidValidatePnaclPath(bool is_valid);
private:
// Called when enough information is gathered to return data back to the page.
void MaybeRespondToPage();
// Helper for MaybeRespondToPage -- called after enough information
// is gathered.
void PopulatePageInformation(DictionaryValue* naclInfo);
// Factory for the creating refs in callbacks.
base::WeakPtrFactory<NaClDOMHandler> weak_ptr_factory_;
// Whether the page has requested data.
bool page_has_requested_data_;
// Whether the plugin information is ready.
bool has_plugin_info_;
// Whether PNaCl path was validated. PathService can return a path
// that does not exists, so it needs to be validated.
bool pnacl_path_validated_;
bool pnacl_path_exists_;
// A proxy for handling cross threads messages.
scoped_refptr<NaClDOMHandlerProxy> proxy_;
DISALLOW_COPY_AND_ASSIGN(NaClDOMHandler);
};
NaClDOMHandlerProxy::NaClDOMHandlerProxy(NaClDOMHandler* handler)
: handler_(handler) {
}
void NaClDOMHandlerProxy::ValidatePnaclPath() {
if (!BrowserThread::CurrentlyOn(BrowserThread::FILE)) {
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&NaClDOMHandlerProxy::ValidatePnaclPath, this));
return;
}
bool is_valid = true;
base::FilePath pnacl_path;
bool got_path = PathService::Get(chrome::DIR_PNACL_COMPONENT, &pnacl_path);
// The PathService may return an empty string if PNaCl is not yet installed.
// However, do not trust that the path returned by the PathService exists.
// Check for existence here.
if (!got_path || pnacl_path.empty() || !file_util::PathExists(pnacl_path)) {
is_valid = false;
}
ValidatePnaclPathCallback(is_valid);
}
void NaClDOMHandlerProxy::ValidatePnaclPathCallback(bool is_valid) {
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&NaClDOMHandlerProxy::ValidatePnaclPathCallback,
this, is_valid));
return;
}
// Check that handler_ is still valid, it could be set to NULL if navigation
// happened while checking that the PNaCl file exists.
if (handler_)
handler_->DidValidatePnaclPath(is_valid);
}
NaClDOMHandler::NaClDOMHandler()
: weak_ptr_factory_(this),
page_has_requested_data_(false),
has_plugin_info_(false),
pnacl_path_validated_(false),
pnacl_path_exists_(false),
proxy_(new NaClDOMHandlerProxy(this)) {
PluginService::GetInstance()->GetPlugins(base::Bind(
&NaClDOMHandler::OnGotPlugins, weak_ptr_factory_.GetWeakPtr()));
}
NaClDOMHandler::~NaClDOMHandler() {
if (proxy_)
proxy_->set_handler(NULL);
}
void NaClDOMHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback(
"requestNaClInfo",
base::Bind(&NaClDOMHandler::HandleRequestNaClInfo,
base::Unretained(this)));
}
// Helper functions for collecting a list of key-value pairs that will
// be displayed.
void AddPair(ListValue* list, const string16& key, const string16& value) {
DictionaryValue* results = new DictionaryValue();
results->SetString("key", key);
results->SetString("value", value);
list->Append(results);
}
// Generate an empty data-pair which acts as a line break.
void AddLineBreak(ListValue* list) {
AddPair(list, ASCIIToUTF16(""), ASCIIToUTF16(""));
}
// Check whether a commandline switch is turned on or off.
void ListFlagStatus(ListValue* list, const std::string& flag_label,
const std::string& flag_name) {
if (CommandLine::ForCurrentProcess()->HasSwitch(flag_name))
AddPair(list, ASCIIToUTF16(flag_label), ASCIIToUTF16("On"));
else
AddPair(list, ASCIIToUTF16(flag_label), ASCIIToUTF16("Off"));
}
void NaClDOMHandler::HandleRequestNaClInfo(const ListValue* args) {
page_has_requested_data_ = true;
MaybeRespondToPage();
}
void NaClDOMHandler::OnGotPlugins(
const std::vector<webkit::WebPluginInfo>& plugins) {
has_plugin_info_ = true;
MaybeRespondToPage();
}
void NaClDOMHandler::PopulatePageInformation(DictionaryValue* naclInfo) {
DCHECK(pnacl_path_validated_);
// Store Key-Value pairs of about-information.
scoped_ptr<ListValue> list(new ListValue());
// Obtain the Chrome version info.
chrome::VersionInfo version_info;
AddPair(list.get(),
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
ASCIIToUTF16(version_info.Version() + " (" +
chrome::VersionInfo::GetVersionStringModifier() + ")"));
// OS version information.
// TODO(jvoung): refactor this to share the extra windows labeling
// with about:flash, or something.
std::string os_label = version_info.OSType();
#if defined(OS_WIN)
base::win::OSInfo* os = base::win::OSInfo::GetInstance();
switch (os->version()) {
case base::win::VERSION_XP: os_label += " XP"; break;
case base::win::VERSION_SERVER_2003:
os_label += " Server 2003 or XP Pro 64 bit";
break;
case base::win::VERSION_VISTA: os_label += " Vista or Server 2008"; break;
case base::win::VERSION_WIN7: os_label += " 7 or Server 2008 R2"; break;
case base::win::VERSION_WIN8: os_label += " 8 or Server 2012"; break;
default: os_label += " UNKNOWN"; break;
}
os_label += " SP" + base::IntToString(os->service_pack().major);
if (os->service_pack().minor > 0)
os_label += "." + base::IntToString(os->service_pack().minor);
if (os->architecture() == base::win::OSInfo::X64_ARCHITECTURE)
os_label += " 64 bit";
#endif
AddPair(list.get(),
l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_OS),
ASCIIToUTF16(os_label));
AddLineBreak(list.get());
// Obtain the version of the NaCl plugin.
std::vector<webkit::WebPluginInfo> info_array;
PluginService::GetInstance()->GetPluginInfoArray(
GURL(), "application/x-nacl", false, &info_array, NULL);
string16 nacl_version;
string16 nacl_key = ASCIIToUTF16("NaCl plugin");
if (info_array.empty()) {
AddPair(list.get(), nacl_key, ASCIIToUTF16("Disabled"));
} else {
PluginPrefs* plugin_prefs =
PluginPrefs::GetForProfile(Profile::FromWebUI(web_ui()));
// Only the 0th plugin is used.
nacl_version = info_array[0].version + ASCIIToUTF16(" ") +
info_array[0].path.LossyDisplayName();
if (!plugin_prefs->IsPluginEnabled(info_array[0])) {
nacl_version += ASCIIToUTF16(" (Disabled in profile prefs)");
AddPair(list.get(), nacl_key, nacl_version);
}
AddPair(list.get(), nacl_key, nacl_version);
// Mark the rest as not used.
for (size_t i = 1; i < info_array.size(); ++i) {
nacl_version = info_array[i].version + ASCIIToUTF16(" ") +
info_array[i].path.LossyDisplayName();
nacl_version += ASCIIToUTF16(" (not used)");
if (!plugin_prefs->IsPluginEnabled(info_array[i]))
nacl_version += ASCIIToUTF16(" (Disabled in profile prefs)");
AddPair(list.get(), nacl_key, nacl_version);
}
}
// Check that commandline flags are enabled.
ListFlagStatus(list.get(), "Flag '--enable-nacl'", switches::kEnableNaCl);
AddLineBreak(list.get());
// Obtain the version of the PNaCl translator.
base::FilePath pnacl_path;
bool got_path = PathService::Get(chrome::DIR_PNACL_COMPONENT, &pnacl_path);
if (!got_path || pnacl_path.empty() || !pnacl_path_exists_) {
AddPair(list.get(),
ASCIIToUTF16("PNaCl translator"),
ASCIIToUTF16("Not installed"));
} else {
AddPair(list.get(),
ASCIIToUTF16("PNaCl translator path"),
pnacl_path.LossyDisplayName());
AddPair(list.get(),
ASCIIToUTF16("PNaCl translator version"),
pnacl_path.BaseName().LossyDisplayName());
}
ListFlagStatus(list.get(), "Flag '--enable-pnacl'", switches::kEnablePnacl);
// naclInfo will take ownership of list, and clean it up on destruction.
naclInfo->Set("naclInfo", list.release());
}
void NaClDOMHandler::DidValidatePnaclPath(bool is_valid) {
pnacl_path_validated_ = true;
pnacl_path_exists_ = is_valid;
MaybeRespondToPage();
}
void NaClDOMHandler::MaybeRespondToPage() {
// Don't reply until everything is ready. The page will show a 'loading'
// message until then.
if (!page_has_requested_data_ || !has_plugin_info_)
return;
if (!pnacl_path_validated_) {
DCHECK(proxy_);
proxy_->ValidatePnaclPath();
return;
}
DictionaryValue naclInfo;
PopulatePageInformation(&naclInfo);
web_ui()->CallJavascriptFunction("nacl.returnNaClInfo", naclInfo);
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
//
// NaClUI
//
///////////////////////////////////////////////////////////////////////////////
NaClUI::NaClUI(content::WebUI* web_ui) : WebUIController(web_ui) {
content::RecordAction(UserMetricsAction("ViewAboutNaCl"));
web_ui->AddMessageHandler(new NaClDOMHandler());
// Set up the about:nacl source.
Profile* profile = Profile::FromWebUI(web_ui);
content::WebUIDataSource::Add(profile, CreateNaClUIHTMLSource());
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: osl_Socket_tests.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: pjunck $ $Date: 2004-11-02 14:56:21 $
*
* 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,
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
//------------------------------------------------------------------------
// include files
//------------------------------------------------------------------------
#ifndef _OSL_SOCKET_CONST_H_
#include <osl_Socket_Const.h>
#endif
#include <cppunit/simpleheader.hxx>
#ifndef _OSL_SOCKET_HXX_
#include <osl/socket.hxx>
#endif
//------------------------------------------------------------------------
// helper functions
//------------------------------------------------------------------------
//------------------------------------------------------------------------
// tests cases begins here
//------------------------------------------------------------------------
namespace osl_Socket
{
class tests : public CppUnit::TestFixture
{
public:
void test_001()
{
// _osl_getFullQualifiedDomainName( );
oslSocketResult aResult;
rtl::OUString suHostname = osl::SocketAddr::getLocalHostname(&aResult);
volatile int dummy = 0;
CPPUNIT_ASSERT_MESSAGE("getLocalHostname failed", aResult == osl_Socket_Ok);
}
// -----------------------------------------------------------------------------
#if defined UNX
/*
void getHostname_003()
{
struct hostent *pQualifiedHostByName;
struct hostent *pHostByName;
struct hostent aHostByName, aQualifiedHostByName;
sal_Char pHostBuffer[ 2000 ];
sal_Char pQualifiedHostBuffer[ 2560 ];
int nErrorNo;
pHostBuffer[0] = '\0';
pQualifiedHostBuffer[0] = '\0';
gethostbyname_r ("sceri.PRC.Sun.COM", &aQualifiedHostByName, pQualifiedHostBuffer, sizeof(pQualifiedHostBuffer), &pQualifiedHostByName, &nErrorNo);
// gethostbyname_r ("grande.germany.Sun.COM", &aQualifiedHostByName, pQualifiedHostBuffer, sizeof(pQualifiedHostBuffer), &pQualifiedHostByName, &nErrorNo);
gethostbyname_r ("longshot.PRC.Sun.COM", &aHostByName, pHostBuffer, sizeof(pHostBuffer), &pHostByName, &nErrorNo);
if ( pQualifiedHostByName )
t_print("# getHostname_003: QualifiedHostByName!\n" );
if ( pHostByName )
t_print("# getHostname_003: HostByName!\n" );
}
*/
void getHostname_001()
{
struct hostent *pQualifiedHostByName;
struct hostent *pHostByName;
struct hostent *pQualifiedHostByName1;
struct hostent *pHostByName1;
struct hostent aHostByName, aQualifiedHostByName, aHostByName1, aQualifiedHostByName1;
char pHostBuffer[ 256 ];
char pQualifiedHostBuffer[ 256 ];
char pHostBuffer1[ 2000 ];
char pQualifiedHostBuffer1[ 2000 ];
int nErrorNo;
pHostBuffer[0] = '\0';
pQualifiedHostBuffer[0] = '\0';
pHostBuffer1[0] = '\0';
pQualifiedHostBuffer1[0] = '\0';
gethostbyname_r ("grande.Germany.Sun.COM", &aQualifiedHostByName, pQualifiedHostBuffer, sizeof(pQualifiedHostBuffer), &pQualifiedHostByName, &nErrorNo);
gethostbyname_r ("longshot.PRC.Sun.COM", &aHostByName, pHostBuffer, sizeof(pHostBuffer), &pHostByName, &nErrorNo);
gethostbyname_r ("grande.Germany.Sun.COM", &aQualifiedHostByName1, pQualifiedHostBuffer1, sizeof(pQualifiedHostBuffer1), &pQualifiedHostByName1, &nErrorNo);
gethostbyname_r ("longshot.PRC.Sun.COM", &aHostByName1, pHostBuffer1, sizeof(pHostBuffer1), &pHostByName1, &nErrorNo);
if ( pQualifiedHostByName )
printf( "# QualifiedHostByName got if size is 256!\n" );
if ( pHostByName )
printf( "# HostByName got if size is 256!\n" );
if ( pQualifiedHostByName1 )
printf( "# QualifiedHostByName got if size is 2000!\n" );
if ( pHostByName1 )
printf( "# HostByName got if size is 2000!\n" );
}
#endif
CPPUNIT_TEST_SUITE( tests );
CPPUNIT_TEST( test_001 );
//CPPUNIT_TEST( getHostname_003 );
CPPUNIT_TEST( getHostname_001 );
CPPUNIT_TEST_SUITE_END();
};
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::tests, "osl_SocketTest");
}
// -----------------------------------------------------------------------------
// this macro creates an empty function, which will called by the RegisterAllFunctions()
// to let the user the possibility to also register some functions by hand.
/*#if (defined LINUX)
void RegisterAdditionalFunctions( FktRegFuncPtr _pFunc )
{
// for cover lines in _osl_getFullQualifiedDomainName( )
// STAR_OVERRIDE_DOMAINNAME is more an internal HACK for 5.2, which should remove from sal
setenv( "STAR_OVERRIDE_DOMAINNAME", "PRC.Sun.COM", 0 );
}
#else*/
NOADDITIONAL;
//#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.96); FILE MERGED 2005/09/05 17:44:58 rt 1.4.96.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: osl_Socket_tests.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:40:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
//------------------------------------------------------------------------
// include files
//------------------------------------------------------------------------
#ifndef _OSL_SOCKET_CONST_H_
#include <osl_Socket_Const.h>
#endif
#include <cppunit/simpleheader.hxx>
#ifndef _OSL_SOCKET_HXX_
#include <osl/socket.hxx>
#endif
//------------------------------------------------------------------------
// helper functions
//------------------------------------------------------------------------
//------------------------------------------------------------------------
// tests cases begins here
//------------------------------------------------------------------------
namespace osl_Socket
{
class tests : public CppUnit::TestFixture
{
public:
void test_001()
{
// _osl_getFullQualifiedDomainName( );
oslSocketResult aResult;
rtl::OUString suHostname = osl::SocketAddr::getLocalHostname(&aResult);
volatile int dummy = 0;
CPPUNIT_ASSERT_MESSAGE("getLocalHostname failed", aResult == osl_Socket_Ok);
}
// -----------------------------------------------------------------------------
#if defined UNX
/*
void getHostname_003()
{
struct hostent *pQualifiedHostByName;
struct hostent *pHostByName;
struct hostent aHostByName, aQualifiedHostByName;
sal_Char pHostBuffer[ 2000 ];
sal_Char pQualifiedHostBuffer[ 2560 ];
int nErrorNo;
pHostBuffer[0] = '\0';
pQualifiedHostBuffer[0] = '\0';
gethostbyname_r ("sceri.PRC.Sun.COM", &aQualifiedHostByName, pQualifiedHostBuffer, sizeof(pQualifiedHostBuffer), &pQualifiedHostByName, &nErrorNo);
// gethostbyname_r ("grande.germany.Sun.COM", &aQualifiedHostByName, pQualifiedHostBuffer, sizeof(pQualifiedHostBuffer), &pQualifiedHostByName, &nErrorNo);
gethostbyname_r ("longshot.PRC.Sun.COM", &aHostByName, pHostBuffer, sizeof(pHostBuffer), &pHostByName, &nErrorNo);
if ( pQualifiedHostByName )
t_print("# getHostname_003: QualifiedHostByName!\n" );
if ( pHostByName )
t_print("# getHostname_003: HostByName!\n" );
}
*/
void getHostname_001()
{
struct hostent *pQualifiedHostByName;
struct hostent *pHostByName;
struct hostent *pQualifiedHostByName1;
struct hostent *pHostByName1;
struct hostent aHostByName, aQualifiedHostByName, aHostByName1, aQualifiedHostByName1;
char pHostBuffer[ 256 ];
char pQualifiedHostBuffer[ 256 ];
char pHostBuffer1[ 2000 ];
char pQualifiedHostBuffer1[ 2000 ];
int nErrorNo;
pHostBuffer[0] = '\0';
pQualifiedHostBuffer[0] = '\0';
pHostBuffer1[0] = '\0';
pQualifiedHostBuffer1[0] = '\0';
gethostbyname_r ("grande.Germany.Sun.COM", &aQualifiedHostByName, pQualifiedHostBuffer, sizeof(pQualifiedHostBuffer), &pQualifiedHostByName, &nErrorNo);
gethostbyname_r ("longshot.PRC.Sun.COM", &aHostByName, pHostBuffer, sizeof(pHostBuffer), &pHostByName, &nErrorNo);
gethostbyname_r ("grande.Germany.Sun.COM", &aQualifiedHostByName1, pQualifiedHostBuffer1, sizeof(pQualifiedHostBuffer1), &pQualifiedHostByName1, &nErrorNo);
gethostbyname_r ("longshot.PRC.Sun.COM", &aHostByName1, pHostBuffer1, sizeof(pHostBuffer1), &pHostByName1, &nErrorNo);
if ( pQualifiedHostByName )
printf( "# QualifiedHostByName got if size is 256!\n" );
if ( pHostByName )
printf( "# HostByName got if size is 256!\n" );
if ( pQualifiedHostByName1 )
printf( "# QualifiedHostByName got if size is 2000!\n" );
if ( pHostByName1 )
printf( "# HostByName got if size is 2000!\n" );
}
#endif
CPPUNIT_TEST_SUITE( tests );
CPPUNIT_TEST( test_001 );
//CPPUNIT_TEST( getHostname_003 );
CPPUNIT_TEST( getHostname_001 );
CPPUNIT_TEST_SUITE_END();
};
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(osl_Socket::tests, "osl_SocketTest");
}
// -----------------------------------------------------------------------------
// this macro creates an empty function, which will called by the RegisterAllFunctions()
// to let the user the possibility to also register some functions by hand.
/*#if (defined LINUX)
void RegisterAdditionalFunctions( FktRegFuncPtr _pFunc )
{
// for cover lines in _osl_getFullQualifiedDomainName( )
// STAR_OVERRIDE_DOMAINNAME is more an internal HACK for 5.2, which should remove from sal
setenv( "STAR_OVERRIDE_DOMAINNAME", "PRC.Sun.COM", 0 );
}
#else*/
NOADDITIONAL;
//#endif
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2018)
#ifndef DUNE_GDT_LOCAL_INTEGRANDS_ABS_HH
#define DUNE_GDT_LOCAL_INTEGRANDS_ABS_HH
#include <cmath>
#include "interfaces.hh"
namespace Dune {
namespace GDT {
template <class E, size_t r = 1, size_t rC = 1, class R = double, class F = double>
class LocalElementAbsIntegrand : public LocalUnaryElementIntegrandInterface<E, r, rC, R, F>
{
using ThisType = LocalElementAbsIntegrand<E, r, rC, R, F>;
using BaseType = LocalUnaryElementIntegrandInterface<E, r, rC, R, F>;
public:
using typename BaseType::LocalBasisType;
using typename BaseType::DomainType;
std::unique_ptr<BaseType> copy() const
{
return std::make_unique<ThisType>();
}
int order(const LocalBasisType& basis, const XT::Common::Parameter& param = {}) const
{
return basis.order(param);
}
using BaseType::evaluate;
void evaluate(const LocalBasisType& basis,
const DomainType& point_in_reference_element,
DynamicVector<F>& result,
const XT::Common::Parameter& param = {}) const
{
// prepare storage
const size_t size = basis.size(param);
if (result.size() < size)
result.resize(size);
// evaluate
basis.evaluate(point_in_reference_element, basis_values_, param);
// compute integrand
using std::abs;
for (size_t ii = 0; ii < size; ++ii)
result[ii] = abs(basis_values_[ii]);
} // ... evaluate(...)
private:
mutable std::vector<typename LocalBasisType::RangeType> basis_values_;
}; // class LocalElementAbsIntegrand
} // namespace GDT
} // namespace Dun
#endif // DUNE_GDT_LOCAL_INTEGRANDS_ABS_HH
<commit_msg>[local.integrand.abs] enable vector-valued case<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2018)
#ifndef DUNE_GDT_LOCAL_INTEGRANDS_ABS_HH
#define DUNE_GDT_LOCAL_INTEGRANDS_ABS_HH
#include <cmath>
#include "interfaces.hh"
namespace Dune {
namespace GDT {
template <class E, size_t r = 1, size_t rC = 1, class R = double, class F = double>
class LocalElementAbsIntegrand : public LocalUnaryElementIntegrandInterface<E, r, rC, R, F>
{
static_assert(rC == 1, "");
using ThisType = LocalElementAbsIntegrand<E, r, rC, R, F>;
using BaseType = LocalUnaryElementIntegrandInterface<E, r, rC, R, F>;
public:
using typename BaseType::LocalBasisType;
using typename BaseType::DomainType;
std::unique_ptr<BaseType> copy() const
{
return std::make_unique<ThisType>();
}
int order(const LocalBasisType& basis, const XT::Common::Parameter& param = {}) const
{
return basis.order(param);
}
using BaseType::evaluate;
void evaluate(const LocalBasisType& basis,
const DomainType& point_in_reference_element,
DynamicVector<F>& result,
const XT::Common::Parameter& param = {}) const
{
// prepare storage
const size_t size = basis.size(param);
if (result.size() < size)
result.resize(size);
// evaluate
basis.evaluate(point_in_reference_element, basis_values_, param);
// compute integrand
for (size_t ii = 0; ii < size; ++ii)
result[ii] = basis_values_[ii].two_norm();
} // ... evaluate(...)
private:
mutable std::vector<typename LocalBasisType::RangeType> basis_values_;
}; // class LocalElementAbsIntegrand
} // namespace GDT
} // namespace Dun
#endif // DUNE_GDT_LOCAL_INTEGRANDS_ABS_HH
<|endoftext|>
|
<commit_before>// This file is part of the dune-stuff project:
// http://users.dune-project.org/projects/dune-stuff/
// Copyright Holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
# include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
# include "config.h"
#endif
#include "constant.hh"
namespace Dune {
namespace Stuff {
namespace Function {
// ====================
// ===== Constant =====
// ====================
template< class E, class D, int d, class R, int r >
std::string Constant< E, D, d, R, r >::static_id()
{
return BaseType::static_id() + ".constant";
}
template< class E, class D, int d, class R, int r >
Dune::ParameterTree Constant< E, D, d, R, r >::defaultSettings(const std::string subName)
{
Dune::ParameterTree description;
description["value"] = "1.0";
if (subName.empty())
return description;
else {
Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
extendedDescription.add(description, subName);
return extendedDescription;
}
} // ... defaultSettings(...)
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType* create(const DSC::ExtendedParameterTree settings)
{
typedef typename Constant< E, D, d, R, r >::ThisType ThisType;
typedef typename Constant< E, D, d, R, r >::RangeFieldType RangeFieldType;
return new ThisType(settings.get< RangeFieldType >("value", RangeFieldType(0)));
} // ... create(...)
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const RangeFieldType& val, const std::string nm)
: value_(std::make_shared< RangeType >(val))
, name_(nm)
{}
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const RangeType& val, const std::string nm)
: value_(std::make_shared< RangeType >(val))
, name_(nm)
{}
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const ThisType& other)
: value_(other.value_)
, name_(other.name_)
{}
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType& Constant< E, D, d, R, r >::operator=(const ThisType& other)
{
if (this != &other) {
value_ = other.value_;
name_ = other.name_;
}
return *this;
}
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType* Constant< E, D, d, R, r >::copy() const
{
return new ThisType(*this);
}
template< class E, class D, int d, class R, int r >
std::string Constant< E, D, d, R, r >::name() const
{
return name_;
}
template< class E, class D, int d, class R, int r >
std::unique_ptr< typename Constant< E, D, d, R, r >::LocalfunctionType >
Constant< E, D, d, R, r >::local_function(const EntityType& entity) const
{
return std::unique_ptr< Localfunction >(new Localfunction(entity, value_));
}
} // namespace Function
} // namespace Stuff
} // namespace Dune
#include <dune/stuff/grid/fakeentity.hh>
typedef Dune::Stuff::Grid::FakeEntity< 1 > DuneStuffFake1dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 2 > DuneStuffFake2dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 3 > DuneStuffFake3dEntityType;
template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 3 >;
//#ifdef HAVE_DUNE_GRID
//# include <dune/grid/sgrid.hh>
//typedef typename Dune::SGrid< 1, 1 >::template Codim< 0 >::Entity DuneSGrid1dEntityType;
//typedef typename Dune::SGrid< 2, 2 >::template Codim< 0 >::Entity DuneSGrid2dEntityType;
//typedef typename Dune::SGrid< 3, 3 >::template Codim< 0 >::Entity DuneSGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 3 >;
//# include <dune/grid/yaspgrid.hh>
//typedef typename Dune::YaspGrid< 1 >::template Codim< 0 >::Entity DuneYaspGrid1dEntityType;
//typedef typename Dune::YaspGrid< 2 >::template Codim< 0 >::Entity DuneYaspGrid2dEntityType;
//typedef typename Dune::YaspGrid< 3 >::template Codim< 0 >::Entity DuneYaspGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 3 >;
//# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
//# define ALUGRID_CONFORM 1
//# define ENABLE_ALUGRID 1
//# include <dune/grid/alugrid.hh>
//typedef typename Dune::ALUSimplexGrid< 2, 2 >::template Codim< 0 >::Entity DuneAluSimplexGrid2dEntityType;
//typedef typename Dune::ALUSimplexGrid< 3, 3 >::template Codim< 0 >::Entity DuneAluSimplexGrid3dEntityType;
//typedef typename Dune::ALUCubeGrid< 3, 3 >::template Codim< 0 >::Entity DuneAluCubeGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 3 >;
//# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
//#endif // HAVE_DUNE_GRID
<commit_msg>fix "create" defining a new function<commit_after>// This file is part of the dune-stuff project:
// http://users.dune-project.org/projects/dune-stuff/
// Copyright Holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifdef HAVE_CMAKE_CONFIG
# include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
# include "config.h"
#endif
#include "constant.hh"
namespace Dune {
namespace Stuff {
namespace Function {
// ====================
// ===== Constant =====
// ====================
template< class E, class D, int d, class R, int r >
std::string Constant< E, D, d, R, r >::static_id()
{
return BaseType::static_id() + ".constant";
}
template< class E, class D, int d, class R, int r >
Dune::ParameterTree Constant< E, D, d, R, r >::defaultSettings(const std::string subName)
{
Dune::ParameterTree description;
description["value"] = "1.0";
if (subName.empty())
return description;
else {
Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
extendedDescription.add(description, subName);
return extendedDescription;
}
} // ... defaultSettings(...)
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType* Constant< E, D, d, R, r >::create(const DSC::ExtendedParameterTree settings)
{
typedef typename Constant< E, D, d, R, r >::ThisType ThisType;
typedef typename Constant< E, D, d, R, r >::RangeFieldType RangeFieldType;
return new ThisType(settings.get< RangeFieldType >("value", RangeFieldType(0)));
} // ... create(...)
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const RangeFieldType& val, const std::string nm)
: value_(std::make_shared< RangeType >(val))
, name_(nm)
{}
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const RangeType& val, const std::string nm)
: value_(std::make_shared< RangeType >(val))
, name_(nm)
{}
template< class E, class D, int d, class R, int r >
Constant< E, D, d, R, r >::Constant(const ThisType& other)
: value_(other.value_)
, name_(other.name_)
{}
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType& Constant< E, D, d, R, r >::operator=(const ThisType& other)
{
if (this != &other) {
value_ = other.value_;
name_ = other.name_;
}
return *this;
}
template< class E, class D, int d, class R, int r >
typename Constant< E, D, d, R, r >::ThisType* Constant< E, D, d, R, r >::copy() const
{
return new ThisType(*this);
}
template< class E, class D, int d, class R, int r >
std::string Constant< E, D, d, R, r >::name() const
{
return name_;
}
template< class E, class D, int d, class R, int r >
std::unique_ptr< typename Constant< E, D, d, R, r >::LocalfunctionType >
Constant< E, D, d, R, r >::local_function(const EntityType& entity) const
{
return std::unique_ptr< Localfunction >(new Localfunction(entity, value_));
}
} // namespace Function
} // namespace Stuff
} // namespace Dune
#include <dune/stuff/grid/fakeentity.hh>
typedef Dune::Stuff::Grid::FakeEntity< 1 > DuneStuffFake1dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 2 > DuneStuffFake2dEntityType;
typedef Dune::Stuff::Grid::FakeEntity< 3 > DuneStuffFake3dEntityType;
template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneStuffFake3dEntityType, double, 3, double, 3 >;
//#ifdef HAVE_DUNE_GRID
//# include <dune/grid/sgrid.hh>
//typedef typename Dune::SGrid< 1, 1 >::template Codim< 0 >::Entity DuneSGrid1dEntityType;
//typedef typename Dune::SGrid< 2, 2 >::template Codim< 0 >::Entity DuneSGrid2dEntityType;
//typedef typename Dune::SGrid< 3, 3 >::template Codim< 0 >::Entity DuneSGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneSGrid3dEntityType, double, 3, double, 3 >;
//# include <dune/grid/yaspgrid.hh>
//typedef typename Dune::YaspGrid< 1 >::template Codim< 0 >::Entity DuneYaspGrid1dEntityType;
//typedef typename Dune::YaspGrid< 2 >::template Codim< 0 >::Entity DuneYaspGrid2dEntityType;
//typedef typename Dune::YaspGrid< 3 >::template Codim< 0 >::Entity DuneYaspGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid1dEntityType, double, 1, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneYaspGrid3dEntityType, double, 3, double, 3 >;
//# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
//# define ALUGRID_CONFORM 1
//# define ENABLE_ALUGRID 1
//# include <dune/grid/alugrid.hh>
//typedef typename Dune::ALUSimplexGrid< 2, 2 >::template Codim< 0 >::Entity DuneAluSimplexGrid2dEntityType;
//typedef typename Dune::ALUSimplexGrid< 3, 3 >::template Codim< 0 >::Entity DuneAluSimplexGrid3dEntityType;
//typedef typename Dune::ALUCubeGrid< 3, 3 >::template Codim< 0 >::Entity DuneAluCubeGrid3dEntityType;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid2dEntityType, double, 2, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluSimplexGrid3dEntityType, double, 3, double, 3 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 1 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 2 >;
//template class Dune::Stuff::Function::Constant< DuneAluCubeGrid3dEntityType, double, 3, double, 3 >;
//# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
//#endif // HAVE_DUNE_GRID
<|endoftext|>
|
<commit_before>// This file is part of the dune-stuff project:
// https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH
#define DUNE_STUFF_FUNCTIONS_CONSTANT_HH
#include <memory>
#include <dune/stuff/common/configtree.hh>
#include "interfaces.hh"
namespace Dune {
namespace Stuff {
namespace Functions {
template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class Constant
: public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols>
{
public:
typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType;
typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
using typename BaseType::LocalfunctionType;
static std::string static_id()
{
return BaseType::static_id() + ".constant";
}
static Common::ConfigTree default_config(const std::string sub_name = "")
{
Common::ConfigTree config;
config["value"] = "1.0";
config["name"] = static_id();
if (sub_name.empty())
return config;
else {
Common::ConfigTree tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Common::ConfigTree config = default_config(), const std::string sub_name = static_id())
{
// get correct config
const Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
//extract data
auto value = cfg.get< RangeFieldImp >("value");
auto nm = cfg.get< std::string >("name", static_id());
return Common::make_unique< ThisType >(value, nm);
} // ... create(...)
explicit Constant(const RangeType& constant, const std::string name = static_id())
: constant_(constant)
, name_(name)
{}
explicit Constant(const RangeFieldImp& constant, const std::string name = static_id())
: constant_(constant)
, name_(name)
{}
Constant(const ThisType& other)
: constant_(other.constant_)
, name_(other.name_)
{}
virtual size_t order() const DS_OVERRIDE DS_FINAL
{
return 0;
}
virtual void evaluate(const DomainType& /*x*/, RangeType& ret) const DS_OVERRIDE DS_FINAL
{
ret = constant_;
}
virtual void jacobian(const DomainType& /*x*/, JacobianRangeType& ret) const DS_OVERRIDE DS_FINAL
{
ret *= 0.0;
}
virtual std::string name() const DS_OVERRIDE DS_FINAL
{
return name_;
}
private:
const RangeType constant_;
const std::string name_;
};
} // namespace Functions
} // namespace Stuff
} // namespace Dune
#ifdef DUNE_STUFF_FUNCTIONS_TO_LIB
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(etype, ddim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 1) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 2) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 3)
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, rdim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3)
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim)
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim)
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \
extern template class Dune::Stuff::Functions::Constant< etype, dftype, ddim, rftype, rdim, rcdim >;
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake3dEntityType, 3)
# if HAVE_DUNE_GRID
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid3dEntityType, 3)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid3dEntityType, 3)
# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid3dEntityType, 3)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluCubeGrid3dEntityType, 3)
# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# endif // HAVE_DUNE_GRID
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE
# endif // DUNE_STUFF_FUNCTIONS_TO_LIB
#endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH
<commit_msg>[functions.constant] use new get method<commit_after>// This file is part of the dune-stuff project:
// https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH
#define DUNE_STUFF_FUNCTIONS_CONSTANT_HH
#include <memory>
#include <dune/stuff/common/configtree.hh>
#include "interfaces.hh"
namespace Dune {
namespace Stuff {
namespace Functions {
template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 >
class Constant
: public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols>
{
public:
typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > BaseType;
typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > ThisType;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
using typename BaseType::LocalfunctionType;
static std::string static_id()
{
return BaseType::static_id() + ".constant";
}
static Common::ConfigTree default_config(const std::string sub_name = "")
{
Common::ConfigTree config;
config["value"] = "1.0";
config["name"] = static_id();
if (sub_name.empty())
return config;
else {
Common::ConfigTree tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Common::ConfigTree config = default_config(), const std::string sub_name = static_id())
{
// get correct config
const Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
const Common::ConfigTree default_cfg = default_config();
//create
return Common::make_unique< ThisType >(
cfg.get< RangeType >("value", default_cfg.get< RangeType >("value")),
cfg.get("name", default_cfg.get< std::string >("name")));
} // ... create(...)
explicit Constant(const RangeType& constant, const std::string name = static_id())
: constant_(constant)
, name_(name)
{}
explicit Constant(const RangeFieldImp& constant, const std::string name = static_id())
: constant_(constant)
, name_(name)
{}
Constant(const ThisType& other)
: constant_(other.constant_)
, name_(other.name_)
{}
virtual size_t order() const DS_OVERRIDE DS_FINAL
{
return 0;
}
virtual void evaluate(const DomainType& /*x*/, RangeType& ret) const DS_OVERRIDE DS_FINAL
{
ret = constant_;
}
virtual void jacobian(const DomainType& /*x*/, JacobianRangeType& ret) const DS_OVERRIDE DS_FINAL
{
ret *= 0.0;
}
virtual std::string name() const DS_OVERRIDE DS_FINAL
{
return name_;
}
private:
const RangeType constant_;
const std::string name_;
};
} // namespace Functions
} // namespace Stuff
} // namespace Dune
#ifdef DUNE_STUFF_FUNCTIONS_TO_LIB
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(etype, ddim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 1) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 2) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, 3)
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS(etype, ddim, rdim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 1) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 2) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, 3)
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES(etype, ddim, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, double, ddim, rdim, rcdim)
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES(etype, dftype, ddim, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, double, rdim, rcdim) \
DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, long double, rdim, rcdim)
# define DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION(etype, dftype, ddim, rftype, rdim, rcdim) \
extern template class Dune::Stuff::Functions::Constant< etype, dftype, ddim, rftype, rdim, rcdim >;
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesFake3dEntityType, 3)
# if HAVE_DUNE_GRID
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesSGrid3dEntityType, 3)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid1dEntityType, 1)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesYaspGrid3dEntityType, 3)
# if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid2dEntityType, 2)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluSimplexGrid3dEntityType, 3)
DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE(DuneStuffFunctionsInterfacesAluCubeGrid3dEntityType, 3)
# endif // HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# endif // HAVE_DUNE_GRID
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LAST_EXPANSION
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_RANGEFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DOMAINFIELDTYPES
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGECOLS
# undef DUNE_STUFF_FUNCTIONS_CONSTANT_LIST_DIMRANGE
# endif // DUNE_STUFF_FUNCTIONS_TO_LIB
#endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH
<|endoftext|>
|
<commit_before>#include "test_common.hh"
#include <memory>
#include <dune/common/exceptions.hh>
#include <dune/common/typetraits.hh>
#include <dune/common/static_assert.hh>
#if HAVE_DUNE_GRID
#include <dune/grid/sgrid.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/grid/provider.hh>
using namespace Dune::Stuff;
typedef testing::Types< FunctionConstant< double, 1, double, 1 >
, FunctionConstant< double, 2, double, 1 >
, FunctionConstant< double, 3, double, 1 >
> LocalizableFunctions;
template< class FunctionType >
struct LocalizableFunctionTest
: public ::testing::Test
{
dune_static_assert((Dune::IsBaseOf< LocalizableFunction, FunctionType >::value), "ERROR: not a LocalizableFunction!");
typedef typename FunctionType::DomainFieldType DomainFieldType;
static const unsigned int dimDomain = FunctionType::dimDomain;
typedef typename FunctionType::DomainType DomainType;
typedef typename FunctionType::RangeFieldType RangeFieldType;
static const unsigned int dimRangeRows = FunctionType::dimRangeRows;
static const unsigned int dimRangeCols = FunctionType::dimRangeCols;
typedef typename FunctionType::RangeType RangeType;
typedef Dune::SGrid< dimDomain, dimDomain > GridType;
typedef GridProviderCube< GridType > GridProviderType;
typedef typename GridType::LeafGridView GridViewType;
// typedef typename GridType::template Codim< 0 >::Entity EntityType;
// typedef typename FunctionType::template LocalizedFunction< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRangeRows, dimRangeCols >::Type LocalFunctionType;
void check() const
{
// generate grid
const GridProviderType* gridProvider = GridProviderType::create(GridProviderType::defaultSettings());
const std::shared_ptr< const GridType > grid = gridProvider->grid();
const GridViewType gridView = grid->leafView();
const auto entityIt = gridView.template begin< 0 >();
const auto& entity = *entityIt;
// create function
const FunctionType* function = FunctionType::create(FunctionType::defaultSettings());
// get localfunction
const auto localFunction =function->localFunction(entity);
const int DUNE_UNUSED(order) = localFunction.order();
const auto& DUNE_UNUSED(ent) = localFunction.entity();
const DomainType x(1);
RangeType ret(0);
localFunction.evaluate(x, ret);
// clean up
delete function;
delete gridProvider;
}
}; // struct LocalizableFunctionTest
TYPED_TEST_CASE(LocalizableFunctionTest, LocalizableFunctions);
TYPED_TEST(LocalizableFunctionTest, LocalizableFunction) {
this->check();
}
int main(int argc, char** argv)
{
test_init(argc, argv);
return RUN_ALL_TESTS();
}
#else // HAVE_DUNE_GRID
int main(int /*argc*/, char** /*argv*/)
{
return 0;
}
#endif // HAVE_DUNE_GRID
<commit_msg>[test.localfunction] removed obsolete test<commit_after><|endoftext|>
|
<commit_before>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#include <Python.h>
#include <dynd/type_registry.hpp>
#include "types/pyobject_type.hpp"
using namespace dynd;
const type_id_t pyobject_id = ndt::type_registry.insert(
any_kind_id, ndt::type(new pyobject_type(), true));
pyobject_type::pyobject_type()
: ndt::base_type(pyobject_id, sizeof(PyObject *), alignof(PyObject *),
type_flag_none | type_flag_zeroinit, 0, 0, 0)
{
}
void pyobject_type::print_type(std::ostream &o) const { o << "pyobject"; }
bool pyobject_type::operator==(const base_type &rhs) const
{
return get_id() == rhs.get_id();
}
void pyobject_type::print_data(std::ostream &o, const char *arrmeta,
const char *data) const
{
PyObject *repr = PyObject_Repr(*reinterpret_cast<PyObject *const *>(data));
#if PY_VERSION_HEX < 0x03000000
o << PyString_AsString(repr);
#else
o << PyUnicode_AsUTF8(repr);
#endif
Py_DECREF(repr);
}
<commit_msg>Updates to match libdynd<commit_after>//
// Copyright (C) 2011-15 DyND Developers
// BSD 2-Clause License, see LICENSE.txt
//
#include <Python.h>
#include <dynd/type_registry.hpp>
#include "types/pyobject_type.hpp"
using namespace dynd;
const type_id_t pyobject_id = new_id("pyobject", any_kind_id);
pyobject_type::pyobject_type()
: ndt::base_type(pyobject_id, sizeof(PyObject *), alignof(PyObject *),
type_flag_none | type_flag_zeroinit, 0, 0, 0)
{
}
void pyobject_type::print_type(std::ostream &o) const { o << "pyobject"; }
bool pyobject_type::operator==(const base_type &rhs) const
{
return get_id() == rhs.get_id();
}
void pyobject_type::print_data(std::ostream &o, const char *arrmeta,
const char *data) const
{
PyObject *repr = PyObject_Repr(*reinterpret_cast<PyObject *const *>(data));
#if PY_VERSION_HEX < 0x03000000
o << PyString_AsString(repr);
#else
o << PyUnicode_AsUTF8(repr);
#endif
Py_DECREF(repr);
}
<|endoftext|>
|
<commit_before>/*
* OpenCMISS-Zinc Library Unit Tests
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <gtest/gtest.h>
#include <zinc/field.hpp>
#include <zinc/fieldcache.hpp>
#include <zinc/fieldconstant.hpp>
#include <zinc/fieldfiniteelement.hpp>
#include <zinc/fieldmeshoperators.hpp>
#include <zinc/fieldmodule.hpp>
#include <zinc/fieldsubobjectgroup.hpp>
#include <zinc/region.hpp>
#include <zinc/streamregion.hpp>
#include "utilities/zinctestsetupcpp.hpp"
#include "utilities/fileio.hpp"
#include "test_resources.h"
#define FIELDML_OUTPUT_FOLDER "fieldmltest"
ManageOutputFolder manageOutputFolderFieldML(FIELDML_OUTPUT_FOLDER);
namespace {
void check_cube_model(Fieldmodule& fm)
{
int result;
Field coordinates = fm.findFieldByName("coordinates");
EXPECT_TRUE(coordinates.isValid());
EXPECT_EQ(3, coordinates.getNumberOfComponents());
EXPECT_TRUE(coordinates.isTypeCoordinate());
Field pressure = fm.findFieldByName("pressure");
EXPECT_TRUE(pressure.isValid());
EXPECT_EQ(1, pressure.getNumberOfComponents());
EXPECT_FALSE(pressure.isTypeCoordinate());
EXPECT_EQ(OK, result = fm.defineAllFaces());
Mesh mesh3d = fm.findMeshByDimension(3);
EXPECT_EQ(1, mesh3d.getSize());
Mesh mesh2d = fm.findMeshByDimension(2);
EXPECT_EQ(6, mesh2d.getSize());
Mesh mesh1d = fm.findMeshByDimension(1);
EXPECT_EQ(12, mesh1d.getSize());
Nodeset nodes = fm.findNodesetByFieldDomainType(Field::DOMAIN_TYPE_NODES);
EXPECT_EQ(8, nodes.getSize());
Element element = mesh3d.findElementByIdentifier(1);
EXPECT_TRUE(element.isValid());
EXPECT_EQ(Element::SHAPE_TYPE_CUBE, element.getShapeType());
const double valueOne = 1.0;
Field one = fm.createFieldConstant(1, &valueOne);
FieldMeshIntegral volume = fm.createFieldMeshIntegral(one, coordinates, mesh3d);
const int numberOfPoints = 2;
EXPECT_EQ(OK, result = volume.setNumbersOfPoints(1, &numberOfPoints));
FieldMeshIntegral surfacePressureIntegral = fm.createFieldMeshIntegral(pressure, coordinates, mesh2d);
EXPECT_EQ(OK, result = surfacePressureIntegral.setNumbersOfPoints(1, &numberOfPoints));
Fieldcache cache = fm.createFieldcache();
double outVolume;
EXPECT_EQ(OK, result = volume.evaluateReal(cache, 1, &outVolume));
ASSERT_DOUBLE_EQ(1.0, outVolume);
double outSurfacePressureIntegral;
EXPECT_EQ(OK, result = surfacePressureIntegral.evaluateReal(cache, 1, &outSurfacePressureIntegral));
ASSERT_DOUBLE_EQ(540000.0, outSurfacePressureIntegral);
}
}
// cube model defines a 3-D RC coordinates field and 1-D pressure field
// using the same trilinear Lagrange scalar template.
// field dofs and mesh nodes connectivity are inline text in the fieldml document
TEST(ZincRegion, read_fieldml_cube)
{
ZincTestSetupCpp zinc;
int result;
EXPECT_EQ(OK, result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_CUBE_RESOURCE)));
check_cube_model(zinc.fm);
// test writing and re-reading into different region
EXPECT_EQ(OK, result = zinc.root_region.writeFile(FIELDML_OUTPUT_FOLDER "/cube.fieldml"));
Region testRegion = zinc.root_region.createChild("test");
EXPECT_EQ(OK, result = testRegion.readFile(FIELDML_OUTPUT_FOLDER "/cube.fieldml"));
Fieldmodule testFm = testRegion.getFieldmodule();
check_cube_model(zinc.fm);
}
// Also reads cube model, but tries to read it as EX format which should fail
TEST(ZincStreaminformationRegion, fileFormat)
{
ZincTestSetupCpp zinc;
int result;
StreaminformationRegion streamInfo = zinc.root_region.createStreaminformationRegion();
EXPECT_TRUE(streamInfo.isValid());
StreamresourceFile fileResource = streamInfo.createStreamresourceFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_CUBE_RESOURCE));
EXPECT_TRUE(fileResource.isValid());
StreaminformationRegion::FileFormat fileFormat = streamInfo.getFileFormat();
EXPECT_EQ(StreaminformationRegion::FILE_FORMAT_AUTOMATIC, fileFormat);
EXPECT_EQ(OK, result = streamInfo.setFileFormat(StreaminformationRegion::FILE_FORMAT_EX));
EXPECT_EQ(StreaminformationRegion::FILE_FORMAT_EX, fileFormat = streamInfo.getFileFormat());
result = zinc.root_region.read(streamInfo);
EXPECT_EQ(ERROR_GENERAL, result); // not in EX format
EXPECT_EQ(OK, result = streamInfo.setFileFormat(StreaminformationRegion::FILE_FORMAT_FIELDML));
EXPECT_EQ(StreaminformationRegion::FILE_FORMAT_FIELDML, fileFormat = streamInfo.getFileFormat());
result = zinc.root_region.read(streamInfo);
EXPECT_EQ(OK, result); // in FieldML format
check_cube_model(zinc.fm);
}
namespace {
void check_tetmesh_model(Fieldmodule& fm)
{
int result;
Field coordinates = fm.findFieldByName("coordinates");
EXPECT_TRUE(coordinates.isValid());
EXPECT_EQ(3, coordinates.getNumberOfComponents());
EXPECT_TRUE(coordinates.isTypeCoordinate());
EXPECT_EQ(OK, result = fm.defineAllFaces());
Mesh mesh3d = fm.findMeshByDimension(3);
EXPECT_EQ(102, mesh3d.getSize());
Mesh mesh2d = fm.findMeshByDimension(2);
EXPECT_EQ(232, mesh2d.getSize());
Mesh mesh1d = fm.findMeshByDimension(1);
EXPECT_EQ(167, mesh1d.getSize());
Nodeset nodes = fm.findNodesetByFieldDomainType(Field::DOMAIN_TYPE_NODES);
EXPECT_EQ(38, nodes.getSize());
for (int i = 1; i < 102; ++i)
{
Element element = mesh3d.findElementByIdentifier(i);
EXPECT_TRUE(element.isValid());
Element::ShapeType shapeType = element.getShapeType();
EXPECT_EQ(Element::SHAPE_TYPE_TETRAHEDRON, shapeType);
}
const double valueOne = 1.0;
Field one = fm.createFieldConstant(1, &valueOne);
FieldMeshIntegral volume = fm.createFieldMeshIntegral(one, coordinates, mesh3d);
EXPECT_TRUE(volume.isValid());
FieldElementGroup exteriorFacesGroup = fm.createFieldElementGroup(mesh2d);
EXPECT_TRUE(exteriorFacesGroup.isValid());
EXPECT_EQ(OK, result = exteriorFacesGroup.setManaged(true));
MeshGroup exteriorFacesMeshGroup = exteriorFacesGroup.getMeshGroup();
EXPECT_TRUE(exteriorFacesMeshGroup.isValid());
FieldIsExterior isExterior = fm.createFieldIsExterior();
EXPECT_TRUE(isExterior.isValid());
exteriorFacesMeshGroup.addElementsConditional(isExterior);
EXPECT_EQ(56, exteriorFacesMeshGroup.getSize());
FieldMeshIntegral surfaceArea = fm.createFieldMeshIntegral(one, coordinates, exteriorFacesMeshGroup);
EXPECT_TRUE(surfaceArea.isValid());
Fieldcache cache = fm.createFieldcache();
double outVolume;
EXPECT_EQ(OK, result = volume.evaluateReal(cache, 1, &outVolume));
ASSERT_DOUBLE_EQ(0.41723178864303812, outVolume);
double outSurfaceArea;
EXPECT_EQ(OK, result = surfaceArea.evaluateReal(cache, 1, &outSurfaceArea));
ASSERT_DOUBLE_EQ(2.7717561493468423, outSurfaceArea);
}
}
// tetmesh model defines a 3-D RC coordinates field over a tetrahedral
// mesh in approximate unit sphere shape with trilinearSimplex basis/
// node coordinates and connectivity are read from separate files
TEST(ZincRegion, read_fieldml_tetmesh)
{
ZincTestSetupCpp zinc;
int result;
EXPECT_EQ(OK, result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_TETMESH_RESOURCE)));
check_tetmesh_model(zinc.fm);
// check can't merge cube model since it redefines element 1 shape
result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_CUBE_RESOURCE));
EXPECT_EQ(ERROR_INCOMPATIBLE_DATA, result);
// test writing and re-reading into different region
EXPECT_EQ(OK, result = zinc.root_region.writeFile(FIELDML_OUTPUT_FOLDER "/tetmesh.fieldml"));
Region testRegion = zinc.root_region.createChild("test");
EXPECT_EQ(OK, result = testRegion.readFile(FIELDML_OUTPUT_FOLDER "/tetmesh.fieldml"));
Fieldmodule testFm = testRegion.getFieldmodule();
check_tetmesh_model(zinc.fm);
}
namespace {
void check_wheel_model(Fieldmodule& fm)
{
int result;
Field coordinates = fm.findFieldByName("coordinates");
EXPECT_TRUE(coordinates.isValid());
EXPECT_EQ(3, coordinates.getNumberOfComponents());
EXPECT_TRUE(coordinates.isTypeCoordinate());
EXPECT_EQ(OK, result = fm.defineAllFaces());
Mesh mesh3d = fm.findMeshByDimension(3);
EXPECT_EQ(12, mesh3d.getSize());
Mesh mesh2d = fm.findMeshByDimension(2);
EXPECT_EQ(48, mesh2d.getSize());
Mesh mesh1d = fm.findMeshByDimension(1);
EXPECT_EQ(61, mesh1d.getSize());
Nodeset nodes = fm.findNodesetByFieldDomainType(Field::DOMAIN_TYPE_NODES);
EXPECT_EQ(129, nodes.getSize());
for (int i = 1; i < 12; ++i)
{
Element element = mesh3d.findElementByIdentifier(i);
EXPECT_TRUE(element.isValid());
Element::ShapeType shapeType = element.getShapeType();
if (i <= 6)
EXPECT_EQ(Element::SHAPE_TYPE_WEDGE12, shapeType);
else
EXPECT_EQ(Element::SHAPE_TYPE_CUBE, shapeType);
}
const double valueOne = 1.0;
Field one = fm.createFieldConstant(1, &valueOne);
FieldMeshIntegral volume = fm.createFieldMeshIntegral(one, coordinates, mesh3d);
EXPECT_TRUE(volume.isValid());
const int pointCount = 2;
EXPECT_EQ(OK, result = volume.setNumbersOfPoints(1, &pointCount));
FieldElementGroup exteriorFacesGroup = fm.createFieldElementGroup(mesh2d);
EXPECT_TRUE(exteriorFacesGroup.isValid());
EXPECT_EQ(OK, result = exteriorFacesGroup.setManaged(true));
MeshGroup exteriorFacesMeshGroup = exteriorFacesGroup.getMeshGroup();
EXPECT_TRUE(exteriorFacesMeshGroup.isValid());
FieldIsExterior isExterior = fm.createFieldIsExterior();
EXPECT_TRUE(isExterior.isValid());
exteriorFacesMeshGroup.addElementsConditional(isExterior);
EXPECT_EQ(30, exteriorFacesMeshGroup.getSize());
FieldMeshIntegral surfaceArea = fm.createFieldMeshIntegral(one, coordinates, exteriorFacesMeshGroup);
EXPECT_TRUE(surfaceArea.isValid());
EXPECT_EQ(OK, result = surfaceArea.setNumbersOfPoints(1, &pointCount));
Fieldcache cache = fm.createFieldcache();
double outVolume;
EXPECT_EQ(OK, result = volume.evaluateReal(cache, 1, &outVolume));
ASSERT_DOUBLE_EQ(100.28718664065387, outVolume);
double outSurfaceArea;
EXPECT_EQ(OK, result = surfaceArea.evaluateReal(cache, 1, &outSurfaceArea));
ASSERT_DOUBLE_EQ(150.53218306379620, outSurfaceArea);
}
}
// wheel_direct model defines a 3-D RC coordinates field over a wheel mesh
// consisting of 6 wedge elements in the centre, and 6 cube elements around
// them, all coordinates interpolated with triquadratic bases.
// This model tests having variant element shapes and a piecewise field
// template which directly maps element to function (basis + parameter map).
// It also reads shapeids, node coordinates and connectivity (for wedge and
// cube connectivity) from separate files, and the connectivity data uses
// dictionary of keys (DOK) format with key data in the first column of the
// same file.
TEST(ZincRegion, read_fieldml_wheel_direct)
{
ZincTestSetupCpp zinc;
int result;
EXPECT_EQ(OK, result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_WHEEL_DIRECT_RESOURCE)));
check_wheel_model(zinc.fm);
}
// wheel_indirect model is the same as the wheel_direct model except that it
// uses a more efficient indirect element-to-function map
TEST(ZincRegion, read_fieldml_wheel_indirect)
{
ZincTestSetupCpp zinc;
int result;
EXPECT_EQ(OK, result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_WHEEL_INDIRECT_RESOURCE)));
check_wheel_model(zinc.fm);
// test writing and re-reading into different region
EXPECT_EQ(OK, result = zinc.root_region.writeFile(FIELDML_OUTPUT_FOLDER "/wheel.fieldml"));
Region testRegion = zinc.root_region.createChild("test");
EXPECT_EQ(OK, result = testRegion.readFile(FIELDML_OUTPUT_FOLDER "/wheel.fieldml"));
Fieldmodule testFm = testRegion.getFieldmodule();
check_wheel_model(zinc.fm);
}
<commit_msg>Test the new region's fields on re-reading FieldML output. https://tracker.physiomeproject.org/show_bug.cgi?id=3827<commit_after>/*
* OpenCMISS-Zinc Library Unit Tests
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <gtest/gtest.h>
#include <zinc/field.hpp>
#include <zinc/fieldcache.hpp>
#include <zinc/fieldconstant.hpp>
#include <zinc/fieldfiniteelement.hpp>
#include <zinc/fieldmeshoperators.hpp>
#include <zinc/fieldmodule.hpp>
#include <zinc/fieldsubobjectgroup.hpp>
#include <zinc/region.hpp>
#include <zinc/streamregion.hpp>
#include "utilities/zinctestsetupcpp.hpp"
#include "utilities/fileio.hpp"
#include "test_resources.h"
#define FIELDML_OUTPUT_FOLDER "fieldmltest"
ManageOutputFolder manageOutputFolderFieldML(FIELDML_OUTPUT_FOLDER);
namespace {
void check_cube_model(Fieldmodule& fm)
{
int result;
Field coordinates = fm.findFieldByName("coordinates");
EXPECT_TRUE(coordinates.isValid());
EXPECT_EQ(3, coordinates.getNumberOfComponents());
EXPECT_TRUE(coordinates.isTypeCoordinate());
Field pressure = fm.findFieldByName("pressure");
EXPECT_TRUE(pressure.isValid());
EXPECT_EQ(1, pressure.getNumberOfComponents());
EXPECT_FALSE(pressure.isTypeCoordinate());
EXPECT_EQ(OK, result = fm.defineAllFaces());
Mesh mesh3d = fm.findMeshByDimension(3);
EXPECT_EQ(1, mesh3d.getSize());
Mesh mesh2d = fm.findMeshByDimension(2);
EXPECT_EQ(6, mesh2d.getSize());
Mesh mesh1d = fm.findMeshByDimension(1);
EXPECT_EQ(12, mesh1d.getSize());
Nodeset nodes = fm.findNodesetByFieldDomainType(Field::DOMAIN_TYPE_NODES);
EXPECT_EQ(8, nodes.getSize());
Element element = mesh3d.findElementByIdentifier(1);
EXPECT_TRUE(element.isValid());
EXPECT_EQ(Element::SHAPE_TYPE_CUBE, element.getShapeType());
const double valueOne = 1.0;
Field one = fm.createFieldConstant(1, &valueOne);
FieldMeshIntegral volume = fm.createFieldMeshIntegral(one, coordinates, mesh3d);
const int numberOfPoints = 2;
EXPECT_EQ(OK, result = volume.setNumbersOfPoints(1, &numberOfPoints));
FieldMeshIntegral surfacePressureIntegral = fm.createFieldMeshIntegral(pressure, coordinates, mesh2d);
EXPECT_EQ(OK, result = surfacePressureIntegral.setNumbersOfPoints(1, &numberOfPoints));
Fieldcache cache = fm.createFieldcache();
double outVolume;
EXPECT_EQ(OK, result = volume.evaluateReal(cache, 1, &outVolume));
ASSERT_DOUBLE_EQ(1.0, outVolume);
double outSurfacePressureIntegral;
EXPECT_EQ(OK, result = surfacePressureIntegral.evaluateReal(cache, 1, &outSurfacePressureIntegral));
ASSERT_DOUBLE_EQ(540000.0, outSurfacePressureIntegral);
}
}
// cube model defines a 3-D RC coordinates field and 1-D pressure field
// using the same trilinear Lagrange scalar template.
// field dofs and mesh nodes connectivity are inline text in the fieldml document
TEST(ZincRegion, read_fieldml_cube)
{
ZincTestSetupCpp zinc;
int result;
EXPECT_EQ(OK, result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_CUBE_RESOURCE)));
check_cube_model(zinc.fm);
// test writing and re-reading into different region
EXPECT_EQ(OK, result = zinc.root_region.writeFile(FIELDML_OUTPUT_FOLDER "/cube.fieldml"));
Region testRegion = zinc.root_region.createChild("test");
EXPECT_EQ(OK, result = testRegion.readFile(FIELDML_OUTPUT_FOLDER "/cube.fieldml"));
Fieldmodule testFm = testRegion.getFieldmodule();
check_cube_model(testFm);
}
// Also reads cube model, but tries to read it as EX format which should fail
TEST(ZincStreaminformationRegion, fileFormat)
{
ZincTestSetupCpp zinc;
int result;
StreaminformationRegion streamInfo = zinc.root_region.createStreaminformationRegion();
EXPECT_TRUE(streamInfo.isValid());
StreamresourceFile fileResource = streamInfo.createStreamresourceFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_CUBE_RESOURCE));
EXPECT_TRUE(fileResource.isValid());
StreaminformationRegion::FileFormat fileFormat = streamInfo.getFileFormat();
EXPECT_EQ(StreaminformationRegion::FILE_FORMAT_AUTOMATIC, fileFormat);
EXPECT_EQ(OK, result = streamInfo.setFileFormat(StreaminformationRegion::FILE_FORMAT_EX));
EXPECT_EQ(StreaminformationRegion::FILE_FORMAT_EX, fileFormat = streamInfo.getFileFormat());
result = zinc.root_region.read(streamInfo);
EXPECT_EQ(ERROR_GENERAL, result); // not in EX format
EXPECT_EQ(OK, result = streamInfo.setFileFormat(StreaminformationRegion::FILE_FORMAT_FIELDML));
EXPECT_EQ(StreaminformationRegion::FILE_FORMAT_FIELDML, fileFormat = streamInfo.getFileFormat());
result = zinc.root_region.read(streamInfo);
EXPECT_EQ(OK, result); // in FieldML format
check_cube_model(zinc.fm);
}
namespace {
void check_tetmesh_model(Fieldmodule& fm)
{
int result;
Field coordinates = fm.findFieldByName("coordinates");
EXPECT_TRUE(coordinates.isValid());
EXPECT_EQ(3, coordinates.getNumberOfComponents());
EXPECT_TRUE(coordinates.isTypeCoordinate());
EXPECT_EQ(OK, result = fm.defineAllFaces());
Mesh mesh3d = fm.findMeshByDimension(3);
EXPECT_EQ(102, mesh3d.getSize());
Mesh mesh2d = fm.findMeshByDimension(2);
EXPECT_EQ(232, mesh2d.getSize());
Mesh mesh1d = fm.findMeshByDimension(1);
EXPECT_EQ(167, mesh1d.getSize());
Nodeset nodes = fm.findNodesetByFieldDomainType(Field::DOMAIN_TYPE_NODES);
EXPECT_EQ(38, nodes.getSize());
for (int i = 1; i < 102; ++i)
{
Element element = mesh3d.findElementByIdentifier(i);
EXPECT_TRUE(element.isValid());
Element::ShapeType shapeType = element.getShapeType();
EXPECT_EQ(Element::SHAPE_TYPE_TETRAHEDRON, shapeType);
}
const double valueOne = 1.0;
Field one = fm.createFieldConstant(1, &valueOne);
FieldMeshIntegral volume = fm.createFieldMeshIntegral(one, coordinates, mesh3d);
EXPECT_TRUE(volume.isValid());
FieldElementGroup exteriorFacesGroup = fm.createFieldElementGroup(mesh2d);
EXPECT_TRUE(exteriorFacesGroup.isValid());
EXPECT_EQ(OK, result = exteriorFacesGroup.setManaged(true));
MeshGroup exteriorFacesMeshGroup = exteriorFacesGroup.getMeshGroup();
EXPECT_TRUE(exteriorFacesMeshGroup.isValid());
FieldIsExterior isExterior = fm.createFieldIsExterior();
EXPECT_TRUE(isExterior.isValid());
exteriorFacesMeshGroup.addElementsConditional(isExterior);
EXPECT_EQ(56, exteriorFacesMeshGroup.getSize());
FieldMeshIntegral surfaceArea = fm.createFieldMeshIntegral(one, coordinates, exteriorFacesMeshGroup);
EXPECT_TRUE(surfaceArea.isValid());
Fieldcache cache = fm.createFieldcache();
double outVolume;
EXPECT_EQ(OK, result = volume.evaluateReal(cache, 1, &outVolume));
ASSERT_DOUBLE_EQ(0.41723178864303812, outVolume);
double outSurfaceArea;
EXPECT_EQ(OK, result = surfaceArea.evaluateReal(cache, 1, &outSurfaceArea));
ASSERT_DOUBLE_EQ(2.7717561493468423, outSurfaceArea);
}
}
// tetmesh model defines a 3-D RC coordinates field over a tetrahedral
// mesh in approximate unit sphere shape with trilinearSimplex basis/
// node coordinates and connectivity are read from separate files
TEST(ZincRegion, read_fieldml_tetmesh)
{
ZincTestSetupCpp zinc;
int result;
EXPECT_EQ(OK, result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_TETMESH_RESOURCE)));
check_tetmesh_model(zinc.fm);
// check can't merge cube model since it redefines element 1 shape
result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_CUBE_RESOURCE));
EXPECT_EQ(ERROR_INCOMPATIBLE_DATA, result);
// test writing and re-reading into different region
EXPECT_EQ(OK, result = zinc.root_region.writeFile(FIELDML_OUTPUT_FOLDER "/tetmesh.fieldml"));
Region testRegion = zinc.root_region.createChild("test");
EXPECT_EQ(OK, result = testRegion.readFile(FIELDML_OUTPUT_FOLDER "/tetmesh.fieldml"));
Fieldmodule testFm = testRegion.getFieldmodule();
check_tetmesh_model(testFm);
}
namespace {
void check_wheel_model(Fieldmodule& fm)
{
int result;
Field coordinates = fm.findFieldByName("coordinates");
EXPECT_TRUE(coordinates.isValid());
EXPECT_EQ(3, coordinates.getNumberOfComponents());
EXPECT_TRUE(coordinates.isTypeCoordinate());
EXPECT_EQ(OK, result = fm.defineAllFaces());
Mesh mesh3d = fm.findMeshByDimension(3);
EXPECT_EQ(12, mesh3d.getSize());
Mesh mesh2d = fm.findMeshByDimension(2);
EXPECT_EQ(48, mesh2d.getSize());
Mesh mesh1d = fm.findMeshByDimension(1);
EXPECT_EQ(61, mesh1d.getSize());
Nodeset nodes = fm.findNodesetByFieldDomainType(Field::DOMAIN_TYPE_NODES);
EXPECT_EQ(129, nodes.getSize());
for (int i = 1; i < 12; ++i)
{
Element element = mesh3d.findElementByIdentifier(i);
EXPECT_TRUE(element.isValid());
Element::ShapeType shapeType = element.getShapeType();
if (i <= 6)
EXPECT_EQ(Element::SHAPE_TYPE_WEDGE12, shapeType);
else
EXPECT_EQ(Element::SHAPE_TYPE_CUBE, shapeType);
}
const double valueOne = 1.0;
Field one = fm.createFieldConstant(1, &valueOne);
FieldMeshIntegral volume = fm.createFieldMeshIntegral(one, coordinates, mesh3d);
EXPECT_TRUE(volume.isValid());
const int pointCount = 2;
EXPECT_EQ(OK, result = volume.setNumbersOfPoints(1, &pointCount));
FieldElementGroup exteriorFacesGroup = fm.createFieldElementGroup(mesh2d);
EXPECT_TRUE(exteriorFacesGroup.isValid());
EXPECT_EQ(OK, result = exteriorFacesGroup.setManaged(true));
MeshGroup exteriorFacesMeshGroup = exteriorFacesGroup.getMeshGroup();
EXPECT_TRUE(exteriorFacesMeshGroup.isValid());
FieldIsExterior isExterior = fm.createFieldIsExterior();
EXPECT_TRUE(isExterior.isValid());
exteriorFacesMeshGroup.addElementsConditional(isExterior);
EXPECT_EQ(30, exteriorFacesMeshGroup.getSize());
FieldMeshIntegral surfaceArea = fm.createFieldMeshIntegral(one, coordinates, exteriorFacesMeshGroup);
EXPECT_TRUE(surfaceArea.isValid());
EXPECT_EQ(OK, result = surfaceArea.setNumbersOfPoints(1, &pointCount));
Fieldcache cache = fm.createFieldcache();
double outVolume;
EXPECT_EQ(OK, result = volume.evaluateReal(cache, 1, &outVolume));
ASSERT_DOUBLE_EQ(100.28718664065387, outVolume);
double outSurfaceArea;
EXPECT_EQ(OK, result = surfaceArea.evaluateReal(cache, 1, &outSurfaceArea));
ASSERT_DOUBLE_EQ(150.53218306379620, outSurfaceArea);
}
}
// wheel_direct model defines a 3-D RC coordinates field over a wheel mesh
// consisting of 6 wedge elements in the centre, and 6 cube elements around
// them, all coordinates interpolated with triquadratic bases.
// This model tests having variant element shapes and a piecewise field
// template which directly maps element to function (basis + parameter map).
// It also reads shapeids, node coordinates and connectivity (for wedge and
// cube connectivity) from separate files, and the connectivity data uses
// dictionary of keys (DOK) format with key data in the first column of the
// same file.
TEST(ZincRegion, read_fieldml_wheel_direct)
{
ZincTestSetupCpp zinc;
int result;
EXPECT_EQ(OK, result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_WHEEL_DIRECT_RESOURCE)));
check_wheel_model(zinc.fm);
}
// wheel_indirect model is the same as the wheel_direct model except that it
// uses a more efficient indirect element-to-function map
TEST(ZincRegion, read_fieldml_wheel_indirect)
{
ZincTestSetupCpp zinc;
int result;
EXPECT_EQ(OK, result = zinc.root_region.readFile(
TestResources::getLocation(TestResources::FIELDIO_FIELDML_WHEEL_INDIRECT_RESOURCE)));
check_wheel_model(zinc.fm);
// test writing and re-reading into different region
EXPECT_EQ(OK, result = zinc.root_region.writeFile(FIELDML_OUTPUT_FOLDER "/wheel.fieldml"));
Region testRegion = zinc.root_region.createChild("test");
EXPECT_EQ(OK, result = testRegion.readFile(FIELDML_OUTPUT_FOLDER "/wheel.fieldml"));
Fieldmodule testFm = testRegion.getFieldmodule();
check_wheel_model(testFm);
}
<|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 <iostream>
#include <string.h>
#include <ooxml/resourceids.hxx>
#include "OOXMLFastTokenHandler.hxx"
#if defined __clang__
#if __has_warning("-Wdeprecated-register")
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-register"
#endif
#endif
#include "gperffasttoken.hxx"
#if defined __clang__
#if __has_warning("-Wdeprecated-register")
#pragma GCC diagnostic pop
#endif
#endif
namespace writerfilter {
namespace ooxml
{
using namespace ::std;
OOXMLFastTokenHandler::OOXMLFastTokenHandler
(css::uno::Reference< css::uno::XComponentContext > const & context)
: m_xContext(context)
{}
// ::com::sun::star::xml::sax::XFastTokenHandler:
::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getToken(const OUString & Identifier)
throw (css::uno::RuntimeException)
{
::sal_Int32 nResult = OOXML_FAST_TOKENS_END;
struct tokenmap::token * pToken =
tokenmap::Perfect_Hash::in_word_set
(OUStringToOString(Identifier, RTL_TEXTENCODING_ASCII_US).getStr(),
Identifier.getLength());
if (pToken != NULL)
nResult = pToken->nToken;
#ifdef DEBUG_TOKEN
clog << "getToken: "
<< OUStringToOString(Identifier, RTL_TEXTENCODING_ASCII_US).getStr()
<< ", " << nResult
<< endl;
#endif
return nResult;
}
OUString SAL_CALL OOXMLFastTokenHandler::getIdentifier(::sal_Int32 Token)
throw (css::uno::RuntimeException)
{
OUString sResult;
#if 0
//FIXME this is broken: tokenmap::wordlist is not indexed by Token!
if ( Token >= 0 || Token < OOXML_FAST_TOKENS_END )
{
static OUString aTokens[OOXML_FAST_TOKENS_END];
if (aTokens[Token].getLength() == 0)
aTokens[Token] = OUString::createFromAscii
(tokenmap::wordlist[Token].name);
}
#else
(void) Token;
#endif
return sResult;
}
css::uno::Sequence< ::sal_Int8 > SAL_CALL OOXMLFastTokenHandler::getUTF8Identifier(::sal_Int32 Token)
throw (css::uno::RuntimeException)
{
#if 0
if ( Token < 0 || Token >= OOXML_FAST_TOKENS_END )
#endif
return css::uno::Sequence< ::sal_Int8 >();
#if 0
//FIXME this is broken: tokenmap::wordlist is not indexed by Token!
return css::uno::Sequence< ::sal_Int8 >(reinterpret_cast< const sal_Int8 *>(tokenmap::wordlist[Token].name), strlen(tokenmap::wordlist[Token].name));
#else
(void) Token;
#endif
}
::sal_Int32 OOXMLFastTokenHandler::getTokenDirect( const char *pStr, sal_Int32 nLength ) const
{
struct tokenmap::token * pToken =
tokenmap::Perfect_Hash::in_word_set( pStr, nLength );
sal_Int32 nResult = pToken != NULL ? pToken->nToken : OOXML_FAST_TOKENS_END;
#ifdef DEBUG_TOKEN
clog << "getTokenFromUTF8: "
<< string(pStr, nLength)
<< ", " << nResult
<< (pToken == NULL ? ", failed" : "") << endl;
#endif
return nResult;
}
::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getTokenFromUTF8
(const css::uno::Sequence< ::sal_Int8 > & Identifier) throw (css::uno::RuntimeException)
{
return getTokenDirect(reinterpret_cast<const char *>
(Identifier.getConstArray()),
Identifier.getLength());
}
}}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix windows compile.<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 <iostream>
#include <string.h>
#include <ooxml/resourceids.hxx>
#include "OOXMLFastTokenHandler.hxx"
#if defined __clang__
#if __has_warning("-Wdeprecated-register")
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-register"
#endif
#endif
#include "gperffasttoken.hxx"
#if defined __clang__
#if __has_warning("-Wdeprecated-register")
#pragma GCC diagnostic pop
#endif
#endif
namespace writerfilter {
namespace ooxml
{
using namespace ::std;
OOXMLFastTokenHandler::OOXMLFastTokenHandler
(css::uno::Reference< css::uno::XComponentContext > const & context)
: m_xContext(context)
{}
// ::com::sun::star::xml::sax::XFastTokenHandler:
::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getToken(const OUString & Identifier)
throw (css::uno::RuntimeException)
{
::sal_Int32 nResult = OOXML_FAST_TOKENS_END;
struct tokenmap::token * pToken =
tokenmap::Perfect_Hash::in_word_set
(OUStringToOString(Identifier, RTL_TEXTENCODING_ASCII_US).getStr(),
Identifier.getLength());
if (pToken != NULL)
nResult = pToken->nToken;
#ifdef DEBUG_TOKEN
clog << "getToken: "
<< OUStringToOString(Identifier, RTL_TEXTENCODING_ASCII_US).getStr()
<< ", " << nResult
<< endl;
#endif
return nResult;
}
OUString SAL_CALL OOXMLFastTokenHandler::getIdentifier(::sal_Int32 Token)
throw (css::uno::RuntimeException)
{
OUString sResult;
#if 0
//FIXME this is broken: tokenmap::wordlist is not indexed by Token!
if ( Token >= 0 || Token < OOXML_FAST_TOKENS_END )
{
static OUString aTokens[OOXML_FAST_TOKENS_END];
if (aTokens[Token].getLength() == 0)
aTokens[Token] = OUString::createFromAscii
(tokenmap::wordlist[Token].name);
}
#else
(void) Token;
#endif
return sResult;
}
css::uno::Sequence< ::sal_Int8 > SAL_CALL OOXMLFastTokenHandler::getUTF8Identifier(::sal_Int32 Token)
throw (css::uno::RuntimeException)
{
#if 0
if ( Token < 0 || Token >= OOXML_FAST_TOKENS_END )
#endif
return css::uno::Sequence< ::sal_Int8 >();
#if 0
//FIXME this is broken: tokenmap::wordlist is not indexed by Token!
return css::uno::Sequence< ::sal_Int8 >(reinterpret_cast< const sal_Int8 *>(tokenmap::wordlist[Token].name), strlen(tokenmap::wordlist[Token].name));
#else
(void) Token;
#endif
}
sal_Int32 OOXMLFastTokenHandler::getTokenDirect( const char *pStr, sal_Int32 nLength ) const
{
struct tokenmap::token * pToken =
tokenmap::Perfect_Hash::in_word_set( pStr, nLength );
sal_Int32 nResult = pToken != NULL ? pToken->nToken : OOXML_FAST_TOKENS_END;
#ifdef DEBUG_TOKEN
clog << "getTokenFromUTF8: "
<< string(pStr, nLength)
<< ", " << nResult
<< (pToken == NULL ? ", failed" : "") << endl;
#endif
return nResult;
}
::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getTokenFromUTF8
(const css::uno::Sequence< ::sal_Int8 > & Identifier) throw (css::uno::RuntimeException)
{
return getTokenDirect(reinterpret_cast<const char *>
(Identifier.getConstArray()),
Identifier.getLength());
}
}}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2004, 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <lac/petsc_matrix_base.h>
#include <lac/petsc_full_matrix.h>
#include <lac/petsc_sparse_matrix.h>
#include <lac/petsc_parallel_sparse_matrix.h>
#include <lac/petsc_vector.h>
#ifdef DEAL_II_USE_PETSC
namespace PETScWrappers
{
namespace MatrixIterators
{
void
MatrixBase::const_iterator::Accessor::
visit_present_row ()
{
// if we are asked to visit the
// past-the-end line, then simply
// release all our caches and go on
// with life
if (this->a_row == matrix->m())
{
colnum_cache.reset ();
value_cache.reset ();
return;
}
// otherwise first flush PETSc caches
matrix->compress ();
// get a representation of the present
// row
int ncols;
#if (PETSC_VERSION_MAJOR <= 2) && \
((PETSC_VERSION_MINOR < 2) || \
((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0)))
int *colnums;
PetscScalar *values;
#else
const int *colnums;
const PetscScalar *values;
#endif
int ierr;
ierr = MatGetRow(*matrix, this->a_row, &ncols, &colnums, &values);
AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr));
// copy it into our caches if the line
// isn't empty. if it is, then we've
// done something wrong, since we
// shouldn't have initialized an
// iterator for an empty line (what
// would it point to?)
Assert (ncols != 0, ExcInternalError());
colnum_cache.reset (new std::vector<unsigned int> (colnums,
colnums+ncols));
value_cache.reset (new std::vector<PetscScalar> (values, values+ncols));
// and finally restore the matrix
ierr = MatRestoreRow(*matrix, this->a_row, &ncols, &colnums, &values);
AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr));
}
}
MatrixBase::MatrixBase ()
:
last_action (LastAction::none)
{}
MatrixBase::~MatrixBase ()
{
const int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::clear ()
{
// destroy the matrix...
int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// ...and replace it by an empty
// sequential matrix
const int m=0, n=0, n_nonzero_per_row=0;
ierr = MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, n_nonzero_per_row,
0, &matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
MatrixBase &
MatrixBase::operator = (const double d)
{
Assert (d==0, ExcScalarAssignmentOnlyForZeroValue());
// flush previously cached elements. this
// seems to be necessary since petsc
// 2.2.1, at least for parallel vectors
// (see test bits/petsc_64)
compress ();
const int ierr = MatZeroEntries (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return *this;
}
void
MatrixBase::set (const unsigned int i,
const unsigned int j,
const PetscScalar value)
{
if (last_action != LastAction::insert)
{
int ierr;
ierr = MatAssemblyBegin(matrix,MAT_FLUSH_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = MatAssemblyEnd(matrix,MAT_FLUSH_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
const signed int petsc_i = i;
const signed int petsc_j = j;
const int ierr
= MatSetValues (matrix, 1, &petsc_i, 1, &petsc_j,
&value, INSERT_VALUES);
AssertThrow (ierr == 0, ExcPETScError(ierr));
last_action = LastAction::insert;
}
void
MatrixBase::add (const unsigned int i,
const unsigned int j,
const PetscScalar value)
{
if (last_action != LastAction::add)
{
int ierr;
ierr = MatAssemblyBegin(matrix,MAT_FLUSH_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = MatAssemblyEnd(matrix,MAT_FLUSH_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
last_action = LastAction::add;
}
// we have to do above actions in any
// case to be consistent with the MPI
// communication model (see the
// comments in the documentation of
// PETScWrappers::MPI::Vector), but we
// can save some work if the addend is
// zero
if (value == 0)
return;
const signed int petsc_i = i;
const signed int petsc_j = j;
const int ierr
= MatSetValues (matrix, 1, &petsc_i, 1, &petsc_j,
&value, ADD_VALUES);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::clear_row (const unsigned int row)
{
compress ();
// now set all the entries of this row to
// zero
IS index_set;
#if (PETSC_VERSION_MAJOR <= 2) && (PETSC_VERSION_MINOR <= 2)
const int petsc_row = row;
#else
const PetscInt petsc_row = row;
#endif
ISCreateGeneral (get_mpi_communicator(), 1, &petsc_row, &index_set);
static const PetscScalar zero = 0;
const int ierr
= MatZeroRows(matrix, index_set, &zero);
AssertThrow (ierr == 0, ExcPETScError(ierr));
compress ();
}
void
MatrixBase::clear_rows (const std::vector<unsigned int> &rows)
{
compress ();
// now set all the entries of these rows
// to zero
IS index_set;
#if (PETSC_VERSION_MAJOR <= 2) && (PETSC_VERSION_MINOR <= 2)
const std::vector<int> petsc_rows (rows.begin(), rows.end());
#else
const std::vector<PetscInt> petsc_rows (rows.begin(), rows.end());
#endif
// call the functions. note that we have
// to call them even if #rows is empty,
// since this is a collective operation
ISCreateGeneral (get_mpi_communicator(), rows.size(),
&petsc_rows[0], &index_set);
static const PetscScalar zero = 0;
const int ierr
= MatZeroRows(matrix, index_set, &zero);
AssertThrow (ierr == 0, ExcPETScError(ierr));
compress ();
}
PetscScalar
MatrixBase::el (const unsigned int i,
const unsigned int j) const
{
const signed int petsc_i = i;
const signed int petsc_j = j;
PetscScalar value;
const int ierr
= MatGetValues (matrix, 1, &petsc_i, 1, &petsc_j,
&value);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return value;
}
PetscScalar
MatrixBase::diag_element (const unsigned int i) const
{
Assert (m() == n(), ExcNotQuadratic());
// this doesn't seem to work any
// different than any other element
return el(i,i);
}
void
MatrixBase::compress ()
{
// flush buffers
int ierr;
ierr = MatAssemblyBegin (matrix,MAT_FINAL_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = MatAssemblyEnd (matrix,MAT_FINAL_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// try to compress the representation
ierr = MatCompress (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
unsigned int
MatrixBase::m () const
{
int n_rows, n_cols;
int ierr = MatGetSize (matrix, &n_rows, &n_cols);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return n_rows;
}
unsigned int
MatrixBase::n () const
{
int n_rows, n_cols;
int ierr = MatGetSize (matrix, &n_rows, &n_cols);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return n_cols;
}
unsigned int
MatrixBase::local_size () const
{
int n_rows, n_cols;
int ierr = MatGetLocalSize (matrix, &n_rows, &n_cols);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return n_rows;
}
std::pair<unsigned int, unsigned int>
MatrixBase::local_range () const
{
int begin, end;
const int ierr = MatGetOwnershipRange (static_cast<const Mat &>(matrix),
&begin, &end);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return std::make_pair (begin, end);
}
unsigned int
MatrixBase::n_nonzero_elements () const
{
MatInfo mat_info;
const int ierr
= MatGetInfo (matrix, MAT_GLOBAL_SUM, &mat_info);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return static_cast<unsigned int>(mat_info.nz_used);
}
unsigned int
MatrixBase::
row_length (const unsigned int row) const
{
//TODO: this function will probably only work if compress() was called on the
//matrix previously. however, we can't do this here, since it would impose
//global communication and one would have to make sure that this function is
//called the same number of times from all processors, something that is
//unreasonable. there should simply be a way in PETSc to query the number of
//entries in a row bypassing the call to compress(), but I can't find one
Assert (row < m(), ExcInternalError());
// get a representation of the present
// row
int ncols;
#if (PETSC_VERSION_MAJOR <= 2) && \
((PETSC_VERSION_MINOR < 2) || \
((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0)))
int *colnums;
PetscScalar *values;
#else
const int *colnums;
const PetscScalar *values;
#endif
//TODO: this is probably horribly inefficient; we should lobby for a way to
//query this information from PETSc
int ierr;
ierr = MatGetRow(*this, row, &ncols, &colnums, &values);
AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr));
// then restore the matrix and return the
// number of columns in this row as
// queried previously
ierr = MatRestoreRow(*this, row, &ncols, &colnums, &values);
AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr));
return ncols;
}
PetscReal
MatrixBase::l1_norm () const
{
PetscReal result;
const int ierr
= MatNorm (matrix, NORM_1, &result);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return result;
}
PetscReal
MatrixBase::linfty_norm () const
{
PetscReal result;
const int ierr
= MatNorm (matrix, NORM_INFINITY, &result);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return result;
}
PetscReal
MatrixBase::frobenius_norm () const
{
PetscReal result;
const int ierr
= MatNorm (matrix, NORM_FROBENIUS, &result);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return result;
}
MatrixBase &
MatrixBase::operator *= (const PetscScalar a)
{
#if (PETSC_VERSION_MAJOR <= 2) && (PETSC_VERSION_MINOR < 3)
const int ierr = MatScale (&a, matrix);
#else
const int ierr = MatScale (matrix, a);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
return *this;
}
MatrixBase &
MatrixBase::operator /= (const PetscScalar a)
{
const PetscScalar factor = 1./a;
#if (PETSC_VERSION_MAJOR <= 2) && (PETSC_VERSION_MINOR < 3)
const int ierr = MatScale (&factor, matrix);
#else
const int ierr = MatScale (matrix, factor);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
return *this;
}
void
MatrixBase::vmult (VectorBase &dst,
const VectorBase &src) const
{
Assert (&src != &dst, ExcSourceEqualsDestination());
const int ierr = MatMult (matrix, src, dst);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::Tvmult (VectorBase &dst,
const VectorBase &src) const
{
Assert (&src != &dst, ExcSourceEqualsDestination());
const int ierr = MatMultTranspose (matrix, src, dst);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::vmult_add (VectorBase &dst,
const VectorBase &src) const
{
Assert (&src != &dst, ExcSourceEqualsDestination());
const int ierr = MatMultAdd (matrix, src, dst, dst);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::Tvmult_add (VectorBase &dst,
const VectorBase &src) const
{
Assert (&src != &dst, ExcSourceEqualsDestination());
const int ierr = MatMultTransposeAdd (matrix, src, dst, dst);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
PetscScalar
MatrixBase::matrix_norm_square (const VectorBase &v) const
{
Vector tmp(v.size());
vmult (tmp, v);
return tmp*v;
}
PetscScalar
MatrixBase::matrix_scalar_product (const VectorBase &u,
const VectorBase &v) const
{
Vector tmp(v.size());
vmult (tmp, v);
return u*tmp;
}
PetscScalar
MatrixBase::residual (VectorBase &dst,
const VectorBase &x,
const VectorBase &b) const
{
// avoid the use of a temporary, and
// rather do one negation pass more than
// necessary
vmult (dst, x);
dst -= b;
dst *= -1;
return dst.l2_norm();
}
MatrixBase::operator const Mat () const
{
return matrix;
}
}
#else
// On gcc2.95 on Alpha OSF1, the native assembler does not like empty
// files, so provide some dummy code
namespace { void dummy () {} }
#endif // DEAL_II_USE_PETSC
<commit_msg>Actually, the offending change in petsc seems to have been between 2.2.0 and 2.2.1...<commit_after>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2004, 2005 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <lac/petsc_matrix_base.h>
#include <lac/petsc_full_matrix.h>
#include <lac/petsc_sparse_matrix.h>
#include <lac/petsc_parallel_sparse_matrix.h>
#include <lac/petsc_vector.h>
#ifdef DEAL_II_USE_PETSC
namespace PETScWrappers
{
namespace MatrixIterators
{
void
MatrixBase::const_iterator::Accessor::
visit_present_row ()
{
// if we are asked to visit the
// past-the-end line, then simply
// release all our caches and go on
// with life
if (this->a_row == matrix->m())
{
colnum_cache.reset ();
value_cache.reset ();
return;
}
// otherwise first flush PETSc caches
matrix->compress ();
// get a representation of the present
// row
int ncols;
#if (PETSC_VERSION_MAJOR <= 2) && \
((PETSC_VERSION_MINOR < 2) || \
((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0)))
int *colnums;
PetscScalar *values;
#else
const int *colnums;
const PetscScalar *values;
#endif
int ierr;
ierr = MatGetRow(*matrix, this->a_row, &ncols, &colnums, &values);
AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr));
// copy it into our caches if the line
// isn't empty. if it is, then we've
// done something wrong, since we
// shouldn't have initialized an
// iterator for an empty line (what
// would it point to?)
Assert (ncols != 0, ExcInternalError());
colnum_cache.reset (new std::vector<unsigned int> (colnums,
colnums+ncols));
value_cache.reset (new std::vector<PetscScalar> (values, values+ncols));
// and finally restore the matrix
ierr = MatRestoreRow(*matrix, this->a_row, &ncols, &colnums, &values);
AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr));
}
}
MatrixBase::MatrixBase ()
:
last_action (LastAction::none)
{}
MatrixBase::~MatrixBase ()
{
const int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::clear ()
{
// destroy the matrix...
int ierr = MatDestroy (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// ...and replace it by an empty
// sequential matrix
const int m=0, n=0, n_nonzero_per_row=0;
ierr = MatCreateSeqAIJ(PETSC_COMM_SELF, m, n, n_nonzero_per_row,
0, &matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
MatrixBase &
MatrixBase::operator = (const double d)
{
Assert (d==0, ExcScalarAssignmentOnlyForZeroValue());
// flush previously cached elements. this
// seems to be necessary since petsc
// 2.2.1, at least for parallel vectors
// (see test bits/petsc_64)
compress ();
const int ierr = MatZeroEntries (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return *this;
}
void
MatrixBase::set (const unsigned int i,
const unsigned int j,
const PetscScalar value)
{
if (last_action != LastAction::insert)
{
int ierr;
ierr = MatAssemblyBegin(matrix,MAT_FLUSH_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = MatAssemblyEnd(matrix,MAT_FLUSH_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
const signed int petsc_i = i;
const signed int petsc_j = j;
const int ierr
= MatSetValues (matrix, 1, &petsc_i, 1, &petsc_j,
&value, INSERT_VALUES);
AssertThrow (ierr == 0, ExcPETScError(ierr));
last_action = LastAction::insert;
}
void
MatrixBase::add (const unsigned int i,
const unsigned int j,
const PetscScalar value)
{
if (last_action != LastAction::add)
{
int ierr;
ierr = MatAssemblyBegin(matrix,MAT_FLUSH_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = MatAssemblyEnd(matrix,MAT_FLUSH_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
last_action = LastAction::add;
}
// we have to do above actions in any
// case to be consistent with the MPI
// communication model (see the
// comments in the documentation of
// PETScWrappers::MPI::Vector), but we
// can save some work if the addend is
// zero
if (value == 0)
return;
const signed int petsc_i = i;
const signed int petsc_j = j;
const int ierr
= MatSetValues (matrix, 1, &petsc_i, 1, &petsc_j,
&value, ADD_VALUES);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::clear_row (const unsigned int row)
{
compress ();
// now set all the entries of this row to
// zero
IS index_set;
#if (PETSC_VERSION_MAJOR <= 2) && \
((PETSC_VERSION_MINOR < 2) || \
((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0)))
const int petsc_row = row;
#else
const PetscInt petsc_row = row;
#endif
ISCreateGeneral (get_mpi_communicator(), 1, &petsc_row, &index_set);
static const PetscScalar zero = 0;
const int ierr
= MatZeroRows(matrix, index_set, &zero);
AssertThrow (ierr == 0, ExcPETScError(ierr));
compress ();
}
void
MatrixBase::clear_rows (const std::vector<unsigned int> &rows)
{
compress ();
// now set all the entries of these rows
// to zero
IS index_set;
#if (PETSC_VERSION_MAJOR <= 2) && \
((PETSC_VERSION_MINOR < 2) || \
((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0)))
const std::vector<int> petsc_rows (rows.begin(), rows.end());
#else
const std::vector<PetscInt> petsc_rows (rows.begin(), rows.end());
#endif
// call the functions. note that we have
// to call them even if #rows is empty,
// since this is a collective operation
ISCreateGeneral (get_mpi_communicator(), rows.size(),
&petsc_rows[0], &index_set);
static const PetscScalar zero = 0;
const int ierr
= MatZeroRows(matrix, index_set, &zero);
AssertThrow (ierr == 0, ExcPETScError(ierr));
compress ();
}
PetscScalar
MatrixBase::el (const unsigned int i,
const unsigned int j) const
{
const signed int petsc_i = i;
const signed int petsc_j = j;
PetscScalar value;
const int ierr
= MatGetValues (matrix, 1, &petsc_i, 1, &petsc_j,
&value);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return value;
}
PetscScalar
MatrixBase::diag_element (const unsigned int i) const
{
Assert (m() == n(), ExcNotQuadratic());
// this doesn't seem to work any
// different than any other element
return el(i,i);
}
void
MatrixBase::compress ()
{
// flush buffers
int ierr;
ierr = MatAssemblyBegin (matrix,MAT_FINAL_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
ierr = MatAssemblyEnd (matrix,MAT_FINAL_ASSEMBLY);
AssertThrow (ierr == 0, ExcPETScError(ierr));
// try to compress the representation
ierr = MatCompress (matrix);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
unsigned int
MatrixBase::m () const
{
int n_rows, n_cols;
int ierr = MatGetSize (matrix, &n_rows, &n_cols);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return n_rows;
}
unsigned int
MatrixBase::n () const
{
int n_rows, n_cols;
int ierr = MatGetSize (matrix, &n_rows, &n_cols);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return n_cols;
}
unsigned int
MatrixBase::local_size () const
{
int n_rows, n_cols;
int ierr = MatGetLocalSize (matrix, &n_rows, &n_cols);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return n_rows;
}
std::pair<unsigned int, unsigned int>
MatrixBase::local_range () const
{
int begin, end;
const int ierr = MatGetOwnershipRange (static_cast<const Mat &>(matrix),
&begin, &end);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return std::make_pair (begin, end);
}
unsigned int
MatrixBase::n_nonzero_elements () const
{
MatInfo mat_info;
const int ierr
= MatGetInfo (matrix, MAT_GLOBAL_SUM, &mat_info);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return static_cast<unsigned int>(mat_info.nz_used);
}
unsigned int
MatrixBase::
row_length (const unsigned int row) const
{
//TODO: this function will probably only work if compress() was called on the
//matrix previously. however, we can't do this here, since it would impose
//global communication and one would have to make sure that this function is
//called the same number of times from all processors, something that is
//unreasonable. there should simply be a way in PETSc to query the number of
//entries in a row bypassing the call to compress(), but I can't find one
Assert (row < m(), ExcInternalError());
// get a representation of the present
// row
int ncols;
#if (PETSC_VERSION_MAJOR <= 2) && \
((PETSC_VERSION_MINOR < 2) || \
((PETSC_VERSION_MINOR == 2) && (PETSC_VERSION_SUBMINOR == 0)))
int *colnums;
PetscScalar *values;
#else
const int *colnums;
const PetscScalar *values;
#endif
//TODO: this is probably horribly inefficient; we should lobby for a way to
//query this information from PETSc
int ierr;
ierr = MatGetRow(*this, row, &ncols, &colnums, &values);
AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr));
// then restore the matrix and return the
// number of columns in this row as
// queried previously
ierr = MatRestoreRow(*this, row, &ncols, &colnums, &values);
AssertThrow (ierr == 0, MatrixBase::ExcPETScError(ierr));
return ncols;
}
PetscReal
MatrixBase::l1_norm () const
{
PetscReal result;
const int ierr
= MatNorm (matrix, NORM_1, &result);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return result;
}
PetscReal
MatrixBase::linfty_norm () const
{
PetscReal result;
const int ierr
= MatNorm (matrix, NORM_INFINITY, &result);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return result;
}
PetscReal
MatrixBase::frobenius_norm () const
{
PetscReal result;
const int ierr
= MatNorm (matrix, NORM_FROBENIUS, &result);
AssertThrow (ierr == 0, ExcPETScError(ierr));
return result;
}
MatrixBase &
MatrixBase::operator *= (const PetscScalar a)
{
#if (PETSC_VERSION_MAJOR <= 2) && (PETSC_VERSION_MINOR < 3)
const int ierr = MatScale (&a, matrix);
#else
const int ierr = MatScale (matrix, a);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
return *this;
}
MatrixBase &
MatrixBase::operator /= (const PetscScalar a)
{
const PetscScalar factor = 1./a;
#if (PETSC_VERSION_MAJOR <= 2) && (PETSC_VERSION_MINOR < 3)
const int ierr = MatScale (&factor, matrix);
#else
const int ierr = MatScale (matrix, factor);
#endif
AssertThrow (ierr == 0, ExcPETScError(ierr));
return *this;
}
void
MatrixBase::vmult (VectorBase &dst,
const VectorBase &src) const
{
Assert (&src != &dst, ExcSourceEqualsDestination());
const int ierr = MatMult (matrix, src, dst);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::Tvmult (VectorBase &dst,
const VectorBase &src) const
{
Assert (&src != &dst, ExcSourceEqualsDestination());
const int ierr = MatMultTranspose (matrix, src, dst);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::vmult_add (VectorBase &dst,
const VectorBase &src) const
{
Assert (&src != &dst, ExcSourceEqualsDestination());
const int ierr = MatMultAdd (matrix, src, dst, dst);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
void
MatrixBase::Tvmult_add (VectorBase &dst,
const VectorBase &src) const
{
Assert (&src != &dst, ExcSourceEqualsDestination());
const int ierr = MatMultTransposeAdd (matrix, src, dst, dst);
AssertThrow (ierr == 0, ExcPETScError(ierr));
}
PetscScalar
MatrixBase::matrix_norm_square (const VectorBase &v) const
{
Vector tmp(v.size());
vmult (tmp, v);
return tmp*v;
}
PetscScalar
MatrixBase::matrix_scalar_product (const VectorBase &u,
const VectorBase &v) const
{
Vector tmp(v.size());
vmult (tmp, v);
return u*tmp;
}
PetscScalar
MatrixBase::residual (VectorBase &dst,
const VectorBase &x,
const VectorBase &b) const
{
// avoid the use of a temporary, and
// rather do one negation pass more than
// necessary
vmult (dst, x);
dst -= b;
dst *= -1;
return dst.l2_norm();
}
MatrixBase::operator const Mat () const
{
return matrix;
}
}
#else
// On gcc2.95 on Alpha OSF1, the native assembler does not like empty
// files, so provide some dummy code
namespace { void dummy () {} }
#endif // DEAL_II_USE_PETSC
<|endoftext|>
|
<commit_before><commit_msg>half-written test<commit_after>#include "geometry/grassmann.hpp"
#include "geometry/orthogonal_map.hpp"
#include "geometry/permutation.hpp"
#include "geometry/point.hpp"
#include "geometry/rotation.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/si.hpp"
#include "testing_utilities/almost_equals.hpp"
namespace principia {
namespace geometry {
using quantities::Length;
using si::Metre;
using testing::Eq;
using testing_utilities::AlmostEquals;
class AffineMapTest : public testing::Test {
protected:
struct World;
typedef OrthogonalMap<World, World> Orth;
typedef Permutation<World, World> Perm;
typedef Rotation<World, World> Rot;
void SetUp() override {
zero_ = Vector<Length, World>({0 * Metre, 0 * Metre, 0 * Metre});
i_ = Vector<Length, World>({1 * Metre, 0 * Metre, 0 * Metre});
j_ = Vector<Length, World>({0 * Metre, 1 * Metre, 0 * Metre});
k_ = Vector<Length, World>({0 * Metre, 0 * Metre, 1 * Metre});
}
Vector<Length, World> zero_;
Vector<Length, World> i_;
Vector<Length, World> j_;
Vector<Length, World> k_;
Point<Length, World> bottom_left_back_;
};
TEST_F(AffineMapTest, Cube) {
}
} // namespace geometry
} // namespace principia
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2013 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/**
* \file Linux-specific implementation of utf8conv.h
*/
#include "../typedefs.h"
#include "../utf8conv.h"
#include <cstdlib>
#include <clocale>
#include <langinfo.h>
#include <cassert>
#include <cstring>
#include <string>
#include <unistd.h>
using namespace std;
class Startup {
public:
Startup() {
// Since this can fail before main(), we can't rely on cerr etc.
// being initialized. At least give the user a clue...
char *gl = setlocale(LC_ALL, NULL);
char *sl = setlocale(LC_ALL, "");
if (sl == NULL) {
// Couldn't get environment-specified locale, warn user
// and punt to default "C"
char wrnmess[] = "Couldn't load locale, falling back to default\n";
write(STDERR_FILENO, wrnmess, sizeof(wrnmess)/sizeof(*wrnmess)-1);
sl = setlocale(LC_ALL, gl);
}
if (sl == NULL) {
// If we can't get the default, we're really FUBARed
char errmess[] = "Couldn't initialize locale - bailing out\n";
write(STDERR_FILENO, errmess, sizeof(errmess)/sizeof(*errmess)-1);
_exit(2);
}
if (strcmp(nl_langinfo(CODESET), "UTF-8")){
char errmess[] = "Current locale doesn't support UTF-8\n";
write(STDERR_FILENO, errmess, sizeof(errmess)/sizeof(*errmess)-1);
}
}
};
static Startup startup;
size_t pws_os::wcstombs(char *dst, size_t maxdstlen,
const wchar_t *src, size_t , bool )
{
return ::wcstombs(dst, src, maxdstlen) + 1;
}
size_t pws_os::mbstowcs(wchar_t *dst, size_t maxdstlen,
const char *src, size_t , bool )
{
return ::mbstowcs(dst, src, maxdstlen) + 1;
}
wstring pws_os::towc(const char *val)
{
wstring retval(L"");
assert(val != NULL);
int len = strlen(val);
int wsize;
const char *p = val;
wchar_t wvalue;
while (len > 0) {
wsize = mbtowc(&wvalue, p, MB_CUR_MAX);
if (wsize <= 0)
break;
retval += wvalue;
p += wsize;
len -= wsize;
};
return retval;
}
#ifdef UNICODE
std::string pws_os::tomb(const stringT& val)
{
if (!val.empty()) {
const size_t N = std::wcstombs(NULL, val.c_str(), 0);
assert(N > 0);
char* szstr = new char[N+1];
szstr[N] = 0;
std::wcstombs(szstr, val.c_str(), N);
std::string retval(szstr);
delete[] szstr;
return retval;
} else
return string();
}
#else
std::string pws_os::tomb(const stringT& val)
{
return val;
}
#endif
<commit_msg>[1150] Linux: terminating \0 should not be stored as part of string<commit_after>/*
* Copyright (c) 2003-2013 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/**
* \file Linux-specific implementation of utf8conv.h
*/
#include "../typedefs.h"
#include "../utf8conv.h"
#include <cstdlib>
#include <clocale>
#include <langinfo.h>
#include <cassert>
#include <cstring>
#include <string>
#include <unistd.h>
using namespace std;
class Startup {
public:
Startup() {
// Since this can fail before main(), we can't rely on cerr etc.
// being initialized. At least give the user a clue...
char *gl = setlocale(LC_ALL, NULL);
char *sl = setlocale(LC_ALL, "");
if (sl == NULL) {
// Couldn't get environment-specified locale, warn user
// and punt to default "C"
char wrnmess[] = "Couldn't load locale, falling back to default\n";
write(STDERR_FILENO, wrnmess, sizeof(wrnmess)/sizeof(*wrnmess)-1);
sl = setlocale(LC_ALL, gl);
}
if (sl == NULL) {
// If we can't get the default, we're really FUBARed
char errmess[] = "Couldn't initialize locale - bailing out\n";
write(STDERR_FILENO, errmess, sizeof(errmess)/sizeof(*errmess)-1);
_exit(2);
}
if (strcmp(nl_langinfo(CODESET), "UTF-8")){
char errmess[] = "Current locale doesn't support UTF-8\n";
write(STDERR_FILENO, errmess, sizeof(errmess)/sizeof(*errmess)-1);
}
}
};
static Startup startup;
size_t pws_os::wcstombs(char *dst, size_t maxdstlen,
const wchar_t *src, size_t , bool )
{
return ::wcstombs(dst, src, maxdstlen);
}
size_t pws_os::mbstowcs(wchar_t *dst, size_t maxdstlen,
const char *src, size_t , bool )
{
return ::mbstowcs(dst, src, maxdstlen) + 1;
}
wstring pws_os::towc(const char *val)
{
wstring retval(L"");
assert(val != NULL);
int len = strlen(val);
int wsize;
const char *p = val;
wchar_t wvalue;
while (len > 0) {
wsize = mbtowc(&wvalue, p, MB_CUR_MAX);
if (wsize <= 0)
break;
retval += wvalue;
p += wsize;
len -= wsize;
};
return retval;
}
#ifdef UNICODE
std::string pws_os::tomb(const stringT& val)
{
if (!val.empty()) {
const size_t N = std::wcstombs(NULL, val.c_str(), 0);
assert(N > 0);
char* szstr = new char[N+1];
szstr[N] = 0;
std::wcstombs(szstr, val.c_str(), N);
std::string retval(szstr);
delete[] szstr;
return retval;
} else
return string();
}
#else
std::string pws_os::tomb(const stringT& val)
{
return val;
}
#endif
<|endoftext|>
|
<commit_before>// Copyright 2020-2021 The Ray Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "function_helper.h"
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <memory>
#include "ray/util/logging.h"
namespace ray {
namespace internal {
void FunctionHelper::LoadDll(const boost::filesystem::path &lib_path) {
RAY_LOG(INFO) << "Start load library " << lib_path;
auto it = libraries_.find(lib_path.string());
if (it != libraries_.end()) {
return;
}
RAY_CHECK(boost::filesystem::exists(lib_path))
<< lib_path << " dynamic library not found.";
std::shared_ptr<boost::dll::shared_library> lib = nullptr;
try {
lib = std::make_shared<boost::dll::shared_library>(
lib_path.string(), boost::dll::load_mode::type::rtld_lazy);
} catch (std::exception &e) {
RAY_LOG(FATAL) << "Load library failed, lib_path: " << lib_path
<< ", failed reason: " << e.what();
return;
} catch (...) {
RAY_LOG(FATAL) << "Load library failed, lib_path: " << lib_path
<< ", unknown failed reason.";
return;
}
RAY_LOG(INFO) << "Loaded library: " << lib_path << " successfully.";
RAY_CHECK(libraries_.emplace(lib_path.string(), lib).second);
try {
auto entry_func = boost::dll::import_alias<msgpack::sbuffer(
const std::string &, const ArgsBufferList &, msgpack::sbuffer *)>(
*lib, "TaskExecutionHandler");
auto function_names = LoadAllRemoteFunctions(lib_path.string(), *lib, entry_func);
if (function_names.empty()) {
RAY_LOG(WARNING) << "No remote functions in library " << lib_path
<< ", maybe it's not a dynamic library of Ray application.";
lib->unload();
return;
}
RAY_LOG(INFO) << "The lib path: " << lib_path
<< ", all remote functions: " << function_names;
return;
} catch (std::exception &e) {
RAY_LOG(WARNING) << "Get execute function failed, lib_path: " << lib_path
<< ", failed reason: " << e.what();
lib->unload();
} catch (...) {
RAY_LOG(WARNING) << "Get execute function failed, lib_path: " << lib_path
<< ", unknown failed reason.";
lib->unload();
}
return;
}
std::string FunctionHelper::LoadAllRemoteFunctions(const std::string lib_path,
const boost::dll::shared_library &lib,
const EntryFuntion &entry_function) {
static const std::string internal_function_name = "GetRemoteFunctions";
if (!lib.has(internal_function_name)) {
RAY_LOG(WARNING) << "Internal function '" << internal_function_name
<< "' not found in " << lib_path;
return "";
}
// Both default worker and user dynamic library static link libray_api.so which has a
// singleton class RayRuntimeHolder, the user dynamic library will get a new un-init
// instance of RayRuntimeHolder, so we need to init the RayRuntimeHolder singleton when
// loading the user dynamic library to make sure the new instance valid.
auto init_func =
boost::dll::import_alias<void(std::shared_ptr<RayRuntime>)>(lib, "InitRayRuntime");
init_func(RayRuntimeHolder::Instance().Runtime());
auto get_remote_func = boost::dll::import_alias<
std::pair<const RemoteFunctionMap_t &, const RemoteMemberFunctionMap_t &>()>(
lib, internal_function_name);
std::string names_str;
auto function_maps = get_remote_func();
for (const auto &pair : function_maps.first) {
names_str.append(pair.first).append(", ");
remote_funcs_.emplace(pair.first, entry_function);
}
for (const auto &pair : function_maps.second) {
names_str.append(pair.first).append(", ");
remote_member_funcs_.emplace(pair.first, entry_function);
}
if (!names_str.empty()) {
names_str.pop_back();
names_str.pop_back();
}
return names_str;
}
void FindDynamicLibrary(boost::filesystem::path path,
std::list<boost::filesystem::path> &dynamic_libraries) {
#if defined(_WIN32)
static const std::unordered_set<std::string> dynamic_library_extension = {".dll"};
#elif __APPLE__
static const std::unordered_set<std::string> dynamic_library_extension = {".dylib",
".so"};
#else
static const std::unordered_set<std::string> dynamic_library_extension = {".so"};
#endif
auto extension = boost::filesystem::extension(path);
if (dynamic_library_extension.find(extension) != dynamic_library_extension.end()) {
RAY_LOG(INFO) << path << " dynamic library found.";
dynamic_libraries.emplace_back(path);
}
}
void FunctionHelper::LoadFunctionsFromPaths(const std::vector<std::string> &paths) {
std::list<boost::filesystem::path> dynamic_libraries;
// Lookup dynamic libraries from paths.
for (auto path : paths) {
if (boost::filesystem::is_directory(path)) {
for (auto &entry :
boost::make_iterator_range(boost::filesystem::directory_iterator(path), {})) {
FindDynamicLibrary(entry, dynamic_libraries);
}
} else if (boost::filesystem::exists(path)) {
FindDynamicLibrary(path, dynamic_libraries);
} else {
RAY_LOG(FATAL) << path << " dynamic library not found.";
}
}
// Try to load all found libraries.
for (auto lib : dynamic_libraries) {
LoadDll(lib);
}
}
const EntryFuntion &FunctionHelper::GetExecutableFunctions(
const std::string &function_name) {
auto it = remote_funcs_.find(function_name);
if (it == remote_funcs_.end()) {
throw RayFunctionNotFound("Executable function not found, the function name " +
function_name);
} else {
return it->second;
}
}
const EntryFuntion &FunctionHelper::GetExecutableMemberFunctions(
const std::string &function_name) {
auto it = remote_member_funcs_.find(function_name);
if (it == remote_member_funcs_.end()) {
throw RayFunctionNotFound("Executable member function not found, the function name " +
function_name);
} else {
return it->second;
}
}
} // namespace internal
} // namespace ray<commit_msg>[C++ worker] optimize the log of dynamic library loading (#26120)<commit_after>// Copyright 2020-2021 The Ray Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "function_helper.h"
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <memory>
#include "ray/util/logging.h"
namespace ray {
namespace internal {
void FunctionHelper::LoadDll(const boost::filesystem::path &lib_path) {
RAY_LOG(INFO) << "Start loading the library " << lib_path << ".";
auto it = libraries_.find(lib_path.string());
if (it != libraries_.end()) {
return;
}
RAY_CHECK(boost::filesystem::exists(lib_path))
<< lib_path << " dynamic library not found.";
std::shared_ptr<boost::dll::shared_library> lib = nullptr;
try {
lib = std::make_shared<boost::dll::shared_library>(
lib_path.string(), boost::dll::load_mode::type::rtld_lazy);
} catch (std::exception &e) {
RAY_LOG(FATAL) << "Failed to load library, lib_path: " << lib_path
<< ", failed reason: " << e.what();
return;
} catch (...) {
RAY_LOG(FATAL) << "Failed to load library, lib_path: " << lib_path
<< ", unknown failed reason.";
return;
}
RAY_CHECK(libraries_.emplace(lib_path.string(), lib).second);
try {
auto entry_func = boost::dll::import_alias<msgpack::sbuffer(
const std::string &, const ArgsBufferList &, msgpack::sbuffer *)>(
*lib, "TaskExecutionHandler");
auto function_names = LoadAllRemoteFunctions(lib_path.string(), *lib, entry_func);
if (function_names.empty()) {
RAY_LOG(WARNING)
<< "No remote functions in library " << lib_path
<< ". If you've already used Ray::Task or Ray::Actor in the library, please "
"ensure the remote functions have been registered by `RAY_REMOTE` macro.";
lib->unload();
return;
}
RAY_LOG(INFO) << "The library " << lib_path
<< " is loaded successfully. The remote functions: " << function_names
<< ".";
return;
} catch (boost::system::system_error &e) {
RAY_LOG(INFO) << "The library " << lib_path << " isn't integrated with Ray, skip it.";
lib->unload();
} catch (std::exception &e) {
RAY_LOG(WARNING) << "Failed to get entry function from library: " << lib_path
<< ", failed reason: " << e.what();
lib->unload();
} catch (...) {
RAY_LOG(WARNING) << "Failed to get entry function from library: " << lib_path
<< ", unknown failed reason.";
lib->unload();
}
return;
}
std::string FunctionHelper::LoadAllRemoteFunctions(const std::string lib_path,
const boost::dll::shared_library &lib,
const EntryFuntion &entry_function) {
static const std::string internal_function_name = "GetRemoteFunctions";
if (!lib.has(internal_function_name)) {
RAY_LOG(WARNING) << "Internal function '" << internal_function_name
<< "' not found in " << lib_path;
return "";
}
// Both default worker and user dynamic library static link libray_api.so which has a
// singleton class RayRuntimeHolder, the user dynamic library will get a new un-init
// instance of RayRuntimeHolder, so we need to init the RayRuntimeHolder singleton when
// loading the user dynamic library to make sure the new instance valid.
auto init_func =
boost::dll::import_alias<void(std::shared_ptr<RayRuntime>)>(lib, "InitRayRuntime");
init_func(RayRuntimeHolder::Instance().Runtime());
auto get_remote_func = boost::dll::import_alias<
std::pair<const RemoteFunctionMap_t &, const RemoteMemberFunctionMap_t &>()>(
lib, internal_function_name);
std::string names_str;
auto function_maps = get_remote_func();
for (const auto &pair : function_maps.first) {
names_str.append(pair.first).append(", ");
remote_funcs_.emplace(pair.first, entry_function);
}
for (const auto &pair : function_maps.second) {
names_str.append(pair.first).append(", ");
remote_member_funcs_.emplace(pair.first, entry_function);
}
if (!names_str.empty()) {
names_str.pop_back();
names_str.pop_back();
}
return names_str;
}
void FindDynamicLibrary(boost::filesystem::path path,
std::list<boost::filesystem::path> &dynamic_libraries) {
#if defined(_WIN32)
static const std::unordered_set<std::string> dynamic_library_extension = {".dll"};
#elif __APPLE__
static const std::unordered_set<std::string> dynamic_library_extension = {".dylib",
".so"};
#else
static const std::unordered_set<std::string> dynamic_library_extension = {".so"};
#endif
auto extension = boost::filesystem::extension(path);
if (dynamic_library_extension.find(extension) != dynamic_library_extension.end()) {
dynamic_libraries.emplace_back(path);
}
}
void FunctionHelper::LoadFunctionsFromPaths(const std::vector<std::string> &paths) {
std::list<boost::filesystem::path> dynamic_libraries;
// Lookup dynamic libraries from paths.
for (auto path : paths) {
if (boost::filesystem::is_directory(path)) {
for (auto &entry :
boost::make_iterator_range(boost::filesystem::directory_iterator(path), {})) {
FindDynamicLibrary(entry, dynamic_libraries);
}
} else if (boost::filesystem::exists(path)) {
FindDynamicLibrary(path, dynamic_libraries);
} else {
RAY_LOG(FATAL) << path << " dynamic library not found.";
}
}
// Try to load all found libraries.
for (auto lib : dynamic_libraries) {
LoadDll(lib);
}
}
const EntryFuntion &FunctionHelper::GetExecutableFunctions(
const std::string &function_name) {
auto it = remote_funcs_.find(function_name);
if (it == remote_funcs_.end()) {
throw RayFunctionNotFound("Executable function not found, the function name " +
function_name);
} else {
return it->second;
}
}
const EntryFuntion &FunctionHelper::GetExecutableMemberFunctions(
const std::string &function_name) {
auto it = remote_member_funcs_.find(function_name);
if (it == remote_member_funcs_.end()) {
throw RayFunctionNotFound("Executable member function not found, the function name " +
function_name);
} else {
return it->second;
}
}
} // namespace internal
} // namespace ray<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chrome_process_util.h"
#include <vector>
#include <set>
#include "base/process_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/result_codes.h"
using base::Time;
using base::TimeDelta;
void TerminateAllChromeProcesses(const FilePath& data_dir) {
// Total time the function will wait for chrome processes
// to terminate after it told them to do so.
const TimeDelta kExitTimeout = TimeDelta::FromMilliseconds(5000);
ChromeProcessList process_pids(GetRunningChromeProcesses(data_dir));
std::vector<base::ProcessHandle> handles;
{
ChromeProcessList::const_iterator it;
for (it = process_pids.begin(); it != process_pids.end(); ++it) {
base::ProcessHandle handle;
// Ignore processes for which we can't open the handle. We don't guarantee
// that all processes will terminate, only try to do so.
if (base::OpenPrivilegedProcessHandle(*it, &handle))
handles.push_back(handle);
}
}
std::vector<base::ProcessHandle>::const_iterator it;
for (it = handles.begin(); it != handles.end(); ++it)
base::KillProcess(*it, ResultCodes::TASKMAN_KILL, false);
const Time start = Time::Now();
for (it = handles.begin();
it != handles.end() && Time::Now() - start < kExitTimeout;
++it) {
int64 wait_time_ms = (Time::Now() - start).InMilliseconds();
base::WaitForSingleProcess(*it, wait_time_ms);
}
for (it = handles.begin(); it != handles.end(); ++it)
base::CloseProcessHandle(*it);
}
class ChildProcessFilter : public base::ProcessFilter {
public:
explicit ChildProcessFilter(base::ProcessId parent_pid)
: parent_pids_(&parent_pid, (&parent_pid) + 1) {}
explicit ChildProcessFilter(std::vector<base::ProcessId> parent_pids)
: parent_pids_(parent_pids.begin(), parent_pids.end()) {}
virtual bool Includes(base::ProcessId pid, base::ProcessId parent_pid) const {
return parent_pids_.find(parent_pid) != parent_pids_.end();
}
private:
const std::set<base::ProcessId> parent_pids_;
DISALLOW_COPY_AND_ASSIGN(ChildProcessFilter);
};
ChromeProcessList GetRunningChromeProcesses(const FilePath& data_dir) {
ChromeProcessList result;
base::ProcessId browser_pid = ChromeBrowserProcessId(data_dir);
if (browser_pid == (base::ProcessId) -1)
return result;
ChildProcessFilter filter(browser_pid);
base::NamedProcessIterator it(chrome::kBrowserProcessExecutableName, &filter);
const ProcessEntry* process_entry;
while ((process_entry = it.NextProcessEntry())) {
#if defined(OS_WIN)
result.push_back(process_entry->th32ProcessID);
#elif defined(OS_POSIX)
result.push_back(process_entry->pid);
#endif
}
#if defined(OS_LINUX)
// On Linux we might be running with a zygote process for the renderers.
// Because of that we sweep the list of processes again and pick those which
// are children of one of the processes that we've already seen.
{
ChildProcessFilter filter(result);
base::NamedProcessIterator it(chrome::kBrowserProcessExecutableName,
&filter);
while ((process_entry = it.NextProcessEntry()))
result.push_back(process_entry->pid);
}
#endif
result.push_back(browser_pid);
return result;
}
<commit_msg>Increase timeout when terminating Chrome processes in tests.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/chrome_process_util.h"
#include <vector>
#include <set>
#include "base/process_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/result_codes.h"
using base::Time;
using base::TimeDelta;
void TerminateAllChromeProcesses(const FilePath& data_dir) {
// Total time the function will wait for chrome processes
// to terminate after it told them to do so.
const TimeDelta kExitTimeout = TimeDelta::FromSeconds(30);
ChromeProcessList process_pids(GetRunningChromeProcesses(data_dir));
std::vector<base::ProcessHandle> handles;
{
ChromeProcessList::const_iterator it;
for (it = process_pids.begin(); it != process_pids.end(); ++it) {
base::ProcessHandle handle;
// Ignore processes for which we can't open the handle. We don't guarantee
// that all processes will terminate, only try to do so.
if (base::OpenPrivilegedProcessHandle(*it, &handle))
handles.push_back(handle);
}
}
std::vector<base::ProcessHandle>::const_iterator it;
for (it = handles.begin(); it != handles.end(); ++it)
base::KillProcess(*it, ResultCodes::TASKMAN_KILL, false);
const Time start = Time::Now();
for (it = handles.begin();
it != handles.end() && Time::Now() - start < kExitTimeout;
++it) {
int64 wait_time_ms = (Time::Now() - start).InMilliseconds();
base::WaitForSingleProcess(*it, wait_time_ms);
}
for (it = handles.begin(); it != handles.end(); ++it)
base::CloseProcessHandle(*it);
}
class ChildProcessFilter : public base::ProcessFilter {
public:
explicit ChildProcessFilter(base::ProcessId parent_pid)
: parent_pids_(&parent_pid, (&parent_pid) + 1) {}
explicit ChildProcessFilter(std::vector<base::ProcessId> parent_pids)
: parent_pids_(parent_pids.begin(), parent_pids.end()) {}
virtual bool Includes(base::ProcessId pid, base::ProcessId parent_pid) const {
return parent_pids_.find(parent_pid) != parent_pids_.end();
}
private:
const std::set<base::ProcessId> parent_pids_;
DISALLOW_COPY_AND_ASSIGN(ChildProcessFilter);
};
ChromeProcessList GetRunningChromeProcesses(const FilePath& data_dir) {
ChromeProcessList result;
base::ProcessId browser_pid = ChromeBrowserProcessId(data_dir);
if (browser_pid == (base::ProcessId) -1)
return result;
ChildProcessFilter filter(browser_pid);
base::NamedProcessIterator it(chrome::kBrowserProcessExecutableName, &filter);
const ProcessEntry* process_entry;
while ((process_entry = it.NextProcessEntry())) {
#if defined(OS_WIN)
result.push_back(process_entry->th32ProcessID);
#elif defined(OS_POSIX)
result.push_back(process_entry->pid);
#endif
}
#if defined(OS_LINUX)
// On Linux we might be running with a zygote process for the renderers.
// Because of that we sweep the list of processes again and pick those which
// are children of one of the processes that we've already seen.
{
ChildProcessFilter filter(result);
base::NamedProcessIterator it(chrome::kBrowserProcessExecutableName,
&filter);
while ((process_entry = it.NextProcessEntry()))
result.push_back(process_entry->pid);
}
#endif
result.push_back(browser_pid);
return result;
}
<|endoftext|>
|
<commit_before>#include "fenetre.h"
#include "ui_fenetre.h"
#include "fileManagement.h"
//#include <QMessageBox>
Fenetre::Fenetre(QWidget *parent) : QMainWindow(parent), ui(new Ui::Fenetre)
{
ui->setupUi(this);
//on connecte les Qapplication
connect(ui->actionNouveau,SIGNAL(triggered()),this,SLOT(nouveauFichier()));
connect(ui->actionOuvrir,SIGNAL(triggered()),this,SLOT(ouvrirFichier()));
connect(ui->actionSauvegarder,SIGNAL(triggered()),this,SLOT(sauvegarderFichier()));
connect(ui->actionQuitter,SIGNAL(triggered()),qApp,SLOT(quit()));
index = loadIndexFromFile("runes.index"); //on charge les runes
//on charge les icones des runes;
vectorPixRune.push_back(new QPixmap("marque_ico.png"));
vectorPixRune.push_back(new QPixmap("sceau_ico.png"));
vectorPixRune.push_back(new QPixmap("glyphe_ico.png"));
vectorPixRune.push_back(new QPixmap("quint_ico.png"));
for (auto &a : index)
{
QHBoxLayout* layout = new QHBoxLayout; //layout de l'élément
QLabel* ico = new QLabel; //icone de rune
ico->setPixmap(vectorPixRune[static_cast<unsigned>(a.getType())]->scaledToHeight(50,Qt::SmoothTransformation)); //on resize
QLabel* nom = new QLabel(a.getColoredName()); //on met le nom coloré de la rune
nom->setWordWrap(true);
nom->setMaximumWidth(200);
QLabel* intEffet = new QLabel(a.getColoredEffect());
layout->addWidget(ico);
layout->addWidget(nom);
layout->addWidget(intEffet);
QListWidgetItem* item = new QListWidgetItem();
ui->DRunelist->addItem(item); //temporaire
QWidget* wi = new QWidget;
wi->setLayout(layout);
item->setSizeHint(wi->sizeHint());
ui->DRunelist->setItemWidget(item,wi);
}
connect(ui->DRunelist,SIGNAL(clicked(QModelIndex)),this,SLOT(ajouteBonneList(QModelIndex))); //on connecte pour que quand on clique on ajoute la rune.
//on connecte pour qu'on pouisse supprimer les runes des petites listes
connect(ui->MarquesList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerMarque(QModelIndex)));
connect(ui->SceauxList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerSceau(QModelIndex)));
connect(ui->GlyphesList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerGlyphe(QModelIndex)));
connect(ui->QuintList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerQuint(QModelIndex)));
}
Fenetre::~Fenetre()
{
delete ui;
}
void Fenetre::supprimerMarque(QModelIndex ind)
{
page.remove(RuneType::Marque, ind.row()); //on supprime la bonne rune
ui->MarquesList->removeItemWidget(ui->MarquesList->currentItem()); //on delete l'item
updateStats();
}
void Fenetre::supprimerSceau(QModelIndex ind)
{
page.remove(RuneType::Sceau, ind.row()); //on supprime la bonne rune
ui->SceauxList->removeItemWidget(ui->SceauxList->currentItem()); //on delete l'item
updateStats();
}
void Fenetre::supprimerGlyphe(QModelIndex ind)
{
page.remove(RuneType::Glyphe, ind.row()); //on supprime la bonne rune
ui->GlyphesList->removeItemWidget(ui->GlyphesList->currentItem()); //on delete l'item
updateStats();
}
void Fenetre::supprimerQuint(QModelIndex ind)
{
page.remove(RuneType::Quint, ind.row()); //on supprime la bonne rune
ui->QuintList->removeItemWidget(ui->QuintList->currentItem()); //on delete l'item
updateStats();
}
void Fenetre::ajouteBonneList(QModelIndex ind)
{
bool success = page.ajouterRune(index[ind.row()]); //On ajoute le bon index à la runepage. théoriquement c'est bon.
if (success) //on a jouté la rune
{
if (index[ind.row()].getType() == RuneType::Marque) //on a cliqué sur une marque
{
addToList(ui->MarquesList, index[ind.row()]); //on ajoute à la liste des marques
}
else if (index[ind.row()].getType() == RuneType::Sceau) //on a cliqué sur un sceau
{
addToList(ui->SceauxList, index[ind.row()]); //on ajoute à la liste des sceaux
}
else if (index[ind.row()].getType() == RuneType::Glyphe) //on a cliqué sur un glyphe
{
addToList(ui->GlyphesList, index[ind.row()]); //on ajoute à la liste des glyphes
}
else if (index[ind.row()].getType() == RuneType::Quint) //on a cliqué sur une quintessence
{
addToList(ui->QuintList, index[ind.row()]); //on ajoute à la liste des quints
}
}
updateStats();
}
void Fenetre::addToList(QListWidget* list, Rune const& rune)
{
QHBoxLayout* layout = new QHBoxLayout; //layout de l'élément
QLabel* nom = new QLabel(rune.getColoredName(7)); //on met le nom coloré de la rune
nom->setWordWrap(true);
nom->setMaximumWidth(125);
QLabel* intEffet = new QLabel(rune.getColoredEffect(8));
layout->addWidget(nom);
layout->addWidget(intEffet);
QListWidgetItem* item = new QListWidgetItem();
list->addItem(item); //temporaire
QWidget* wi = new QWidget;
wi->setLayout(layout);
item->setSizeHint(wi->sizeHint());
list->setItemWidget(item,wi);
}
void Fenetre::nouveauFichier()
{
//on vide les listes
ui->MarquesList->clear();
ui->SceauxList->clear();
ui->GlyphesList->clear();
ui->QuintList->clear();
//on vide la page
page.clear();
updateStats();
}
void Fenetre::ouvrirFichier()
{
//rien pour le moment
}
void Fenetre::sauvegarderFichier()
{
//rien non plus
}
void Fenetre::updateStats()
{
if (ui->MarquesList->count() == 0 && ui->SceauxList->count() == 0 && ui->GlyphesList->count() == 0 && ui->QuintList->count() == 0) //les listes sont toutes vides
{
ui->StatLabel->setText(""); //on vide le texte
}
else
{
QString newLabel{"<html><head/><body>"};
QString tmp{""};
std::vector<Effet> allEffect = page.getAllEffect(); //on récupère tous les effets de la page !
for (auto &a : allEffect) //on parcoure tous les effets
{
tmp = (a.second > 0) ? "<span style=\" color:#d00000; font-size:20pt; font-weight:400\">+ " : "<span style=\" color:#0267b5; font-size:20pt; font-weight:400\">- "; //on prend le signe du bonus
//+/- XX STAT (avec de la coloration et STAT en italique)
newLabel += "<p align=\"center\">" + tmp + QString::number(abs(a.second)) + " </span><span style=\" font-style:italic; color:#000000; font-size:20pt; font-weight:600\">" + a.first.c_str() + "</span></p>";
}
newLabel += "</body></html>"; //on finit la mise en page
ui->StatLabel->setText(newLabel);
}
}
<commit_msg>Youpi on peut supprimmer correctement ! (Efin faut règler un bug sur la suppression des quints :()<commit_after>#include "fenetre.h"
#include "ui_fenetre.h"
#include "fileManagement.h"
//#include <QMessageBox>
Fenetre::Fenetre(QWidget *parent) : QMainWindow(parent), ui(new Ui::Fenetre)
{
ui->setupUi(this);
//on connecte les Qapplication
connect(ui->actionNouveau,SIGNAL(triggered()),this,SLOT(nouveauFichier()));
connect(ui->actionOuvrir,SIGNAL(triggered()),this,SLOT(ouvrirFichier()));
connect(ui->actionSauvegarder,SIGNAL(triggered()),this,SLOT(sauvegarderFichier()));
connect(ui->actionQuitter,SIGNAL(triggered()),qApp,SLOT(quit()));
index = loadIndexFromFile("runes.index"); //on charge les runes
//on charge les icones des runes;
vectorPixRune.push_back(new QPixmap("marque_ico.png"));
vectorPixRune.push_back(new QPixmap("sceau_ico.png"));
vectorPixRune.push_back(new QPixmap("glyphe_ico.png"));
vectorPixRune.push_back(new QPixmap("quint_ico.png"));
for (auto &a : index)
{
QHBoxLayout* layout = new QHBoxLayout; //layout de l'élément
QLabel* ico = new QLabel; //icone de rune
ico->setPixmap(vectorPixRune[static_cast<unsigned>(a.getType())]->scaledToHeight(50,Qt::SmoothTransformation)); //on resize
QLabel* nom = new QLabel(a.getColoredName()); //on met le nom coloré de la rune
nom->setWordWrap(true);
nom->setMaximumWidth(200);
QLabel* intEffet = new QLabel(a.getColoredEffect());
layout->addWidget(ico);
layout->addWidget(nom);
layout->addWidget(intEffet);
QListWidgetItem* item = new QListWidgetItem();
ui->DRunelist->addItem(item); //temporaire
QWidget* wi = new QWidget;
wi->setLayout(layout);
item->setSizeHint(wi->sizeHint());
ui->DRunelist->setItemWidget(item,wi);
}
connect(ui->DRunelist,SIGNAL(clicked(QModelIndex)),this,SLOT(ajouteBonneList(QModelIndex))); //on connecte pour que quand on clique on ajoute la rune.
//on connecte pour qu'on pouisse supprimer les runes des petites listes
connect(ui->MarquesList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerMarque(QModelIndex)));
connect(ui->SceauxList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerSceau(QModelIndex)));
connect(ui->GlyphesList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerGlyphe(QModelIndex)));
connect(ui->QuintList,SIGNAL(clicked(QModelIndex)),this,SLOT(supprimerQuint(QModelIndex)));
}
Fenetre::~Fenetre()
{
delete ui;
}
void Fenetre::supprimerMarque(QModelIndex ind)
{
page.remove(RuneType::Marque, ind.row()); //on supprime la bonne rune
ui->MarquesList->removeItemWidget(ui->MarquesList->currentItem()); //on delete l'item
ui->MarquesList->takeItem(ind.row()); //on enlève les espaces
updateStats();
}
void Fenetre::supprimerSceau(QModelIndex ind)
{
page.remove(RuneType::Sceau, ind.row()); //on supprime la bonne rune
ui->SceauxList->removeItemWidget(ui->SceauxList->currentItem()); //on delete l'item
ui->SceauxList->takeItem(ind.row()); //on enlève les espaces
updateStats();
}
void Fenetre::supprimerGlyphe(QModelIndex ind)
{
page.remove(RuneType::Glyphe, ind.row()); //on supprime la bonne rune
ui->GlyphesList->removeItemWidget(ui->GlyphesList->currentItem()); //on delete l'item
ui->GlyphesList->takeItem(ind.row()); //on enlève les espaces
updateStats();
}
void Fenetre::supprimerQuint(QModelIndex ind)
{
page.remove(RuneType::Quint, ind.row()); //on supprime la bonne rune
ui->QuintList->removeItemWidget(ui->QuintList->currentItem()); //on delete l'item
ui->QuintList->takeItem(ind.row()); //on enlève les espaces
updateStats();
}
void Fenetre::ajouteBonneList(QModelIndex ind)
{
bool success = page.ajouterRune(index[ind.row()]); //On ajoute le bon index à la runepage. théoriquement c'est bon.
if (success) //on a jouté la rune
{
if (index[ind.row()].getType() == RuneType::Marque) //on a cliqué sur une marque
{
addToList(ui->MarquesList, index[ind.row()]); //on ajoute à la liste des marques
}
else if (index[ind.row()].getType() == RuneType::Sceau) //on a cliqué sur un sceau
{
addToList(ui->SceauxList, index[ind.row()]); //on ajoute à la liste des sceaux
}
else if (index[ind.row()].getType() == RuneType::Glyphe) //on a cliqué sur un glyphe
{
addToList(ui->GlyphesList, index[ind.row()]); //on ajoute à la liste des glyphes
}
else if (index[ind.row()].getType() == RuneType::Quint) //on a cliqué sur une quintessence
{
addToList(ui->QuintList, index[ind.row()]); //on ajoute à la liste des quints
}
}
updateStats();
}
void Fenetre::addToList(QListWidget* list, Rune const& rune)
{
QHBoxLayout* layout = new QHBoxLayout; //layout de l'élément
QLabel* nom = new QLabel(rune.getColoredName(7)); //on met le nom coloré de la rune
nom->setWordWrap(true);
nom->setMaximumWidth(125);
QLabel* intEffet = new QLabel(rune.getColoredEffect(8));
layout->addWidget(nom);
layout->addWidget(intEffet);
QListWidgetItem* item = new QListWidgetItem();
list->addItem(item); //temporaire
QWidget* wi = new QWidget;
wi->setLayout(layout);
item->setSizeHint(wi->sizeHint());
list->setItemWidget(item,wi);
}
void Fenetre::nouveauFichier()
{
//on vide les listes
ui->MarquesList->clear();
ui->SceauxList->clear();
ui->GlyphesList->clear();
ui->QuintList->clear();
//on vide la page
page.clear();
updateStats();
}
void Fenetre::ouvrirFichier()
{
//rien pour le moment
}
void Fenetre::sauvegarderFichier()
{
//rien non plus
}
void Fenetre::updateStats()
{
if (ui->MarquesList->count() == 0 && ui->SceauxList->count() == 0 && ui->GlyphesList->count() == 0 && ui->QuintList->count() == 0) //les listes sont toutes vides
{
ui->StatLabel->setText(""); //on vide le texte
}
else
{
QString newLabel{"<html><head/><body>"};
QString tmp{""};
std::vector<Effet> allEffect = page.getAllEffect(); //on récupère tous les effets de la page !
for (auto &a : allEffect) //on parcoure tous les effets
{
tmp = (a.second > 0) ? "<span style=\" color:#d00000; font-size:20pt; font-weight:400\">+ " : "<span style=\" color:#0267b5; font-size:20pt; font-weight:400\">- "; //on prend le signe du bonus
//+/- XX STAT (avec de la coloration et STAT en italique)
newLabel += "<p align=\"center\">" + tmp + QString::number(abs(a.second)) + " </span><span style=\" font-style:italic; color:#000000; font-size:20pt; font-weight:600\">" + a.first.c_str() + "</span></p>";
}
newLabel += "</body></html>"; //on finit la mise en page
ui->StatLabel->setText(newLabel);
}
}
<|endoftext|>
|
<commit_before>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include "VideoBasedTracker.h"
// Library/third-party includes
// - none
// Standard includes
// - none
namespace osvr {
namespace vbtracker {
void VideoBasedTracker::addOculusSensor() {
/// @todo this clearly violates what I expected was the invariant - not
/// sure if it's because of incomplete Oculus information, or due to a
/// misunderstanding of how this all works.
m_led_groups.emplace_back();
}
void VideoBasedTracker::addSensor(LedIdentifier *identifier,
DoubleVecVec const &m,
std::vector<double> const &d,
DoubleVecVec const &locations,
size_t requiredInliers,
size_t permittedOutliers) {
addSensor(LedIdentifierPtr(identifier), m, d, locations,
requiredInliers, permittedOutliers);
}
void VideoBasedTracker::addSensor(LedIdentifierPtr &&identifier,
DoubleVecVec const &m,
std::vector<double> const &d,
DoubleVecVec const &locations,
size_t requiredInliers,
size_t permittedOutliers) {
m_identifiers.emplace_back(std::move(identifier));
m_estimators.emplace_back(
new BeaconBasedPoseEstimator(m, d, locations,
requiredInliers, permittedOutliers));
m_led_groups.emplace_back();
m_assertInvariants();
}
bool VideoBasedTracker::processImage(cv::Mat frame, cv::Mat grayImage,
PoseHandler handler) {
m_assertInvariants();
bool done = false;
m_frame = frame;
m_imageGray = grayImage;
//================================================================
// Tracking the points
// Threshold the image based on the brightness value that is between
// the darkest and brightest pixel in the image.
double minVal, maxVal;
cv::minMaxLoc(m_imageGray, &minVal, &maxVal);
double thresholdValue = 150;
cv::threshold(m_imageGray, m_thresholdImage, thresholdValue, 255,
CV_THRESH_BINARY);
// Construct a blob detector and find the blobs in the image.
// This set of parameters is optimized for the OSVR HDK prototype
// that has exposed LEDs.
/// @todo: Make a different set of parameters optimized for the
/// Oculus Dk2.
/// @todo: Determine the maximum size of a trackable blob by seeing
/// when we're so close that we can't view at least four in the
/// camera.
cv::SimpleBlobDetector::Params params;
params.minThreshold = static_cast<float>(thresholdValue);
params.maxThreshold = static_cast<float>(thresholdValue + (maxVal - thresholdValue) * 0.3);
params.thresholdStep = (params.maxThreshold - params.minThreshold) / 10;
params.blobColor = static_cast<uchar>(255);
params.filterByColor = false; // Look for bright blobs: there is a bug in this code
params.minInertiaRatio = 0.5;
params.maxInertiaRatio = 1.0;
params.filterByInertia = false; // Do we test for non-elongated blobs?
params.minArea = 1; // How small can the blobs be?
params.filterByConvexity = false; // Test for convexity?
params.filterByCircularity = false; // Test for circularity?
params.minDistBetweenBlobs = 3;
cv::SimpleBlobDetector detector(params);
/// @todo this variable is a candidate for hoisting to member
std::vector<cv::KeyPoint> foundKeyPoints;
detector.detect(m_imageGray, foundKeyPoints);
// TODO: Consider computing the center of mass of a dilated bounding
// rectangle around each keypoint to produce a more precise subpixel
// localization of each LED. The moments() function may be helpful
// with this.
// TODO: Estimate the summed brightness of each blob so that we can
// detect when they are getting brighter and dimmer. Pass this as
// the brightness parameter to the Led class when adding a new one
// or augmenting with a new frame.
// We allow multiple sets of LEDs, each corresponding to a different
// sensor, to be located in the same image. We construct a new set
// of LEDs for each and try to find them. It is assumed that they all
// have unique ID patterns across all sensors.
for (size_t sensor = 0; sensor < m_identifiers.size(); sensor++) {
osvrPose3SetIdentity(&m_pose);
std::vector<cv::KeyPoint> keyPoints = foundKeyPoints;
// Locate the closest blob from this frame to each LED found
// in the previous frame. If it is close enough to the nearest
// neighbor from last time, we assume that it is the same LED and
// update it. If not, we delete the LED from the list. Once we
// have matched a blob to an LED, we remove it from the list. If
// there are any blobs leftover, we create new LEDs from them.
// TODO: Include motion estimate based on Kalman filter along with
// model of the projection once we have one built. Note that this
// will require handling the lens distortion appropriately.
auto led = begin(m_led_groups[sensor]);
auto e = end(m_led_groups[sensor]);
while (led != e) {
double TODO_BLOB_MOVE_THRESHOLD = 10;
auto nearest =
led->nearest(keyPoints, TODO_BLOB_MOVE_THRESHOLD);
if (nearest == keyPoints.end()) {
// We have no blob corresponding to this LED, so we need
// to delete this LED.
led = m_led_groups[sensor].erase(led);
} else {
// Update the values in this LED and then go on to the
// next one. Remove this blob from the list of potential
// matches.
led->addMeasurement(nearest->pt, nearest->size);
keyPoints.erase(nearest);
led++;
}
}
// If we have any blobs that have not been associated with an
// LED, then we add a new LED for each of them.
// std::cout << "Had " << Leds.size() << " LEDs, " <<
// keyPoints.size() << " new ones available" << std::endl;
while (keyPoints.size() > 0) {
osvr::vbtracker::Led newLed(m_identifiers[sensor].get(),
keyPoints.begin()->pt,
keyPoints.begin()->size);
m_led_groups[sensor].push_back(newLed);
keyPoints.erase(keyPoints.begin());
}
//==================================================================
// Compute the pose of the HMD w.r.t. the camera frame of reference.
// TODO: Keep track of whether we already have a good pose and, if
// so, have the algorithm initialize using it so we do less work on
// average.
bool gotPose = false;
if (m_estimators[sensor]) {
OSVR_PoseState pose;
if (m_estimators[sensor]->EstimatePoseFromLeds(
m_led_groups[sensor], pose)) {
m_pose = pose;
handler(static_cast<unsigned>(sensor), pose);
gotPose = true;
}
}
#ifdef VBHMD_DEBUG
// Don't display the debugging info every frame, or we can't go fast enough.
static int count = 0;
if (++count == 11) {
// Draw detected blobs as red circles.
cv::drawKeypoints(m_frame, keyPoints, m_imageWithBlobs,
cv::Scalar(0, 0, 255),
cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
// Label the keypoints with their IDs.
for (led = m_led_groups[sensor].begin();
led != m_led_groups[sensor].end(); led++) {
// Print 1-based LED ID for actual LEDs
auto label = std::to_string(led->getOneBasedID());
cv::Point where = led->getLocation();
where.x += 1;
where.y += 1;
cv::putText(m_imageWithBlobs, label, where,
cv::FONT_HERSHEY_SIMPLEX, 0.5,
cv::Scalar(0, 0, 255));
}
// If we have a transform, reproject all of the points from the
// model space (the LED locations) back into the image and
// display them on the blob image in green.
if (gotPose) {
std::vector<cv::Point2f> imagePoints;
m_estimators[sensor]->ProjectBeaconsToImage(imagePoints);
size_t n = imagePoints.size();
for (size_t i = 0; i < n; ++i) {
// Print 1-based LED IDs
auto label = std::to_string(i + 1);
auto where = imagePoints[i];
where.x += 1;
where.y += 1;
cv::putText(m_imageWithBlobs, label, where,
cv::FONT_HERSHEY_SIMPLEX, 0.5,
cv::Scalar(0, 255, 0));
}
}
// Pick which image to show and show it.
if (m_frame.data) {
std::ostringstream windowName;
windowName << "Sensor" << sensor;
cv::imshow(windowName.str().c_str(), *m_shownImage);
int key = cv::waitKey(1);
switch (key) {
case 'i':
// Show the input image.
m_shownImage = &m_frame;
break;
case 't':
// Show the thresholded image.
m_shownImage = &m_thresholdImage;
break;
case 'b':
// Show the blob image.
m_shownImage = &m_imageWithBlobs;
break;
case 'q':
// Indicate we want to quit.
done = true;
break;
}
}
// Report the pose, if we got one
if (gotPose) {
std::cout << "Pos (sensor " << sensor
<< "): " << m_pose.translation.data[0] << ", "
<< m_pose.translation.data[1] << ", "
<< m_pose.translation.data[2] << std::endl;
}
count = 0;
}
#endif
}
m_assertInvariants();
return done;
}
} // namespace vbtracker
} // namespace osvr
<commit_msg>vbtracker: Fix usage of SimpleBlobDetector for both OpenCV 2.4 and 3<commit_after>/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, 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.
// Internal Includes
#include "VideoBasedTracker.h"
// Library/third-party includes
#include <opencv2/core/version.hpp>
// Standard includes
// - none
namespace osvr {
namespace vbtracker {
void VideoBasedTracker::addOculusSensor() {
/// @todo this clearly violates what I expected was the invariant - not
/// sure if it's because of incomplete Oculus information, or due to a
/// misunderstanding of how this all works.
m_led_groups.emplace_back();
}
void VideoBasedTracker::addSensor(LedIdentifier *identifier,
DoubleVecVec const &m,
std::vector<double> const &d,
DoubleVecVec const &locations,
size_t requiredInliers,
size_t permittedOutliers) {
addSensor(LedIdentifierPtr(identifier), m, d, locations,
requiredInliers, permittedOutliers);
}
void VideoBasedTracker::addSensor(LedIdentifierPtr &&identifier,
DoubleVecVec const &m,
std::vector<double> const &d,
DoubleVecVec const &locations,
size_t requiredInliers,
size_t permittedOutliers) {
m_identifiers.emplace_back(std::move(identifier));
m_estimators.emplace_back(
new BeaconBasedPoseEstimator(m, d, locations,
requiredInliers, permittedOutliers));
m_led_groups.emplace_back();
m_assertInvariants();
}
bool VideoBasedTracker::processImage(cv::Mat frame, cv::Mat grayImage,
PoseHandler handler) {
m_assertInvariants();
bool done = false;
m_frame = frame;
m_imageGray = grayImage;
//================================================================
// Tracking the points
// Threshold the image based on the brightness value that is between
// the darkest and brightest pixel in the image.
double minVal, maxVal;
cv::minMaxLoc(m_imageGray, &minVal, &maxVal);
double thresholdValue = 150;
cv::threshold(m_imageGray, m_thresholdImage, thresholdValue, 255,
CV_THRESH_BINARY);
// Construct a blob detector and find the blobs in the image.
// This set of parameters is optimized for the OSVR HDK prototype
// that has exposed LEDs.
/// @todo: Make a different set of parameters optimized for the
/// Oculus Dk2.
/// @todo: Determine the maximum size of a trackable blob by seeing
/// when we're so close that we can't view at least four in the
/// camera.
cv::SimpleBlobDetector::Params params;
params.minThreshold = static_cast<float>(thresholdValue);
params.maxThreshold = static_cast<float>(thresholdValue + (maxVal - thresholdValue) * 0.3);
params.thresholdStep = (params.maxThreshold - params.minThreshold) / 10;
params.blobColor = static_cast<uchar>(255);
params.filterByColor = false; // Look for bright blobs: there is a bug in this code
params.minInertiaRatio = 0.5;
params.maxInertiaRatio = 1.0;
params.filterByInertia = false; // Do we test for non-elongated blobs?
params.minArea = 1; // How small can the blobs be?
params.filterByConvexity = false; // Test for convexity?
params.filterByCircularity = false; // Test for circularity?
params.minDistBetweenBlobs = 3;
#if CV_MAJOR_VERSION == 2
cv::Ptr<cv::SimpleBlobDetector> detector =
new cv::SimpleBlobDetector(params);
#elif CV_MAJOR_VERSION == 3
auto detector = cv::SimpleBlobDetector::create(params);
#else
#error "Unrecognized OpenCV version!"
#endif
/// @todo this variable is a candidate for hoisting to member
std::vector<cv::KeyPoint> foundKeyPoints;
detector->detect(m_imageGray, foundKeyPoints);
// TODO: Consider computing the center of mass of a dilated bounding
// rectangle around each keypoint to produce a more precise subpixel
// localization of each LED. The moments() function may be helpful
// with this.
// TODO: Estimate the summed brightness of each blob so that we can
// detect when they are getting brighter and dimmer. Pass this as
// the brightness parameter to the Led class when adding a new one
// or augmenting with a new frame.
// We allow multiple sets of LEDs, each corresponding to a different
// sensor, to be located in the same image. We construct a new set
// of LEDs for each and try to find them. It is assumed that they all
// have unique ID patterns across all sensors.
for (size_t sensor = 0; sensor < m_identifiers.size(); sensor++) {
osvrPose3SetIdentity(&m_pose);
std::vector<cv::KeyPoint> keyPoints = foundKeyPoints;
// Locate the closest blob from this frame to each LED found
// in the previous frame. If it is close enough to the nearest
// neighbor from last time, we assume that it is the same LED and
// update it. If not, we delete the LED from the list. Once we
// have matched a blob to an LED, we remove it from the list. If
// there are any blobs leftover, we create new LEDs from them.
// TODO: Include motion estimate based on Kalman filter along with
// model of the projection once we have one built. Note that this
// will require handling the lens distortion appropriately.
auto led = begin(m_led_groups[sensor]);
auto e = end(m_led_groups[sensor]);
while (led != e) {
double TODO_BLOB_MOVE_THRESHOLD = 10;
auto nearest =
led->nearest(keyPoints, TODO_BLOB_MOVE_THRESHOLD);
if (nearest == keyPoints.end()) {
// We have no blob corresponding to this LED, so we need
// to delete this LED.
led = m_led_groups[sensor].erase(led);
} else {
// Update the values in this LED and then go on to the
// next one. Remove this blob from the list of potential
// matches.
led->addMeasurement(nearest->pt, nearest->size);
keyPoints.erase(nearest);
led++;
}
}
// If we have any blobs that have not been associated with an
// LED, then we add a new LED for each of them.
// std::cout << "Had " << Leds.size() << " LEDs, " <<
// keyPoints.size() << " new ones available" << std::endl;
while (keyPoints.size() > 0) {
osvr::vbtracker::Led newLed(m_identifiers[sensor].get(),
keyPoints.begin()->pt,
keyPoints.begin()->size);
m_led_groups[sensor].push_back(newLed);
keyPoints.erase(keyPoints.begin());
}
//==================================================================
// Compute the pose of the HMD w.r.t. the camera frame of reference.
// TODO: Keep track of whether we already have a good pose and, if
// so, have the algorithm initialize using it so we do less work on
// average.
bool gotPose = false;
if (m_estimators[sensor]) {
OSVR_PoseState pose;
if (m_estimators[sensor]->EstimatePoseFromLeds(
m_led_groups[sensor], pose)) {
m_pose = pose;
handler(static_cast<unsigned>(sensor), pose);
gotPose = true;
}
}
#ifdef VBHMD_DEBUG
// Don't display the debugging info every frame, or we can't go fast enough.
static int count = 0;
if (++count == 11) {
// Draw detected blobs as red circles.
cv::drawKeypoints(m_frame, keyPoints, m_imageWithBlobs,
cv::Scalar(0, 0, 255),
cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
// Label the keypoints with their IDs.
for (led = m_led_groups[sensor].begin();
led != m_led_groups[sensor].end(); led++) {
// Print 1-based LED ID for actual LEDs
auto label = std::to_string(led->getOneBasedID());
cv::Point where = led->getLocation();
where.x += 1;
where.y += 1;
cv::putText(m_imageWithBlobs, label, where,
cv::FONT_HERSHEY_SIMPLEX, 0.5,
cv::Scalar(0, 0, 255));
}
// If we have a transform, reproject all of the points from the
// model space (the LED locations) back into the image and
// display them on the blob image in green.
if (gotPose) {
std::vector<cv::Point2f> imagePoints;
m_estimators[sensor]->ProjectBeaconsToImage(imagePoints);
size_t n = imagePoints.size();
for (size_t i = 0; i < n; ++i) {
// Print 1-based LED IDs
auto label = std::to_string(i + 1);
auto where = imagePoints[i];
where.x += 1;
where.y += 1;
cv::putText(m_imageWithBlobs, label, where,
cv::FONT_HERSHEY_SIMPLEX, 0.5,
cv::Scalar(0, 255, 0));
}
}
// Pick which image to show and show it.
if (m_frame.data) {
std::ostringstream windowName;
windowName << "Sensor" << sensor;
cv::imshow(windowName.str().c_str(), *m_shownImage);
int key = cv::waitKey(1);
switch (key) {
case 'i':
// Show the input image.
m_shownImage = &m_frame;
break;
case 't':
// Show the thresholded image.
m_shownImage = &m_thresholdImage;
break;
case 'b':
// Show the blob image.
m_shownImage = &m_imageWithBlobs;
break;
case 'q':
// Indicate we want to quit.
done = true;
break;
}
}
// Report the pose, if we got one
if (gotPose) {
std::cout << "Pos (sensor " << sensor
<< "): " << m_pose.translation.data[0] << ", "
<< m_pose.translation.data[1] << ", "
<< m_pose.translation.data[2] << std::endl;
}
count = 0;
}
#endif
}
m_assertInvariants();
return done;
}
} // namespace vbtracker
} // namespace osvr
<|endoftext|>
|
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2016 INRIA.
*
* 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.
*/
/*!\file NE....cpp
\brief \ref EMNE_MULTIBODY - C++ input file, Time-Stepping version - O.B.
A multibody example.
Direct description of the model.
Simulation with a Time-Stepping scheme.
*/
#include "SiconosKernel.hpp"
#include "KneeJointR.hpp"
#include "PrismaticJointR.hpp"
#include <boost/math/quaternion.hpp>
using namespace std;
/* Given a position of a point in the Inertial Frame and the configuration vector q of a solid
* returns a position in the spatial frame.
*/
void fromInertialToSpatialFrame(double *positionInInertialFrame, double *positionInSpatialFrame, SP::SiconosVector q )
{
double q0 = q->getValue(3);
double q1 = q->getValue(4);
double q2 = q->getValue(5);
double q3 = q->getValue(6);
::boost::math::quaternion<double> quatQ(q0, q1, q2, q3);
::boost::math::quaternion<double> quatcQ(q0, -q1, -q2, -q3);
::boost::math::quaternion<double> quatpos(0, positionInInertialFrame[0], positionInInertialFrame[1], positionInInertialFrame[2]);
::boost::math::quaternion<double> quatBuff;
//perform the rotation
quatBuff = quatQ * quatpos * quatcQ;
positionInSpatialFrame[0] = quatBuff.R_component_2()+q->getValue(0);
positionInSpatialFrame[1] = quatBuff.R_component_3()+q->getValue(1);
positionInSpatialFrame[2] = quatBuff.R_component_4()+q->getValue(2);
}
void tipTrajectories(SP::SiconosVector q, double * traj, double length)
{
double positionInInertialFrame[3];
double positionInSpatialFrame[3];
// Output the position of the tip of beam1
positionInInertialFrame[0]=length/2;
positionInInertialFrame[1]=0.0;
positionInInertialFrame[2]=0.0;
fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q );
traj[0] = positionInSpatialFrame[0];
traj[1] = positionInSpatialFrame[1];
traj[2] = positionInSpatialFrame[2];
// std::cout << "positionInSpatialFrame[0]" << positionInSpatialFrame[0]<<std::endl;
// std::cout << "positionInSpatialFrame[1]" << positionInSpatialFrame[1]<<std::endl;
// std::cout << "positionInSpatialFrame[2]" << positionInSpatialFrame[2]<<std::endl;
positionInInertialFrame[0]=-length/2;
fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q );
traj[3]= positionInSpatialFrame[0];
traj[4] = positionInSpatialFrame[1];
traj[5] = positionInSpatialFrame[2];
}
int main(int argc, char* argv[])
{
try
{
// ================= Creation of the model =======================
// User-defined main parameters
unsigned int nDof = 3;
unsigned int qDim = 7;
unsigned int nDim = 6;
double t0 = 0; // initial computation time
double T = 10.0; // final computation time
double h = 0.01; // time step
int N = 1000;
double L1 = 1.0;
double L2 = 1.0;
double L3 = 1.0;
double theta = 1.0; // theta for MoreauJeanOSI integrator
double g = 9.81; // Gravity
double m = 1.;
// -------------------------
// --- Dynamical systems ---
// -------------------------
FILE * pFile;
pFile = fopen("data.h", "w");
if (pFile == NULL)
{
printf("fopen exampleopen filed!\n");
fclose(pFile);
}
cout << "====> Model loading ..." << endl << endl;
// -- Initial positions and velocities --
SP::SiconosVector q03(new SiconosVector(qDim));
SP::SiconosVector v03(new SiconosVector(nDim));
SP::SimpleMatrix I3(new SimpleMatrix(3, 3));
v03->zero();
I3->eye();
I3->setValue(0, 0, 0.1);
q03->zero();
(*q03)(2) = -L1 * sqrt(2.0) - L1 / 2;
double angle = M_PI / 2;
SiconosVector V1(3);
V1.zero();
V1.setValue(0, 0);
V1.setValue(1, 1);
V1.setValue(2, 0);
q03->setValue(3, cos(angle / 2));
q03->setValue(4, V1.getValue(0)*sin(angle / 2));
q03->setValue(5, V1.getValue(1)*sin(angle / 2));
q03->setValue(6, V1.getValue(2)*sin(angle / 2));
SP::NewtonEulerDS bouncingbeam(new NewtonEulerDS(q03, v03, m, I3));
// -- Set external forces (weight) --
SP::SiconosVector weight3(new SiconosVector(nDof));
(*weight3)(2) = -m * g;
bouncingbeam->setFExtPtr(weight3);
// --------------------
// --- Interactions ---
// --------------------
// Interaction with the floor
double e = 0.9;
SP::SimpleMatrix H(new SimpleMatrix(1, qDim));
SP::SiconosVector eR(new SiconosVector(1));
eR->setValue(0, 2.3);
H->zero();
(*H)(0, 2) = 1.0;
SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e));
SP::NewtonEulerR relation0(new NewtonEulerR());
relation0->setJachq(H);
relation0->setE(eR);
cout << "main jacQH" << endl;
relation0->jachq()->display();
// Interactions
// Building the prismatic joint for bouncingbeam
// input - the first concerned DS : bouncingbeam
// - an axis in the spatial frame (absolute frame)
// SP::SimpleMatrix H4(new SimpleMatrix(PrismaticJointR::numberOfConstraints(), qDim));
// H4->zero();
SP::SiconosVector axe1(new SiconosVector(3));
axe1->zero();
axe1->setValue(2, 1);
SP::PrismaticJointR relation4(new PrismaticJointR(axe1, bouncingbeam));
SP::NonSmoothLaw nslaw4(new EqualityConditionNSL(relation4->numberOfConstraints()));
SP::Interaction inter4(new Interaction(nslaw4, relation4));
SP::Interaction interFloor(new Interaction(nslaw0, relation0));
// -------------
// --- Model ---
// -------------
SP::Model myModel(new Model(t0, T));
// add the dynamical system in the non smooth dynamical system
myModel->nonSmoothDynamicalSystem()->insertDynamicalSystem(bouncingbeam);
// link the interaction and the dynamical system
myModel->nonSmoothDynamicalSystem()->link(inter4, bouncingbeam);
myModel->nonSmoothDynamicalSystem()->link(interFloor, bouncingbeam);
// ------------------
// --- Simulation ---
// ------------------
// -- (1) OneStepIntegrators --
SP::MoreauJeanOSI OSI3(new MoreauJeanOSI(theta));
// -- (2) Time discretisation --
SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));
// -- (3) one step non smooth problem
SP::OneStepNSProblem osnspb(new MLCP());
// -- (4) Simulation setup with (1) (2) (3)
SP::TimeStepping s(new TimeStepping(t, OSI3, osnspb));
// s->setComputeResiduY(true);
// s->setUseRelativeConvergenceCriteron(false);
myModel->setSimulation(s);
// =========================== End of model definition ===========================
// ================================= Computation =================================
// --- Simulation initialization ---
cout << "====> Initialisation ..." << endl << endl;
myModel->initialize();
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
unsigned int outputSize = 15 + 7;
SimpleMatrix dataPlot(N, outputSize);
SimpleMatrix bouncingbeamPlot(2,3*N);
SP::SiconosVector q3 = bouncingbeam->q();
SP::SiconosVector y= interFloor->y(0);
SP::SiconosVector ydot= interFloor->y(1);
// --- Time loop ---
cout << "====> Start computation ... " << endl << endl;
// ==== Simulation loop - Writing without explicit event handling =====
int k = 0;
boost::progress_display show_progress(N);
boost::timer time;
time.restart();
SP::SiconosVector yAux(new SiconosVector(3));
yAux->setValue(0, 1);
SP::SimpleMatrix Jaux(new SimpleMatrix(3, 3));
Index dimIndex(2);
Index startIndex(4);
fprintf(pFile, "double T[%d*%d]={", N + 1, outputSize);
double beamTipTrajectories[6];
for (k = 0; k < N; k++)
{
// solve ...
s->newtonSolve(1e-4, 50);
// --- Get values to be plotted ---
dataPlot(k, 0) = s->nextTime();
dataPlot(k, 1) = (*q3)(0);
dataPlot(k, 2) = (*q3)(1);
dataPlot(k, 3) = (*q3)(2);
dataPlot(k, 4) = (*q3)(3);
dataPlot(k, 5) = (*q3)(4);
dataPlot(k, 6) = (*q3)(5);
dataPlot(k, 7) = (*q3)(6);
dataPlot(k, 8) = y->norm2();
dataPlot(k, 9) = ydot->norm2();
tipTrajectories(q3,beamTipTrajectories,L3);
bouncingbeamPlot(0,3*k) = beamTipTrajectories[0];
bouncingbeamPlot(0,3*k+1) = beamTipTrajectories[1];
bouncingbeamPlot(0,3*k+2) = beamTipTrajectories[2];
bouncingbeamPlot(1,3*k) = beamTipTrajectories[3];
bouncingbeamPlot(1,3*k+1) = beamTipTrajectories[4];
bouncingbeamPlot(1,3*k+2) = beamTipTrajectories[5];
//printf("reaction1:%lf \n", interFloor->lambda(1)->getValue(0));
for (unsigned int jj = 0; jj < outputSize; jj++)
{
if ((k || jj))
fprintf(pFile, ",");
fprintf(pFile, "%f", dataPlot(k, jj));
}
fprintf(pFile, "\n");
s->nextStep();
++show_progress;
}
fprintf(pFile, "};");
cout << endl << "End of computation - Number of iterations done: " << k - 1 << endl;
cout << "Computation Time " << time.elapsed() << endl;
// --- Output files ---
cout << "====> Output file writing ..." << endl;
ioMatrix::write("NE_BouncingBeam.dat", "ascii", dataPlot, "noDim");
ioMatrix::write("NE_BouncingBeam_beam.dat", "ascii", bouncingbeamPlot, "noDim");
// SimpleMatrix dataPlotRef(dataPlot);
// dataPlotRef.zero();
// ioMatrix::read("NE_BoundingBeam.ref", "ascii", dataPlotRef);
// if ((dataPlot - dataPlotRef).normInf() > 1e-7)
// {
// (dataPlot - dataPlotRef).display();
// std::cout << "Warning. The results is rather different from the reference file." << std::endl;
// return 1;
// }
fclose(pFile);
}
catch (SiconosException e)
{
cout << e.report() << endl;
}
catch (...)
{
cout << "Exception caught in NE_...cpp" << endl;
}
}
<commit_msg>[example] fix compilation of NE_BouncingBeam<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2016 INRIA.
*
* 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.
*/
/*!\file NE....cpp
\brief \ref EMNE_MULTIBODY - C++ input file, Time-Stepping version - O.B.
A multibody example.
Direct description of the model.
Simulation with a Time-Stepping scheme.
*/
#include "SiconosKernel.hpp"
#include "KneeJointR.hpp"
#include "PrismaticJointR.hpp"
#include <boost/math/quaternion.hpp>
using namespace std;
/* Given a position of a point in the Inertial Frame and the configuration vector q of a solid
* returns a position in the spatial frame.
*/
void fromInertialToSpatialFrame(double *positionInInertialFrame, double *positionInSpatialFrame, SP::SiconosVector q )
{
double q0 = q->getValue(3);
double q1 = q->getValue(4);
double q2 = q->getValue(5);
double q3 = q->getValue(6);
::boost::math::quaternion<double> quatQ(q0, q1, q2, q3);
::boost::math::quaternion<double> quatcQ(q0, -q1, -q2, -q3);
::boost::math::quaternion<double> quatpos(0, positionInInertialFrame[0], positionInInertialFrame[1], positionInInertialFrame[2]);
::boost::math::quaternion<double> quatBuff;
//perform the rotation
quatBuff = quatQ * quatpos * quatcQ;
positionInSpatialFrame[0] = quatBuff.R_component_2()+q->getValue(0);
positionInSpatialFrame[1] = quatBuff.R_component_3()+q->getValue(1);
positionInSpatialFrame[2] = quatBuff.R_component_4()+q->getValue(2);
}
void tipTrajectories(SP::SiconosVector q, double * traj, double length)
{
double positionInInertialFrame[3];
double positionInSpatialFrame[3];
// Output the position of the tip of beam1
positionInInertialFrame[0]=length/2;
positionInInertialFrame[1]=0.0;
positionInInertialFrame[2]=0.0;
fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q );
traj[0] = positionInSpatialFrame[0];
traj[1] = positionInSpatialFrame[1];
traj[2] = positionInSpatialFrame[2];
// std::cout << "positionInSpatialFrame[0]" << positionInSpatialFrame[0]<<std::endl;
// std::cout << "positionInSpatialFrame[1]" << positionInSpatialFrame[1]<<std::endl;
// std::cout << "positionInSpatialFrame[2]" << positionInSpatialFrame[2]<<std::endl;
positionInInertialFrame[0]=-length/2;
fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q );
traj[3]= positionInSpatialFrame[0];
traj[4] = positionInSpatialFrame[1];
traj[5] = positionInSpatialFrame[2];
}
int main(int argc, char* argv[])
{
try
{
// ================= Creation of the model =======================
// User-defined main parameters
unsigned int nDof = 3;
unsigned int qDim = 7;
unsigned int nDim = 6;
double t0 = 0; // initial computation time
double T = 10.0; // final computation time
double h = 0.01; // time step
int N = 1000;
double L1 = 1.0;
double L2 = 1.0;
double L3 = 1.0;
double theta = 1.0; // theta for MoreauJeanOSI integrator
double g = 9.81; // Gravity
double m = 1.;
// -------------------------
// --- Dynamical systems ---
// -------------------------
FILE * pFile;
pFile = fopen("data.h", "w");
if (pFile == NULL)
{
printf("fopen exampleopen filed!\n");
fclose(pFile);
}
cout << "====> Model loading ..." << endl << endl;
// -- Initial positions and velocities --
SP::SiconosVector q03(new SiconosVector(qDim));
SP::SiconosVector v03(new SiconosVector(nDim));
SP::SimpleMatrix I3(new SimpleMatrix(3, 3));
v03->zero();
I3->eye();
I3->setValue(0, 0, 0.1);
q03->zero();
(*q03)(2) = -L1 * sqrt(2.0) - L1 / 2;
double angle = M_PI / 2;
SiconosVector V1(3);
V1.zero();
V1.setValue(0, 0);
V1.setValue(1, 1);
V1.setValue(2, 0);
q03->setValue(3, cos(angle / 2));
q03->setValue(4, V1.getValue(0)*sin(angle / 2));
q03->setValue(5, V1.getValue(1)*sin(angle / 2));
q03->setValue(6, V1.getValue(2)*sin(angle / 2));
SP::NewtonEulerDS bouncingbeam(new NewtonEulerDS(q03, v03, m, I3));
// -- Set external forces (weight) --
SP::SiconosVector weight3(new SiconosVector(nDof));
(*weight3)(2) = -m * g;
bouncingbeam->setFExtPtr(weight3);
// --------------------
// --- Interactions ---
// --------------------
// Interaction with the floor
double e = 0.9;
SP::SimpleMatrix H(new SimpleMatrix(1, qDim));
SP::SiconosVector eR(new SiconosVector(1));
eR->setValue(0, 2.3);
H->zero();
(*H)(0, 2) = 1.0;
SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e));
SP::NewtonEulerR relation0(new NewtonEulerR());
relation0->setJachq(H);
relation0->setE(eR);
cout << "main jacQH" << endl;
relation0->jachq()->display();
// Interactions
// Building the prismatic joint for bouncingbeam
// input - the first concerned DS : bouncingbeam
// - an axis in the spatial frame (absolute frame)
// SP::SimpleMatrix H4(new SimpleMatrix(PrismaticJointR::numberOfConstraints(), qDim));
// H4->zero();
SP::SiconosVector axe1(new SiconosVector(3));
axe1->zero();
axe1->setValue(2, 1);
SP::PrismaticJointR relation4(new PrismaticJointR(axe1, false, bouncingbeam));
SP::NonSmoothLaw nslaw4(new EqualityConditionNSL(relation4->numberOfConstraints()));
SP::Interaction inter4(new Interaction(nslaw4, relation4));
SP::Interaction interFloor(new Interaction(nslaw0, relation0));
// -------------
// --- Model ---
// -------------
SP::Model myModel(new Model(t0, T));
// add the dynamical system in the non smooth dynamical system
myModel->nonSmoothDynamicalSystem()->insertDynamicalSystem(bouncingbeam);
// link the interaction and the dynamical system
myModel->nonSmoothDynamicalSystem()->link(inter4, bouncingbeam);
myModel->nonSmoothDynamicalSystem()->link(interFloor, bouncingbeam);
// ------------------
// --- Simulation ---
// ------------------
// -- (1) OneStepIntegrators --
SP::MoreauJeanOSI OSI3(new MoreauJeanOSI(theta));
// -- (2) Time discretisation --
SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));
// -- (3) one step non smooth problem
SP::OneStepNSProblem osnspb(new MLCP());
// -- (4) Simulation setup with (1) (2) (3)
SP::TimeStepping s(new TimeStepping(t, OSI3, osnspb));
// s->setComputeResiduY(true);
// s->setUseRelativeConvergenceCriteron(false);
myModel->setSimulation(s);
// =========================== End of model definition ===========================
// ================================= Computation =================================
// --- Simulation initialization ---
cout << "====> Initialisation ..." << endl << endl;
myModel->initialize();
// --- Get the values to be plotted ---
// -> saved in a matrix dataPlot
unsigned int outputSize = 15 + 7;
SimpleMatrix dataPlot(N, outputSize);
SimpleMatrix bouncingbeamPlot(2,3*N);
SP::SiconosVector q3 = bouncingbeam->q();
SP::SiconosVector y= interFloor->y(0);
SP::SiconosVector ydot= interFloor->y(1);
// --- Time loop ---
cout << "====> Start computation ... " << endl << endl;
// ==== Simulation loop - Writing without explicit event handling =====
int k = 0;
boost::progress_display show_progress(N);
boost::timer time;
time.restart();
SP::SiconosVector yAux(new SiconosVector(3));
yAux->setValue(0, 1);
SP::SimpleMatrix Jaux(new SimpleMatrix(3, 3));
Index dimIndex(2);
Index startIndex(4);
fprintf(pFile, "double T[%d*%d]={", N + 1, outputSize);
double beamTipTrajectories[6];
for (k = 0; k < N; k++)
{
// solve ...
s->newtonSolve(1e-4, 50);
// --- Get values to be plotted ---
dataPlot(k, 0) = s->nextTime();
dataPlot(k, 1) = (*q3)(0);
dataPlot(k, 2) = (*q3)(1);
dataPlot(k, 3) = (*q3)(2);
dataPlot(k, 4) = (*q3)(3);
dataPlot(k, 5) = (*q3)(4);
dataPlot(k, 6) = (*q3)(5);
dataPlot(k, 7) = (*q3)(6);
dataPlot(k, 8) = y->norm2();
dataPlot(k, 9) = ydot->norm2();
tipTrajectories(q3,beamTipTrajectories,L3);
bouncingbeamPlot(0,3*k) = beamTipTrajectories[0];
bouncingbeamPlot(0,3*k+1) = beamTipTrajectories[1];
bouncingbeamPlot(0,3*k+2) = beamTipTrajectories[2];
bouncingbeamPlot(1,3*k) = beamTipTrajectories[3];
bouncingbeamPlot(1,3*k+1) = beamTipTrajectories[4];
bouncingbeamPlot(1,3*k+2) = beamTipTrajectories[5];
//printf("reaction1:%lf \n", interFloor->lambda(1)->getValue(0));
for (unsigned int jj = 0; jj < outputSize; jj++)
{
if ((k || jj))
fprintf(pFile, ",");
fprintf(pFile, "%f", dataPlot(k, jj));
}
fprintf(pFile, "\n");
s->nextStep();
++show_progress;
}
fprintf(pFile, "};");
cout << endl << "End of computation - Number of iterations done: " << k - 1 << endl;
cout << "Computation Time " << time.elapsed() << endl;
// --- Output files ---
cout << "====> Output file writing ..." << endl;
ioMatrix::write("NE_BouncingBeam.dat", "ascii", dataPlot, "noDim");
ioMatrix::write("NE_BouncingBeam_beam.dat", "ascii", bouncingbeamPlot, "noDim");
// SimpleMatrix dataPlotRef(dataPlot);
// dataPlotRef.zero();
// ioMatrix::read("NE_BoundingBeam.ref", "ascii", dataPlotRef);
// if ((dataPlot - dataPlotRef).normInf() > 1e-7)
// {
// (dataPlot - dataPlotRef).display();
// std::cout << "Warning. The results is rather different from the reference file." << std::endl;
// return 1;
// }
fclose(pFile);
}
catch (SiconosException e)
{
cout << e.report() << endl;
}
catch (...)
{
cout << "Exception caught in NE_...cpp" << endl;
}
}
<|endoftext|>
|
<commit_before>/*
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <boost/numeric/ublas/io.hpp>
*/
#if defined(VIENNACL_WITH_OPENCL) || defined(VIENNACL_WITH_OPENMP) || defined(VIENNACL_WITH_CUDA)
#define VIENNACL
#include "viennacl/ocl/device.hpp"
#include "viennacl/ocl/platform.hpp"
#include "viennacl/scalar.hpp"
#include "viennacl/vector.hpp"
#endif
/* Handle errors by printing an error message and exiting with a
* non-zero status. */
#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/assignment.hpp>
using namespace boost::numeric;
#include "mpi.h"
#include <netcdf_par.h>
#include <netcdf.h>
/**
Write description of function here.
The function should follow these comments.
Use of "brief" tag is optional. (no point to it)
The function arguments listed with "param" will be compared
to the declaration and verified.
@param[in] filename Filename (string)
@param[in] fields List of the fields to be extracted (vector of strings0
@return vector of concatenated field values
*/
template <typename ScalarType>
std::vector<ScalarType> netcdf_read_timeseries(const std::string filename, const std::vector<std::string> fields )
{
int ncid, varid;
int ndims;
/* error handling */
int retval ;
int *dimids;
size_t *dims;
size_t *p;
size_t *start, *count;
int my_rank, mpi_processes;
int slab_size ; // is the number of entries in one slab to be read in
ScalarType *data;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Info info = MPI_INFO_NULL;
MPI_Comm_rank( MPI_COMM_WORLD, &my_rank );
MPI_Comm_size( MPI_COMM_WORLD, &mpi_processes );
/* Open the file. NC_NOWRITE tells netCDF we want read-only access to the file.*/
std::cout << "Processing: " << filename.c_str() << " SEARCHING FOR " << fields[0].c_str() << std::endl;
if ((retval = nc_open_par(filename.c_str(), NC_NOWRITE|NC_MPIIO, comm, info, &ncid))) ERR(retval);
// sequential: if ((retval = nc_open(filename.c_str(), NC_NOWRITE, &ncid))) ERR(retval);
if ((retval = nc_inq_varid(ncid, fields[0].c_str(), &varid))) ERR(retval);
if ((retval = nc_inq_varndims(ncid, varid, &ndims))) ERR(retval);
std::cout << "ndims " << ndims << std::endl;
dimids = (int*) malloc (sizeof(int)*ndims);
start = (size_t*) malloc (sizeof(size_t)*ndims); // Starting points for parallel implementation
count = (size_t*) malloc (sizeof(size_t)*ndims); // Slab sizes
dims = (size_t*) malloc (sizeof(size_t)*ndims);
if ((retval = nc_inq_vardimid(ncid, varid, dimids))) ERR(retval);
p = dims;
for (int i=0; i<ndims; ++i ) {
if ((retval = nc_inq_dimlen(ncid, dimids[i], p))) ERR(retval);
std::cout << "dimension = " << *p++ << std::endl;
count[i] = dimids[i];
start[i] = 0;
}
if (dims[0] % mpi_processes != 0)
{
if (!my_rank) std::cout << "dims[0] " << dims[0] << " is not evenly divisible by mpi_size= " << mpi_processes << std::endl;
static std::vector<ScalarType> empty_vector;
return empty_vector;
}
count[0] = dims[0] / mpi_processes; // Number of 2D slices.
slab_size = count[0];
for (int i=0; i<ndims; ++i ) { slab_size *= count[i]; }
data = (ScalarType*) malloc (sizeof(ScalarType)*slab_size);
/* Read the slab this process is responsible for. */
start[0] = dims[0] / mpi_processes * my_rank;
std::cout << "Rank: " << my_rank << " reading slab: " << start[0] << std::endl;
/* Read one slab of data. */
if ((retval = nc_get_vara_double(ncid, varid, start, count, data))) ERR(retval);
std::vector<ScalarType> output(data, data+slab_size);
free( dims );
free( dimids );
free( start );
free( count );
free( data );
/* Close the file, freeing all resources. */
if ((retval = nc_close(ncid)))
ERR(retval);
return output;
}
int main(int argc, char *argv[])
//****************************************************************************80
//
// Purpose:
//
// Example of parallel NetCDF functionality
//
// Discussion:
//
// This program demonstrates parallel NetCDF functionality. It reads from
// a NetCDF file a specified, specified as the first and second arguments of
// the function.
//
// This is the first step toward implementing a compression backend which
// reads a NetCDF stream, and compresses the time series data in parallel
// using the approaches of Horenko, et al.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// Starting October 2013
//
// Author:
//
// William Sawyer (CSCS)
//
// Reference:
//
// Horenko, Klein, Dolaptchiev, Schuette
// Automated Generation of Reduced Stochastic Weather Models I:
// simultaneous dimension and model reduction for time series analysis
// XXX
//
// Example execution:
//
// aprun -n 2 ./netcdf_test /project/csstaff/outputs/echam/echam6/echam_output/t31_196001.01_echam.nc seaice
//
{
using namespace std;
typedef double ScalarType; //feel free to change this to 'double' if supported by your hardware
/* This will be the netCDF ID for the file and data variable. */
int ncid, varid, dimid;
int ndims, nvars_in, ngatts_in, unlimdimid_in;
int my_rank, mpi_processes;
/* Loop indexes, and error handling. */
int x, y, retval ;
int slab_size ; // is the number of entries in one slab to be read in
double *data_double;
int *dimids;
size_t *dims;
size_t *p;
size_t *start, *count;
viennacl::ocl::set_context_device_type(1, viennacl::ocl::gpu_tag()); // Does not find the GPU
//
// Initialize MPI.
//
MPI_Init ( &argc, &argv );
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Info info = MPI_INFO_NULL;
MPI_Comm_rank( MPI_COMM_WORLD, &my_rank );
MPI_Comm_size( MPI_COMM_WORLD, &mpi_processes );
if (argc <= 2)
{
std::cout << "Usage: " << argv[0] << " <Filename>" << " <field name>" << std::endl;
exit(1);
}
typedef std::vector< viennacl::ocl::platform > platforms_type;
platforms_type platforms = viennacl::ocl::get_platforms();
viennacl::ocl::platform pf = viennacl::ocl::get_platforms()[1];
// for (platforms_type::iterator platform_iter = platforms.begin();
// platform_iter != platforms.end();
// ++platform_iter)
if (!my_rank)
{
typedef std::vector<viennacl::ocl::device> devices_type;
devices_type devices = pf.devices(CL_DEVICE_TYPE_ALL);
//
// print some platform info
//
std::cout << "# =========================================" << std::endl;
std::cout << "# Platform Information " << std::endl;
std::cout << "# =========================================" << std::endl;
std::cout << "#" << std::endl;
std::cout << "# Vendor and version: " << pf.info() << std::endl;
std::cout << "#" << std::endl;
//
// traverse the devices and print the information
//
std::cout << "# " << std::endl;
std::cout << "# Available Devices: " << std::endl;
std::cout << "# " << std::endl;
for(devices_type::iterator iter = devices.begin(); iter != devices.end(); iter++)
{
std::cout << std::endl;
std::cout << " -----------------------------------------" << std::endl;
std::cout << iter->info();
std::cout << " -----------------------------------------" << std::endl;
}
std::cout << std::endl;
std::cout << "###########################################" << std::endl;
std::cout << std::endl;
}
std::cout << "Parallel execution: my_rank " << my_rank << " out of " << mpi_processes << " processes" << std::endl;
std::string filename(argv[1]);
std::vector<std::string> fields(argv+2, argv+argc);
std::vector<ScalarType> X = netcdf_read_timeseries<ScalarType>( filename, fields);
viennacl::vector<ScalarType> Xvcl(X.size());
viennacl::copy(X.begin(), X.end(), Xvcl.begin() );
retval = 0;
std::cout << "retval " << retval << std::endl;
//
// Terminate MPI.
//
MPI::Finalize ( );
return 0;
}
<commit_msg>Changes ongoing<commit_after>/*
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <boost/numeric/ublas/io.hpp>
*/
#if defined(VIENNACL_WITH_OPENCL) || defined(VIENNACL_WITH_OPENMP) || defined(VIENNACL_WITH_CUDA)
#define VIENNACL
#include "viennacl/ocl/device.hpp"
#include "viennacl/ocl/platform.hpp"
#include "viennacl/scalar.hpp"
#include "viennacl/vector.hpp"
#endif
/* Handle errors by printing an error message and exiting with a
* non-zero status. */
#define ERRCODE 2
#define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);}
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/assignment.hpp>
using namespace boost::numeric;
#include "mpi.h"
/**
Write description of function here.
The function should follow these comments.
Use of "brief" tag is optional. (no point to it)
The function arguments listed with "param" will be compared
to the declaration and verified.
@param[in] filename Filename (string)
@param[in] fields List of the fields to be extracted (vector of strings0
@return vector of concatenated field values
*/
#include "read_timeseries.hpp"
int main(int argc, char *argv[])
//****************************************************************************80
//
// Purpose:
//
// Example of parallel NetCDF functionality
//
// Discussion:
//
// This program demonstrates parallel NetCDF functionality. It reads from
// a NetCDF file a specified, specified as the first and second arguments of
// the function.
//
// This is the first step toward implementing a compression backend which
// reads a NetCDF stream, and compresses the time series data in parallel
// using the approaches of Horenko, et al.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// Starting October 2013
//
// Author:
//
// William Sawyer (CSCS)
//
// Reference:
//
// Horenko, Klein, Dolaptchiev, Schuette
// Automated Generation of Reduced Stochastic Weather Models I:
// simultaneous dimension and model reduction for time series analysis
// XXX
//
// Example execution:
//
// aprun -n 2 ./netcdf_test /project/csstaff/outputs/echam/echam6/echam_output/t31_196001.01_echam.nc seaice
//
{
using namespace std;
typedef double ScalarType; //feel free to change this to 'double' if supported by your hardware
/* This will be the netCDF ID for the file and data variable. */
int ncid, varid, dimid;
int ndims, nvars_in, ngatts_in, unlimdimid_in;
int my_rank, mpi_processes;
/* Loop indexes, and error handling. */
int x, y, retval ;
int slab_size ; // is the number of entries in one slab to be read in
double *data_double;
int *dimids;
size_t *dims;
size_t *p;
size_t *start, *count;
viennacl::ocl::set_context_device_type(1, viennacl::ocl::gpu_tag()); // Does not find the GPU
//
// Initialize MPI.
//
MPI_Init ( &argc, &argv );
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Info info = MPI_INFO_NULL;
MPI_Comm_rank( MPI_COMM_WORLD, &my_rank );
MPI_Comm_size( MPI_COMM_WORLD, &mpi_processes );
if (argc <= 2)
{
std::cout << "Usage: " << argv[0] << " <Filename>" << " <field name>" << std::endl;
exit(1);
}
typedef std::vector< viennacl::ocl::platform > platforms_type;
platforms_type platforms = viennacl::ocl::get_platforms();
viennacl::ocl::platform pf = viennacl::ocl::get_platforms()[1];
// for (platforms_type::iterator platform_iter = platforms.begin();
// platform_iter != platforms.end();
// ++platform_iter)
if (!my_rank)
{
typedef std::vector<viennacl::ocl::device> devices_type;
devices_type devices = pf.devices(CL_DEVICE_TYPE_ALL);
//
// print some platform info
//
std::cout << "# =========================================" << std::endl;
std::cout << "# Platform Information " << std::endl;
std::cout << "# =========================================" << std::endl;
std::cout << "#" << std::endl;
std::cout << "# Vendor and version: " << pf.info() << std::endl;
std::cout << "#" << std::endl;
//
// traverse the devices and print the information
//
std::cout << "# " << std::endl;
std::cout << "# Available Devices: " << std::endl;
std::cout << "# " << std::endl;
for(devices_type::iterator iter = devices.begin(); iter != devices.end(); iter++)
{
std::cout << std::endl;
std::cout << " -----------------------------------------" << std::endl;
std::cout << iter->info();
std::cout << " -----------------------------------------" << std::endl;
}
std::cout << std::endl;
std::cout << "###########################################" << std::endl;
std::cout << std::endl;
}
std::cout << "Parallel execution: my_rank " << my_rank << " out of " << mpi_processes << " processes" << std::endl;
std::string filename(argv[1]);
std::vector<std::string> fields(argv+2, argv+argc);
std::vector<ScalarType> X = read_timeseries<ScalarType>( filename, fields);
viennacl::vector<ScalarType> Xvcl(X.size());
viennacl::copy(X.begin(), X.end(), Xvcl.begin() );
retval = 0;
std::cout << "retval " << retval << std::endl;
//
// Terminate MPI.
//
MPI::Finalize ( );
return 0;
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_CHANNEL_LOADER_MODULE_HPP
#define LIBBITCOIN_CHANNEL_LOADER_MODULE_HPP
#include <functional>
#include <string>
#include <system_error>
#include <bitcoin/bitcoin/define.hpp>
#include <bitcoin/bitcoin/error.hpp>
#include <bitcoin/bitcoin/satoshi_serialize.hpp>
#include <bitcoin/bitcoin/utility/data.hpp>
namespace libbitcoin {
namespace network {
class BC_API channel_loader_module_base
{
public:
virtual ~channel_loader_module_base() {}
virtual void attempt_load(const data_chunk& stream) const = 0;
virtual const std::string lookup_symbol() const = 0;
};
// TODO: split to impl.
template <typename Message>
class channel_loader_module
: public channel_loader_module_base
{
public:
typedef std::function<void (const std::error_code&, const Message&)>
load_handler;
channel_loader_module(load_handler handle_load)
: handle_load_(handle_load)
{
}
/// This class is not copyable.
channel_loader_module(const channel_loader_module&) = delete;
void operator=(const channel_loader_module&) = delete;
void attempt_load(const data_chunk& stream) const
{
Message result;
try
{
satoshi_load(stream.begin(), stream.end(), result);
handle_load_(error::success, result);
}
catch (bc::end_of_stream)
{
// This doesn't invalidate the channel (unlike the invalid header).
handle_load_(bc::error::bad_stream, Message());
}
}
const std::string lookup_symbol() const
{
return satoshi_command(Message());
}
private:
load_handler handle_load_;
};
} // namespace network
} // namespace libbitcoin
#endif
<commit_msg>Comments.<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_CHANNEL_LOADER_MODULE_HPP
#define LIBBITCOIN_CHANNEL_LOADER_MODULE_HPP
#include <functional>
#include <string>
#include <system_error>
#include <bitcoin/bitcoin/define.hpp>
#include <bitcoin/bitcoin/error.hpp>
#include <bitcoin/bitcoin/satoshi_serialize.hpp>
#include <bitcoin/bitcoin/utility/data.hpp>
namespace libbitcoin {
namespace network {
class BC_API channel_loader_module_base
{
public:
virtual ~channel_loader_module_base() {}
virtual void attempt_load(const data_chunk& stream) const = 0;
virtual const std::string lookup_symbol() const = 0;
};
template <typename Message>
class channel_loader_module
: public channel_loader_module_base
{
public:
typedef std::function<void (const std::error_code&, const Message&)>
load_handler;
channel_loader_module(load_handler handle_load)
: handle_load_(handle_load)
{
}
/// This class is not copyable.
channel_loader_module(const channel_loader_module&) = delete;
void operator=(const channel_loader_module&) = delete;
void attempt_load(const data_chunk& stream) const
{
Message result;
try
{
satoshi_load(stream.begin(), stream.end(), result);
handle_load_(error::success, result);
}
catch (bc::end_of_stream)
{
handle_load_(bc::error::bad_stream, Message());
}
}
const std::string lookup_symbol() const
{
return satoshi_command(Message());
}
private:
load_handler handle_load_;
};
} // namespace network
} // namespace libbitcoin
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Copyright (C) 2015 Ruslan Baratov
** Contact: http://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Multimedia module.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <cassert> // assert
#include <QGuiApplication>
#include <QQuickView>
#include <QQuickItem>
#include <QCamera>
#include "VideoFilter.hpp"
#include "InfoFilter.hpp"
#include <iostream>
#if defined(Q_OS_IOS)
extern "C" int qtmn(int argc, char** argv) {
#else
int main(int argc, char **argv) {
#endif
#ifdef Q_OS_WIN // avoid ANGLE on Windows
QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
#endif
QGuiApplication app(argc, argv);
qmlRegisterType<VideoFilter>("qmlvideofilter.test", 1, 0, "VideoFilter");
qmlRegisterType<InfoFilter>("qmlvideofilter.test", 1, 0, "InfoFilter");
QQuickView view;
view.setSource(QUrl("qrc:///main.qml"));
#if defined(Q_OS_IOS)
// Default camera on iOS is not setting good parameters by default
QQuickItem* root = view.rootObject();
QObject* qmlCamera = root->findChild<QObject*>("CameraObject");
assert(qmlCamera != nullptr);
QCamera* camera = qvariant_cast<QCamera*>(qmlCamera->property("mediaObject"));
assert(camera != nullptr);
#if 0
QCameraViewfinderSettings viewfinderFoundSetting;
assert(viewfinderFoundSetting.isNull());
// Format_ARGB32 == 1
// Format_NV12 == 22
auto viewfinderSettings = camera->supportedViewfinderSettings();
for (auto i: viewfinderSettings) {
bool good = true;
if (i.pixelFormat() != QVideoFrame::Format_ARGB32) {
good = false;
}
if (i.resolution().height() > view.height()) {
good = false;
}
if (i.resolution().width() > view.width()) {
good = false;
}
if (good) {
// Get last setting if several RGB available.
// Goes from lower resolution to higher (verify?)
viewfinderFoundSetting = i;
}
}
assert(viewfinderFoundSetting.pixelFormat() == QVideoFrame::Format_ARGB32);
camera->setViewfinderSettings(viewfinderFoundSetting);
#endif
// Try the highest resolution ARGB32 format:
QVideoFrame::PixelFormat desiredFormat = QVideoFrame::Format_ARGB32;
auto viewfinderSettings = camera->supportedViewfinderSettings();
std::pair<int, QCameraViewfinderSettings> best;
for (auto i: viewfinderSettings)
{
if (i.pixelFormat() == desiredFormat)
{
int area = (i.resolution().height() * i.resolution().width());
if(area > best.first)
{
best = { area, i };
}
}
}
assert(!best.second.isNull());
assert(best.second.pixelFormat() == desiredFormat);
camera->setViewfinderSettings(best.second);
#endif
view.show();
return app.exec();
}
<commit_msg> view.setResizeMode( QQuickView::SizeRootObjectToView )<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Copyright (C) 2015 Ruslan Baratov
** Contact: http://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Multimedia module.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <cassert> // assert
#include <QGuiApplication>
#include <QQuickView>
#include <QQuickItem>
#include <QCamera>
#include "VideoFilter.hpp"
#include "InfoFilter.hpp"
#include <iostream>
#if defined(Q_OS_IOS)
extern "C" int qtmn(int argc, char** argv)
{
#else
int main(int argc, char **argv)
{
#endif
#ifdef Q_OS_WIN // avoid ANGLE on Windows
QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL);
#endif
QGuiApplication app(argc, argv);
qmlRegisterType<VideoFilter>("qmlvideofilter.test", 1, 0, "VideoFilter");
qmlRegisterType<InfoFilter>("qmlvideofilter.test", 1, 0, "InfoFilter");
QQuickView view;
view.setSource(QUrl("qrc:///main.qml"));
view.setResizeMode( QQuickView::SizeRootObjectToView );
#if defined(Q_OS_IOS)
// Default camera on iOS is not setting good parameters by default
QQuickItem* root = view.rootObject();
//root->setSize({960,1280});
QObject* qmlCamera = root->findChild<QObject*>("CameraObject");
assert(qmlCamera != nullptr);
QCamera* camera = qvariant_cast<QCamera*>(qmlCamera->property("mediaObject"));
assert(camera != nullptr);
#if 0
QCameraViewfinderSettings viewfinderFoundSetting;
assert(viewfinderFoundSetting.isNull());
// Format_ARGB32 == 1
// Format_NV12 == 22
auto viewfinderSettings = camera->supportedViewfinderSettings();
for (auto i: viewfinderSettings) {
bool good = true;
if (i.pixelFormat() != QVideoFrame::Format_ARGB32) {
good = false;
}
if (i.resolution().height() > view.height()) {
good = false;
}
if (i.resolution().width() > view.width()) {
good = false;
}
if (good) {
// Get last setting if several RGB available.
// Goes from lower resolution to higher (verify?)
viewfinderFoundSetting = i;
}
}
assert(viewfinderFoundSetting.pixelFormat() == QVideoFrame::Format_ARGB32);
camera->setViewfinderSettings(viewfinderFoundSetting);
#endif
// Try the highest resolution ARGB32 format:
QVideoFrame::PixelFormat desiredFormat = QVideoFrame::Format_NV12;// QVideoFrame::Format_ARGB32;
auto viewfinderSettings = camera->supportedViewfinderSettings();
std::pair<int, QCameraViewfinderSettings> best;
for (auto i: viewfinderSettings)
{
if (i.pixelFormat() == desiredFormat)
{
int area = (i.resolution().height() * i.resolution().width());
if(area > best.first)
{
best = { area, i };
}
}
}
assert(!best.second.isNull());
assert(best.second.pixelFormat() == desiredFormat);
camera->setViewfinderSettings(best.second);
#endif
view.show();
return app.exec();
}
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#ifdef EXECUTOR
#define AUTOMATIC_CONVERSIONS
#include <QuickDraw.h>
#include <CQuickDraw.h>
#include <MemoryMgr.h>
using namespace Executor;
extern QDGlobals qd;
#define PTR(x) (&inout(x))
// FIXME: Executor still defines Pattern as an array, rather than an array wrapped in a struct
#define PATREF(pat) (pat)
#else
#include <Quickdraw.h>
#include <QDOffscreen.h>
#define PTR(x) (&x)
#define PATREF(pat) (&(pat))
#endif
struct OffscreenPort
{
GrafPort port;
Rect r;
OffscreenPort(int height = 2, int width = 2)
{
OpenPort(&port);
short rowBytes = (width + 31) / 31 * 4;
port.portBits.rowBytes = rowBytes;
port.portBits.baseAddr = NewPtrClear(rowBytes * height);
SetRect(&r, 0,0,width,height);
port.portBits.bounds = r;
set();
}
~OffscreenPort()
{
ClosePort(&port);
}
void set()
{
SetPort(&port);
}
uint8_t& data(int row, int offset)
{
return reinterpret_cast<uint8_t&>(
port.portBits.baseAddr[row * port.portBits.rowBytes + offset]);
}
};
struct OffscreenWorld
{
GWorldPtr world = nullptr;
Rect r;
OffscreenWorld(int depth, int height = 2, int width = 2)
{
SetRect(&r,0,0,2,2);
NewGWorld(PTR(world), depth, &r, nullptr, nullptr, 0);
LockPixels(world->portPixMap);
set();
}
~OffscreenWorld()
{
if((GrafPtr)world == qd.thePort)
SetGDevice(GetMainDevice());
DisposeGWorld(world);
}
void set()
{
SetGWorld(world, nullptr);
}
uint8_t& data(int row, int offset)
{
Ptr baseAddr = (*world->portPixMap)->baseAddr;
uint8_t *data = (uint8_t*)baseAddr;
short rowBytes = (*world->portPixMap)->rowBytes;
rowBytes &= 0x3FFF;
return data[row * rowBytes + offset];
}
uint16_t data16(int row, int offset)
{
return data(row, offset*2) * 256 + data(row, offset*2+1);
}
uint32_t data32(int row, int offset)
{
return data16(row, offset*2) * 65536 + data16(row, offset*2+1);
}
};
TEST(QuickDraw, BWLine1)
{
OffscreenPort port;
EraseRect(&port.r);
MoveTo(0,0);
LineTo(2,2);
EXPECT_EQ(0x80, port.data(0,0));
EXPECT_EQ(0x40, port.data(1,0));
}
TEST(QuickDraw, GWorld8)
{
OffscreenWorld world(8);
EraseRect(&world.r);
MoveTo(0,0);
LineTo(2,2);
EXPECT_EQ(255, world.data(0,0));
EXPECT_EQ(0, world.data(0,1));
EXPECT_EQ(0, world.data(1,0));
EXPECT_EQ(255, world.data(1,1));
}
TEST(QuickDraw, GWorld16)
{
OffscreenWorld world(16);
EraseRect(&world.r);
MoveTo(0,0);
LineTo(2,2);
EXPECT_EQ(0, world.data16(0,0));
EXPECT_EQ(0x7FFF, world.data16(0,1));
}
TEST(QuickDraw, GWorld32)
{
OffscreenWorld world(32);
EraseRect(&world.r);
MoveTo(0,0);
LineTo(2,2);
EXPECT_EQ(0, world.data32(0,0));
EXPECT_EQ(0x00FFFFFF, world.data32(0,1));
}
TEST(QuickDraw, BasicQDColorBW)
{
OffscreenPort port;
FillRect(&port.r, PATREF(qd.gray));
EXPECT_EQ(0x80, port.data(0,0));
EXPECT_EQ(0x40, port.data(1,0));
ForeColor(whiteColor);
BackColor(redColor);
FillRect(&port.r, PATREF(qd.gray));
EXPECT_EQ(0x40, port.data(0,0));
EXPECT_EQ(0x80, port.data(1,0));
EXPECT_EQ(whiteColor, port.port.fgColor);
EXPECT_EQ(redColor, port.port.bkColor);
}
TEST(QuickDraw, BasicQDColor32)
{
OffscreenWorld world(32);
FillRect(&world.r, PATREF(qd.gray));
EXPECT_EQ(0x00000000, world.data32(0,0));
EXPECT_EQ(0x00FFFFFF, world.data32(0,1));
EXPECT_EQ(0x00FFFFFF, world.data32(1,0));
EXPECT_EQ(0x00000000, world.data32(1,1));
ForeColor(whiteColor);
BackColor(redColor);
const uint32_t rgbRed = 0xDD0806;
EXPECT_EQ(0x00FFFFFF, world.world->fgColor);
EXPECT_EQ(rgbRed, world.world->bkColor);
FillRect(&world.r, PATREF(qd.gray));
EXPECT_EQ(0x00FFFFFF, world.data32(0,0));
EXPECT_EQ(rgbRed, world.data32(0,1));
EXPECT_EQ(rgbRed, world.data32(1,0));
EXPECT_EQ(0x00FFFFFF, world.data32(1,1));
}
TEST(QuickDraw, GrayPattern32)
{
OffscreenWorld world(32);
FillRect(&world.r, PATREF(qd.gray));
EXPECT_EQ(0x00000000, world.data32(0,0));
EXPECT_EQ(0x00FFFFFF, world.data32(0,1));
EXPECT_EQ(0x00FFFFFF, world.data32(1,0));
EXPECT_EQ(0x00000000, world.data32(1,1));
}
TEST(QuickDraw, GrayPattern8)
{
OffscreenWorld world(8);
FillRect(&world.r, PATREF(qd.gray));
EXPECT_EQ(0xFF, world.data(0,0));
EXPECT_EQ(0x00, world.data(0,1));
EXPECT_EQ(0x00, world.data(1,0));
EXPECT_EQ(0xFF, world.data(1,1));
}
TEST(QuickDraw, GrayPattern1)
{
OffscreenPort port;
FillRect(&port.r, PATREF(qd.gray));
EXPECT_EQ(0x80, port.data(0,0));
EXPECT_EQ(0x40, port.data(1,0));
}
TEST(QuickDraw, BlackPattern32)
{
OffscreenWorld world(32);
FillRect(&world.r, PATREF(qd.black));
EXPECT_EQ(0x00000000, world.data32(0,0));
EXPECT_EQ(0x00000000, world.data32(0,1));
EXPECT_EQ(0x00000000, world.data32(1,0));
EXPECT_EQ(0x00000000, world.data32(1,1));
}
TEST(QuickDraw, CopyBit8)
{
OffscreenWorld world1(8);
world1.data(0,0) = 1;
world1.data(0,1) = 2;
world1.data(1,0) = 3;
world1.data(1,1) = 4;
OffscreenWorld world2(8);
EraseRect(&world2.r);
RgnHandle rgn1 = NewRgn();
SetRectRgn(rgn1, 0,0,2,1);
RgnHandle rgn2 = NewRgn();
SetRectRgn(rgn2, 0,0,1,2);
UnionRgn(rgn1, rgn2, rgn1);
DisposeRgn(rgn2);
CopyBits(
&GrafPtr(world1.world)->portBits,
&GrafPtr(world2.world)->portBits,
&world1.r, &world2.r, srcCopy, rgn1);
DisposeRgn(rgn1);
EXPECT_EQ(1, world2.data(0,0));
EXPECT_EQ(2, world2.data(0,1));
EXPECT_EQ(3, world2.data(1,0));
EXPECT_EQ(0, world2.data(1,1));
}
TEST(QuickDraw, CopyBit32)
{
OffscreenWorld world1(32);
world1.data(0,3) = 1;
world1.data(0,7) = 2;
world1.data(1,3) = 3;
world1.data(1,7) = 4;
OffscreenWorld world2(32);
EraseRect(&world2.r);
RgnHandle rgn1 = NewRgn();
SetRectRgn(rgn1, 0,0,2,1);
RgnHandle rgn2 = NewRgn();
SetRectRgn(rgn2, 0,0,1,2);
UnionRgn(rgn1, rgn2, rgn1);
DisposeRgn(rgn2);
CopyBits(
&GrafPtr(world1.world)->portBits,
&GrafPtr(world2.world)->portBits,
&world1.r, &world2.r, srcCopy, rgn1);
DisposeRgn(rgn1);
EXPECT_EQ(1, world2.data(0,3));
EXPECT_EQ(2, world2.data(0,7));
EXPECT_EQ(3, world2.data(1,3));
EXPECT_EQ(255, world2.data(1,7));
}
TEST(QuickDraw, CopyMask8)
{
OffscreenPort mask;
mask.data(0,0) = 0xC0;
mask.data(1,0) = 0x80;
OffscreenWorld world1(8);
world1.data(0,0) = 1;
world1.data(0,1) = 2;
world1.data(1,0) = 3;
world1.data(1,1) = 4;
OffscreenWorld world2(8);
EraseRect(&world2.r);
CopyMask(
&GrafPtr(world1.world)->portBits,
&mask.port.portBits,
&GrafPtr(world2.world)->portBits,
&world1.r, &mask.r, &world2.r);
EXPECT_EQ(1, world2.data(0,0));
EXPECT_EQ(2, world2.data(0,1));
EXPECT_EQ(3, world2.data(1,0));
EXPECT_EQ(0, world2.data(1,1));
}
TEST(QuickDraw, CopyMask32)
{
OffscreenPort mask;
mask.data(0,0) = 0xC0;
mask.data(1,0) = 0x80;
OffscreenWorld world1(32);
world1.data(0,3) = 1;
world1.data(0,7) = 2;
world1.data(1,3) = 3;
world1.data(1,7) = 4;
OffscreenWorld world2(32);
EraseRect(&world2.r);
CopyMask(
&GrafPtr(world1.world)->portBits,
&mask.port.portBits,
&GrafPtr(world2.world)->portBits,
&world1.r, &mask.r, &world2.r);
EXPECT_EQ(1, world2.data(0,3));
EXPECT_EQ(2, world2.data(0,7));
EXPECT_EQ(3, world2.data(1,3));
EXPECT_EQ(255, world2.data(1,7));
}
<commit_msg>tests: skip color quickdraw tests if deep gworlds not supported<commit_after>#include "gtest/gtest.h"
#ifdef EXECUTOR
#define AUTOMATIC_CONVERSIONS
#include <QuickDraw.h>
#include <CQuickDraw.h>
#include <MemoryMgr.h>
using namespace Executor;
extern QDGlobals qd;
#define PTR(x) (&inout(x))
// FIXME: Executor still defines Pattern as an array, rather than an array wrapped in a struct
#define PATREF(pat) (pat)
inline bool hasDeepGWorlds()
{
return true;
}
#else
#include <Quickdraw.h>
#include <QDOffscreen.h>
#include <Gestalt.h>
#define PTR(x) (&x)
#define PATREF(pat) (&(pat))
inline bool hasDeepGWorlds()
{
long resp;
if(Gestalt(gestaltQuickdrawFeatures, &resp))
return false;
return resp & (1 << gestaltHasDeepGWorlds);
}
#endif
struct OffscreenPort
{
GrafPort port;
Rect r;
OffscreenPort(int height = 2, int width = 2)
{
OpenPort(&port);
short rowBytes = (width + 31) / 31 * 4;
port.portBits.rowBytes = rowBytes;
port.portBits.baseAddr = NewPtrClear(rowBytes * height);
SetRect(&r, 0,0,width,height);
port.portBits.bounds = r;
set();
}
~OffscreenPort()
{
ClosePort(&port);
}
void set()
{
SetPort(&port);
}
uint8_t& data(int row, int offset)
{
return reinterpret_cast<uint8_t&>(
port.portBits.baseAddr[row * port.portBits.rowBytes + offset]);
}
};
struct OffscreenWorld
{
GWorldPtr world = nullptr;
Rect r;
OffscreenWorld(int depth, int height = 2, int width = 2)
{
SetRect(&r,0,0,2,2);
NewGWorld(PTR(world), depth, &r, nullptr, nullptr, 0);
LockPixels(world->portPixMap);
set();
}
~OffscreenWorld()
{
if((GrafPtr)world == qd.thePort)
SetGDevice(GetMainDevice());
DisposeGWorld(world);
}
void set()
{
SetGWorld(world, nullptr);
}
uint8_t& data(int row, int offset)
{
Ptr baseAddr = (*world->portPixMap)->baseAddr;
uint8_t *data = (uint8_t*)baseAddr;
short rowBytes = (*world->portPixMap)->rowBytes;
rowBytes &= 0x3FFF;
return data[row * rowBytes + offset];
}
uint16_t data16(int row, int offset)
{
return data(row, offset*2) * 256 + data(row, offset*2+1);
}
uint32_t data32(int row, int offset)
{
return data16(row, offset*2) * 65536 + data16(row, offset*2+1);
}
};
TEST(QuickDraw, BWLine1)
{
OffscreenPort port;
EraseRect(&port.r);
MoveTo(0,0);
LineTo(2,2);
EXPECT_EQ(0x80, port.data(0,0));
EXPECT_EQ(0x40, port.data(1,0));
}
TEST(QuickDraw, GWorld8)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world(8);
EraseRect(&world.r);
MoveTo(0,0);
LineTo(2,2);
EXPECT_EQ(255, world.data(0,0));
EXPECT_EQ(0, world.data(0,1));
EXPECT_EQ(0, world.data(1,0));
EXPECT_EQ(255, world.data(1,1));
}
TEST(QuickDraw, GWorld16)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world(16);
EraseRect(&world.r);
MoveTo(0,0);
LineTo(2,2);
EXPECT_EQ(0, world.data16(0,0));
EXPECT_EQ(0x7FFF, world.data16(0,1));
}
TEST(QuickDraw, GWorld32)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world(32);
EraseRect(&world.r);
MoveTo(0,0);
LineTo(2,2);
EXPECT_EQ(0, world.data32(0,0));
EXPECT_EQ(0x00FFFFFF, world.data32(0,1));
}
TEST(QuickDraw, BasicQDColorBW)
{
OffscreenPort port;
FillRect(&port.r, PATREF(qd.gray));
EXPECT_EQ(0x80, port.data(0,0));
EXPECT_EQ(0x40, port.data(1,0));
ForeColor(whiteColor);
BackColor(redColor);
FillRect(&port.r, PATREF(qd.gray));
EXPECT_EQ(0x40, port.data(0,0));
EXPECT_EQ(0x80, port.data(1,0));
EXPECT_EQ(whiteColor, port.port.fgColor);
EXPECT_EQ(redColor, port.port.bkColor);
}
TEST(QuickDraw, BasicQDColor32)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world(32);
FillRect(&world.r, PATREF(qd.gray));
EXPECT_EQ(0x00000000, world.data32(0,0));
EXPECT_EQ(0x00FFFFFF, world.data32(0,1));
EXPECT_EQ(0x00FFFFFF, world.data32(1,0));
EXPECT_EQ(0x00000000, world.data32(1,1));
ForeColor(whiteColor);
BackColor(redColor);
const uint32_t rgbRed = 0xDD0806;
EXPECT_EQ(0x00FFFFFF, world.world->fgColor);
EXPECT_EQ(rgbRed, world.world->bkColor);
FillRect(&world.r, PATREF(qd.gray));
EXPECT_EQ(0x00FFFFFF, world.data32(0,0));
EXPECT_EQ(rgbRed, world.data32(0,1));
EXPECT_EQ(rgbRed, world.data32(1,0));
EXPECT_EQ(0x00FFFFFF, world.data32(1,1));
}
TEST(QuickDraw, GrayPattern32)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world(32);
FillRect(&world.r, PATREF(qd.gray));
EXPECT_EQ(0x00000000, world.data32(0,0));
EXPECT_EQ(0x00FFFFFF, world.data32(0,1));
EXPECT_EQ(0x00FFFFFF, world.data32(1,0));
EXPECT_EQ(0x00000000, world.data32(1,1));
}
TEST(QuickDraw, GrayPattern8)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world(8);
FillRect(&world.r, PATREF(qd.gray));
EXPECT_EQ(0xFF, world.data(0,0));
EXPECT_EQ(0x00, world.data(0,1));
EXPECT_EQ(0x00, world.data(1,0));
EXPECT_EQ(0xFF, world.data(1,1));
}
TEST(QuickDraw, GrayPattern1)
{
OffscreenPort port;
FillRect(&port.r, PATREF(qd.gray));
EXPECT_EQ(0x80, port.data(0,0));
EXPECT_EQ(0x40, port.data(1,0));
}
TEST(QuickDraw, BlackPattern32)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world(32);
FillRect(&world.r, PATREF(qd.black));
EXPECT_EQ(0x00000000, world.data32(0,0));
EXPECT_EQ(0x00000000, world.data32(0,1));
EXPECT_EQ(0x00000000, world.data32(1,0));
EXPECT_EQ(0x00000000, world.data32(1,1));
}
TEST(QuickDraw, CopyBit8)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world1(8);
world1.data(0,0) = 1;
world1.data(0,1) = 2;
world1.data(1,0) = 3;
world1.data(1,1) = 4;
OffscreenWorld world2(8);
EraseRect(&world2.r);
RgnHandle rgn1 = NewRgn();
SetRectRgn(rgn1, 0,0,2,1);
RgnHandle rgn2 = NewRgn();
SetRectRgn(rgn2, 0,0,1,2);
UnionRgn(rgn1, rgn2, rgn1);
DisposeRgn(rgn2);
CopyBits(
&GrafPtr(world1.world)->portBits,
&GrafPtr(world2.world)->portBits,
&world1.r, &world2.r, srcCopy, rgn1);
DisposeRgn(rgn1);
EXPECT_EQ(1, world2.data(0,0));
EXPECT_EQ(2, world2.data(0,1));
EXPECT_EQ(3, world2.data(1,0));
EXPECT_EQ(0, world2.data(1,1));
}
TEST(QuickDraw, CopyBit32)
{
if(!hasDeepGWorlds())
return;
OffscreenWorld world1(32);
world1.data(0,3) = 1;
world1.data(0,7) = 2;
world1.data(1,3) = 3;
world1.data(1,7) = 4;
OffscreenWorld world2(32);
EraseRect(&world2.r);
RgnHandle rgn1 = NewRgn();
SetRectRgn(rgn1, 0,0,2,1);
RgnHandle rgn2 = NewRgn();
SetRectRgn(rgn2, 0,0,1,2);
UnionRgn(rgn1, rgn2, rgn1);
DisposeRgn(rgn2);
CopyBits(
&GrafPtr(world1.world)->portBits,
&GrafPtr(world2.world)->portBits,
&world1.r, &world2.r, srcCopy, rgn1);
DisposeRgn(rgn1);
EXPECT_EQ(1, world2.data(0,3));
EXPECT_EQ(2, world2.data(0,7));
EXPECT_EQ(3, world2.data(1,3));
EXPECT_EQ(255, world2.data(1,7));
}
TEST(QuickDraw, CopyMask8)
{
if(!hasDeepGWorlds())
return;
OffscreenPort mask;
mask.data(0,0) = 0xC0;
mask.data(1,0) = 0x80;
OffscreenWorld world1(8);
world1.data(0,0) = 1;
world1.data(0,1) = 2;
world1.data(1,0) = 3;
world1.data(1,1) = 4;
OffscreenWorld world2(8);
EraseRect(&world2.r);
CopyMask(
&GrafPtr(world1.world)->portBits,
&mask.port.portBits,
&GrafPtr(world2.world)->portBits,
&world1.r, &mask.r, &world2.r);
EXPECT_EQ(1, world2.data(0,0));
EXPECT_EQ(2, world2.data(0,1));
EXPECT_EQ(3, world2.data(1,0));
EXPECT_EQ(0, world2.data(1,1));
}
TEST(QuickDraw, CopyMask32)
{
if(!hasDeepGWorlds())
return;
OffscreenPort mask;
mask.data(0,0) = 0xC0;
mask.data(1,0) = 0x80;
OffscreenWorld world1(32);
world1.data(0,3) = 1;
world1.data(0,7) = 2;
world1.data(1,3) = 3;
world1.data(1,7) = 4;
OffscreenWorld world2(32);
EraseRect(&world2.r);
CopyMask(
&GrafPtr(world1.world)->portBits,
&mask.port.portBits,
&GrafPtr(world2.world)->portBits,
&world1.r, &mask.r, &world2.r);
EXPECT_EQ(1, world2.data(0,3));
EXPECT_EQ(2, world2.data(0,7));
EXPECT_EQ(3, world2.data(1,3));
EXPECT_EQ(255, world2.data(1,7));
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "equations.hpp"
int main() {
using namespace std;
const vector<double> NUMBERS = {69, 420};
RandomEquationBuilder randomEquationBuilder(NUMBERS);
const int GOAL_NUMBER_COUNT = 3;
int TRY_COUNT = 25;
for (int i=0; i<TRY_COUNT; ++i) {
Equation equation = randomEquationBuilder.build(GOAL_NUMBER_COUNT);
try {
double result = equation.evaluate();
cout << equation.toString() << "= " << result << '\n';
} catch (std::runtime_error &rte) {
cout << equation.toString() << "failed. " << rte.what() << '\n';
}
}
return 0;
}<commit_msg>Compensated for modified Equation::toString()<commit_after>#include <iostream>
#include "equations.hpp"
int main() {
using namespace std;
const vector<double> NUMBERS = {69, 420};
RandomEquationBuilder randomEquationBuilder(NUMBERS);
const int GOAL_NUMBER_COUNT = 3;
int TRY_COUNT = 25;
for (int i=0; i<TRY_COUNT; ++i) {
Equation equation = randomEquationBuilder.build(GOAL_NUMBER_COUNT);
try {
double result = equation.evaluate();
cout << equation.toString() << " = " << result << '\n';
} catch (std::runtime_error &rte) {
cout << equation.toString() << "failed. " << rte.what() << '\n';
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "SkGraphics.h"
#include "Test.h"
using namespace skiatest;
// need to explicitly declare this, or we get some weird infinite loop llist
template TestRegistry* TestRegistry::gHead;
class Iter {
public:
Iter(Reporter* r) : fReporter(r) {
r->ref();
fReg = TestRegistry::Head();
}
~Iter() {
fReporter->unref();
}
Test* next() {
if (fReg) {
TestRegistry::Factory fact = fReg->factory();
fReg = fReg->next();
Test* test = fact(NULL);
test->setReporter(fReporter);
return test;
}
return NULL;
}
static int Count() {
const TestRegistry* reg = TestRegistry::Head();
int count = 0;
while (reg) {
count += 1;
reg = reg->next();
}
return count;
}
private:
Reporter* fReporter;
const TestRegistry* fReg;
};
static const char* result2string(Reporter::Result result) {
return result == Reporter::kPassed ? "passed" : "FAILED";
}
class DebugfReporter : public Reporter {
public:
DebugfReporter(bool androidMode) : fAndroidMode(androidMode) {}
void setIndexOfTotal(int index, int total) {
fIndex = index;
fTotal = total;
}
protected:
virtual void onStart(Test* test) {
this->dumpState(test, kStarting_State);
}
virtual void onReport(const char desc[], Reporter::Result result) {
if (!fAndroidMode) {
SkDebugf("\t%s: %s\n", result2string(result), desc);
}
}
virtual void onEnd(Test* test) {
this->dumpState(test, this->getCurrSuccess() ?
kSucceeded_State : kFailed_State);
}
private:
enum State {
kStarting_State = 1,
kSucceeded_State = 0,
kFailed_State = -2
};
void dumpState(Test* test, State state) {
if (fAndroidMode) {
SkDebugf("INSTRUMENTATION_STATUS: test=%s\n", test->getName());
SkDebugf("INSTRUMENTATION_STATUS: class=com.skia\n");
SkDebugf("INSTRUMENTATION_STATUS: current=%d\n", fIndex+1);
SkDebugf("INSTRUMENTATION_STATUS: numtests=%d\n", fTotal);
SkDebugf("INSTRUMENTATION_STATUS_CODE: %d\n", state);
} else {
if (kStarting_State == state) {
SkDebugf("[%d/%d] %s...\n", fIndex+1, fTotal, test->getName());
} else if (kFailed_State == state) {
SkDebugf("---- FAILED\n");
}
}
}
int fIndex, fTotal;
bool fAndroidMode;
};
int main (int argc, char * const argv[]) {
SkAutoGraphics ag;
bool androidMode = false;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-android")) {
androidMode = true;
}
}
DebugfReporter reporter(androidMode);
Iter iter(&reporter);
Test* test;
const int count = Iter::Count();
int index = 0;
int successCount = 0;
while ((test = iter.next()) != NULL) {
reporter.setIndexOfTotal(index, count);
successCount += test->run();
SkDELETE(test);
index += 1;
}
if (!androidMode) {
SkDebugf("Finished %d tests, %d failures.\n", count,
count - successCount);
}
return 0;
}
<commit_msg>make tests return nonzero if failing<commit_after>#include "SkGraphics.h"
#include "Test.h"
using namespace skiatest;
// need to explicitly declare this, or we get some weird infinite loop llist
template TestRegistry* TestRegistry::gHead;
class Iter {
public:
Iter(Reporter* r) : fReporter(r) {
r->ref();
fReg = TestRegistry::Head();
}
~Iter() {
fReporter->unref();
}
Test* next() {
if (fReg) {
TestRegistry::Factory fact = fReg->factory();
fReg = fReg->next();
Test* test = fact(NULL);
test->setReporter(fReporter);
return test;
}
return NULL;
}
static int Count() {
const TestRegistry* reg = TestRegistry::Head();
int count = 0;
while (reg) {
count += 1;
reg = reg->next();
}
return count;
}
private:
Reporter* fReporter;
const TestRegistry* fReg;
};
static const char* result2string(Reporter::Result result) {
return result == Reporter::kPassed ? "passed" : "FAILED";
}
class DebugfReporter : public Reporter {
public:
DebugfReporter(bool androidMode) : fAndroidMode(androidMode) {}
void setIndexOfTotal(int index, int total) {
fIndex = index;
fTotal = total;
}
protected:
virtual void onStart(Test* test) {
this->dumpState(test, kStarting_State);
}
virtual void onReport(const char desc[], Reporter::Result result) {
if (!fAndroidMode) {
SkDebugf("\t%s: %s\n", result2string(result), desc);
}
}
virtual void onEnd(Test* test) {
this->dumpState(test, this->getCurrSuccess() ?
kSucceeded_State : kFailed_State);
}
private:
enum State {
kStarting_State = 1,
kSucceeded_State = 0,
kFailed_State = -2
};
void dumpState(Test* test, State state) {
if (fAndroidMode) {
SkDebugf("INSTRUMENTATION_STATUS: test=%s\n", test->getName());
SkDebugf("INSTRUMENTATION_STATUS: class=com.skia\n");
SkDebugf("INSTRUMENTATION_STATUS: current=%d\n", fIndex+1);
SkDebugf("INSTRUMENTATION_STATUS: numtests=%d\n", fTotal);
SkDebugf("INSTRUMENTATION_STATUS_CODE: %d\n", state);
} else {
if (kStarting_State == state) {
SkDebugf("[%d/%d] %s...\n", fIndex+1, fTotal, test->getName());
} else if (kFailed_State == state) {
SkDebugf("---- FAILED\n");
}
}
}
int fIndex, fTotal;
bool fAndroidMode;
};
int main (int argc, char * const argv[]) {
SkAutoGraphics ag;
bool androidMode = false;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-android")) {
androidMode = true;
}
}
DebugfReporter reporter(androidMode);
Iter iter(&reporter);
Test* test;
const int count = Iter::Count();
int index = 0;
int successCount = 0;
while ((test = iter.next()) != NULL) {
reporter.setIndexOfTotal(index, count);
successCount += test->run();
SkDELETE(test);
index += 1;
}
if (!androidMode) {
SkDebugf("Finished %d tests, %d failures.\n", count,
count - successCount);
}
return (count == successCount) ? 0 : 1;
}
<|endoftext|>
|
<commit_before>#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <string>
// This solve a bug with clang and libc++
template class std::basic_string<char>;
int main(int argc, char** argv) {
boost::array<int, 12> values = {1,2,3,4,5,6,7,100,99,98,97,96};
std::size_t count0 = std::count_if(values.begin(), values.end(), std::bind1st(std::less<int>(),5));
std::size_t count1 = std::count_if(values.begin(), values.end(), boost::bind(std::less<int>(), 5, _1));
std::cout << count0 << " " << count1 << std::endl;
boost::array<std::string, 3> str_values = {"We ", "are", "the champions!"};
count0 = std::count_if(str_values.begin(), str_values.end(), std::mem_fun_ref(&std::string::empty));
count1 = std::count_if(str_values.begin(), str_values.end(), boost::bind(&std::string::empty, _1));
std::cout << count0 << " " << count1 << std::endl;
count1 = std::count_if(str_values.begin(), str_values.end(),
boost::bind(std::less<std::size_t>(), boost::bind(&std::string::size, _1), 5) );
std::string s("Expensive copy constructor of std::string will be called when binding");
count0 = std::count_if(str_values.begin(), str_values.end(), std::bind2nd(std::less<std::string>(), s) );
count1 = std::count_if(str_values.begin(), str_values.end(), boost::bind(std::less<std::string>(), _1, s));
std::cout << count0 << " " << count1 << std::endl;
/*std::string s("Expensive copy constructor of std::string now won't be called when binding");
count0 = std::count_if(str_values.begin(), str_values.end(),
std::bind2nd(std::less<std::string>(), boost::cref(s)));
count1 = std::count_if(str_values.begin(), str_values.end(),
boost::bind(std::less<std::string>(), _1, boost::cref(s)));*/
return 0;
}<commit_msg>Added link to a bug's description.<commit_after>#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <string>
// This solve a bug with clang and libc++
// http://stackoverflow.com/q/29324619
template class std::basic_string<char>;
int main(int argc, char** argv) {
boost::array<int, 12> values = {1,2,3,4,5,6,7,100,99,98,97,96};
std::size_t count0 = std::count_if(values.begin(), values.end(), std::bind1st(std::less<int>(),5));
std::size_t count1 = std::count_if(values.begin(), values.end(), boost::bind(std::less<int>(), 5, _1));
std::cout << count0 << " " << count1 << std::endl;
boost::array<std::string, 3> str_values = {"We ", "are", "the champions!"};
count0 = std::count_if(str_values.begin(), str_values.end(), std::mem_fun_ref(&std::string::empty));
count1 = std::count_if(str_values.begin(), str_values.end(), boost::bind(&std::string::empty, _1));
std::cout << count0 << " " << count1 << std::endl;
count1 = std::count_if(str_values.begin(), str_values.end(),
boost::bind(std::less<std::size_t>(), boost::bind(&std::string::size, _1), 5) );
std::string s("Expensive copy constructor of std::string will be called when binding");
count0 = std::count_if(str_values.begin(), str_values.end(), std::bind2nd(std::less<std::string>(), s) );
count1 = std::count_if(str_values.begin(), str_values.end(), boost::bind(std::less<std::string>(), _1, s));
std::cout << count0 << " " << count1 << std::endl;
/*std::string s("Expensive copy constructor of std::string now won't be called when binding");
count0 = std::count_if(str_values.begin(), str_values.end(),
std::bind2nd(std::less<std::string>(), boost::cref(s)));
count1 = std::count_if(str_values.begin(), str_values.end(),
boost::bind(std::less<std::string>(), _1, boost::cref(s)));*/
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2003 Tommi Maekitalo
*
* 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 <exception>
#include <iostream>
#include <cxxtools/net/tcpstream.h>
#include <cxxtools/arg.h>
#include <cxxtools/log.h>
int main(int argc, char* argv[])
{
try
{
log_init();
cxxtools::Arg<const char*> ip(argc, argv, 'i');
cxxtools::Arg<unsigned short> port(argc, argv, 'p', 1234);
cxxtools::Arg<unsigned> bufsize(argc, argv, 'b', 8192);
cxxtools::Arg<bool> listen(argc, argv, 'l');
cxxtools::Arg<bool> read_reply(argc, argv, 'r');
if (listen)
{
// I'm a server
// listen to a port
cxxtools::net::TcpServer server(ip.getValue(), port);
// accept a connetion
cxxtools::net::iostream worker(server, bufsize);
// copy to stdout
std::cout << worker.rdbuf();
}
else
{
// I'm a client
// connect to server
cxxtools::net::iostream peer(ip, port, bufsize);
// copy stdin to server
peer << std::cin.rdbuf() << std::flush;
if (read_reply)
// copy answer to stdout
std::cout << peer.rdbuf() << std::flush;
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
<commit_msg>fix netcat demo program: omitting ip switch -i must not lead to a crash<commit_after>/*
* Copyright (C) 2003 Tommi Maekitalo
*
* 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 <exception>
#include <iostream>
#include <cxxtools/net/tcpstream.h>
#include <cxxtools/arg.h>
#include <cxxtools/log.h>
int main(int argc, char* argv[])
{
try
{
log_init();
cxxtools::Arg<std::string> ip(argc, argv, 'i');
cxxtools::Arg<unsigned short> port(argc, argv, 'p', 1234);
cxxtools::Arg<unsigned> bufsize(argc, argv, 'b', 8192);
cxxtools::Arg<bool> listen(argc, argv, 'l');
cxxtools::Arg<bool> read_reply(argc, argv, 'r');
if (listen)
{
// I'm a server
// listen to a port
cxxtools::net::TcpServer server(ip.getValue(), port);
// accept a connetion
cxxtools::net::iostream worker(server, bufsize);
// copy to stdout
std::cout << worker.rdbuf();
}
else
{
// I'm a client
// connect to server
cxxtools::net::iostream peer(ip, port, bufsize);
// copy stdin to server
peer << std::cin.rdbuf() << std::flush;
if (read_reply)
// copy answer to stdout
std::cout << peer.rdbuf() << std::flush;
}
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
<|endoftext|>
|
<commit_before>/*
* image.cpp
*
* Created on: Aug 1, 2011
* Author: sanda
*/
#ifndef IMAGE_CPP_
#define IMAGE_CPP_
//
// *** System
//
#include <iostream>
//
// *** Boost
//
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>
//
// *** ViennaCL
//
#define VIENNACL_DEBUG_ALL
#define VIENNACL_HAVE_UBLAS 1
#include "viennacl/scalar.hpp"
#include "viennacl/matrix.hpp"
#include "viennacl/vector.hpp"
#include "viennacl/image.hpp"
#include "viennacl/linalg/prod.hpp"
#include "viennacl/linalg/norm_2.hpp"
#include "viennacl/linalg/direct_solve.hpp"
#include "examples/tutorial/Random.hpp"
//#define cimg_display 0
//#include "../lib/CImg.h"
//#include "../lib/SDKUtil/include/SDKCommon.hpp"
//#include "../lib/SDKUtil/include/SDKApplication.hpp"
//#include "../lib/SDKUtil/include/SDKFile.hpp"
#include "../lib/SDKUtil/SDKBitMap.cpp"
//
// -------------------------------------------------------------
//
//
// -------------------------------------------------------------
//
#define VIENNACL_DEBUG_ALL
using namespace std;
int test()
{
int retval = EXIT_SUCCESS;
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "## Test :: Image" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << std::endl;
viennacl::image<CL_RGBA,CL_UNORM_INT8> image;
// --------------------------------------------------------------------------
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "## Test :: Image 256x256" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
//cimg_library::CImg<unsigned char> img("/home/sanda/Desktop/CImg-1.5.0_beta/examples/img/lena.pgm");
//img.save("/home/sanda/Desktop/CImg-1.5.0_beta/examples/img/lena2.pgm");
streamsdk::SDKBitMap img;
img.load("/home/sanda/Desktop/CImg-1.5.0_beta/examples/img/lena2.pgm");
streamsdk::uchar4* d= img.getPixels();
cl_uchar4* f;
viennacl::image<CL_RGBA,CL_UNORM_INT8> image2(8,8);
viennacl::image<CL_RGBA,CL_UNORM_INT8> image3(8,8);
viennacl::image<CL_RGBA,CL_UNORM_INT8> image4 = image2 + image3;
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << std::endl;
return retval;
}
int main()
{
test();
}
#endif /* IMAGE_CPP_ */
<commit_msg>image test for add/subtract<commit_after>/*
* image.cpp
*
* Created on: Aug 1, 2011
* Author: sanda
*/
#ifndef IMAGE_CPP_
#define IMAGE_CPP_
//
// *** System
//
#include <iostream>
//
// *** Boost
//
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/vector.hpp>
//
// *** ViennaCL
//
#define VIENNACL_DEBUG_ALL
#define VIENNACL_HAVE_UBLAS 1
#include "viennacl/scalar.hpp"
#include "viennacl/matrix.hpp"
#include "viennacl/vector.hpp"
#include "viennacl/image.hpp"
#include "viennacl/linalg/prod.hpp"
#include "viennacl/linalg/norm_2.hpp"
#include "viennacl/linalg/direct_solve.hpp"
#include "examples/tutorial/Random.hpp"
#include <vector>
//
// -------------------------------------------------------------
//
//
// -------------------------------------------------------------
//
#define VIENNACL_DEBUG_ALL
using namespace boost::numeric;
int test()
{
int retval = EXIT_SUCCESS;
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "## Test :: Image 256x256" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "----------------------------------------------" << std::endl;
const int size = 2;
const int pixelSize = 4;
int c = 0;
unsigned char* srcImg2 = new unsigned char[pixelSize * size * size];
unsigned char* srcImg3 = new unsigned char[pixelSize * size * size];
for(int i=0; i< pixelSize* size * size;i++)
{
srcImg2[i] = 124;
srcImg3[i] = 120;
}
std::vector<unsigned char> v(pixelSize * size * size);
for(std::vector<unsigned char>::iterator iter=v.begin(); iter < v.end();++iter)
*iter=0;
viennacl::image<CL_RGBA, CL_UNORM_INT8> image2(size, size, (void*)srcImg2);
viennacl::image<CL_RGBA, CL_UNORM_INT8> image3(size, size, (void*)srcImg3);
(image2+image3).fast_copy_cpu(v.begin());
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << "Vector Init" << std::endl;
c = 0;
for(std::vector<unsigned char>::iterator iter=v.begin(); iter < v.end();++iter)
{
std::cout << ((int)*iter ) << " ";
if (++c % 4 == 0)
{
std::cout<<std::endl;
c = 0;
}
}
std::cout<<" End Vector" << std::endl;
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << std::endl;
(image2 - image3).fast_copy_cpu(v.begin());
std::cout << "Vector Result" << std::endl;
c = 0;
for(std::vector<unsigned char>::iterator iter=v.begin(); iter < v.end();++iter)
{
std::cout << ((int)*iter ) << " ";
if (++c % 4 == 0)
{
std::cout<<std::endl;
c = 0;
}
}
std::cout<<" End Vector" << std::endl;
delete[] srcImg2;
delete[] srcImg3;
std::cout << std::endl;
std::cout << "----------------------------------------------" << std::endl;
std::cout << std::endl;
return retval;
}
int main()
{
test();
}
#endif /* IMAGE_CPP_ */
<|endoftext|>
|
<commit_before>
/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#ifdef HAVE_SDL
#include <stdlib.h>
#include <string>
#include "SDLMedia.h"
#include "ErrorHandler.h"
#ifdef HALF_RATE_AUDIO
static const int defaultAudioRate=11025;
#else
static const int defaultAudioRate=22050;
#endif
//
// SDLMedia
//
SDLMedia::SDLMedia() : BzfMedia()
{
cmdFill = 0;
audioReady = false;
}
double SDLMedia::stopwatch(bool start)
{
Uint32 currentTick = SDL_GetTicks(); //msec
if (start) {
stopwatchTime = currentTick;
return 0.0;
}
if (currentTick >= stopwatchTime)
return (double) (currentTick - stopwatchTime) * 0.001; // sec
else
//Clock is wrapped : happens after 49 days
//Should be "wrap value" - stopwatchtime. Now approx.
return (double) currentTick * 0.001;
}
void SDLMedia::sleep(float timeInSeconds)
{
// Not used ... however ... here it is
SDL_Delay((Uint32) (timeInSeconds * 1000.0));
}
bool SDLMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
printFatalError("Could not initialize SDL-Audio: %s.\n", SDL_GetError());
exit(-1);
};
static SDL_AudioSpec desired;
// what the frequency?
audioOutputRate = defaultAudioRate;
// how big a fragment to use? we want to hold at around 1/10th of
// a second.
int fragmentSize = (int)(0.08f * (float)audioOutputRate);
int n;
n = 0;
while ((1 << n) < fragmentSize)
++n;
// samples are two bytes each so double the size
audioBufferSize = 1 << (n + 1);
desired.freq = audioOutputRate;
desired.format = AUDIO_S16SYS;
desired.channels = 2;
desired.samples = audioBufferSize >> 1; // In stereo samples
desired.callback = &fillAudioWrapper;
desired.userdata = (void *) this; // To handle Wrap of func
/* Open the audio device, forcing the desired format */
if (SDL_OpenAudio(&desired, NULL) < 0) {
fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
return false;
}
// make an output buffer
outputBuffer = new short[audioBufferSize];
// ready to go
audioReady = true;
return true;
}
void SDLMedia::closeAudio()
{
// Stop Audio to avoid callback
SDL_PauseAudio(1);
SDL_CloseAudio();
delete [] outputBuffer;
outputBuffer = 0;
SDL_QuitSubSystem(SDL_INIT_AUDIO);
audioReady = false;
}
void SDLMedia::startAudioCallback(bool (*proc)(void))
{
userCallback = proc;
// Stop sending silence and start calling audio callback
SDL_PauseAudio(0);
}
void SDLMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audioReady) return;
SDL_LockAudio();
// Discard command if full
if ((cmdFill + len) < 2048) {
memcpy(&cmdQueue[cmdFill], cmd, len);
// We should awake audioSleep - but game become unplayable
// using here an SDL_CondSignal(wakeCond)
cmdFill += len;
}
SDL_UnlockAudio();
}
bool SDLMedia::readSoundCommand(void* cmd, int len)
{
bool result = false;
if (cmdFill >= len) {
memcpy(cmd, cmdQueue, len);
// repack list of command waiting to be processed
memmove(cmdQueue, &cmdQueue[len], cmdFill - len);
cmdFill -= len;
result = true;
}
return result;
}
int SDLMedia::getAudioOutputRate() const
{
return audioOutputRate;
}
int SDLMedia::getAudioBufferSize() const
{
return audioBufferSize;
}
int SDLMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
void SDLMedia::fillAudio (Uint8 * stream, int len)
{
userCallback();
Uint8* soundBuffer = stream;
int transferSize = (audioBufferSize - sampleToSend) * 2;
if (transferSize > len)
transferSize = len;
// just copying into the soundBuffer is enough, SDL is looking for
// something different from silence sample
memcpy(soundBuffer,
(Uint8 *) &outputBuffer[sampleToSend],
transferSize);
sampleToSend += transferSize / 2;
soundBuffer += transferSize;
len -= transferSize;
}
void SDLMedia::fillAudioWrapper (void * userdata, Uint8 * stream, int len)
{
SDLMedia * me = (SDLMedia *) userdata;
me->fillAudio(stream, len);
};
void SDLMedia::writeAudioFrames(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
while (numSamples > 0) {
if (numSamples>audioBufferSize)
limit=audioBufferSize;
else
limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0)
outputBuffer[j] = -32767;
else
if (samples[j] > 32767.0)
outputBuffer[j] = 32767;
else
outputBuffer[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
outputBuffer[j] = 0;
}
sampleToSend = 0;
samples += audioBufferSize;
numSamples -= audioBufferSize;
}
}
// Setting Audio Driver
void SDLMedia::setDriver(std::string driverName) {
char envAssign[256];
std::string envVar = "SDL_AUDIODRIVER=" + driverName;
strncpy(envAssign, envVar.c_str(), 255);
envAssign[255] = '\0';
putenv(envAssign);
};
// Setting Audio Device
void SDLMedia::setDevice(std::string deviceName) {
char envAssign[256];
std::string envVar = "SDL_PATH_DSP=" + deviceName;
strncpy(envAssign, envVar.c_str(), 255);
envAssign[255] = '\0';
putenv(envAssign);
};
float* SDLMedia::doReadSound(const std::string &filename, int &numFrames,
int &rate) const
{
SDL_AudioSpec wav_spec;
Uint32 wav_length;
Uint8 *wav_buffer;
int ret;
SDL_AudioCVT wav_cvt;
int16_t *cvt16;
int i;
float *data = NULL;
rate = defaultAudioRate;
if (SDL_LoadWAV(filename.c_str(), &wav_spec, &wav_buffer, &wav_length)) {
/* Build AudioCVT */
ret = SDL_BuildAudioCVT(&wav_cvt,
wav_spec.format, wav_spec.channels, wav_spec.freq,
AUDIO_S16SYS, 2, defaultAudioRate);
/* Check that the convert was built */
if (ret == -1) {
printFatalError("Could not build converter for Wav file %s: %s.\n",
filename.c_str(), SDL_GetError());
} else {
/* Setup for conversion */
wav_cvt.buf = (Uint8*)malloc(wav_length * wav_cvt.len_mult);
wav_cvt.len = wav_length;
memcpy(wav_cvt.buf, wav_buffer, wav_length);
/* And now we're ready to convert */
SDL_ConvertAudio(&wav_cvt);
numFrames = (int)(wav_length * wav_cvt.len_ratio / 4);
cvt16 = (int16_t *)wav_cvt.buf;
data = new float[numFrames * 2];
for (i = 0; i < numFrames * 2; i++)
data[i] = cvt16[i];
free(wav_cvt.buf);
}
SDL_FreeWAV(wav_buffer);
}
return data;
}
#endif //HAVE_SDL
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>reduce delay in sound<commit_after>
/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#ifdef HAVE_SDL
#include <stdlib.h>
#include <string>
#include "SDLMedia.h"
#include "ErrorHandler.h"
#ifdef HALF_RATE_AUDIO
static const int defaultAudioRate=11025;
#else
static const int defaultAudioRate=22050;
#endif
//
// SDLMedia
//
SDLMedia::SDLMedia() : BzfMedia()
{
cmdFill = 0;
audioReady = false;
}
double SDLMedia::stopwatch(bool start)
{
Uint32 currentTick = SDL_GetTicks(); //msec
if (start) {
stopwatchTime = currentTick;
return 0.0;
}
if (currentTick >= stopwatchTime)
return (double) (currentTick - stopwatchTime) * 0.001; // sec
else
//Clock is wrapped : happens after 49 days
//Should be "wrap value" - stopwatchtime. Now approx.
return (double) currentTick * 0.001;
}
void SDLMedia::sleep(float timeInSeconds)
{
// Not used ... however ... here it is
SDL_Delay((Uint32) (timeInSeconds * 1000.0));
}
bool SDLMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
if (SDL_InitSubSystem(SDL_INIT_AUDIO) == -1) {
printFatalError("Could not initialize SDL-Audio: %s.\n", SDL_GetError());
exit(-1);
};
static SDL_AudioSpec desired;
// what the frequency?
audioOutputRate = defaultAudioRate;
// how big a fragment to use? we want to hold at around 1/10th of
// a second.
// probably SDL is using multiple buffering, make it a 3rd
int fragmentSize = (int)(0.03f * (float)audioOutputRate);
int n;
n = 0;
while ((1 << n) < fragmentSize)
++n;
// samples are two bytes each so double the size
audioBufferSize = 1 << (n + 1);
desired.freq = audioOutputRate;
desired.format = AUDIO_S16SYS;
desired.channels = 2;
desired.samples = audioBufferSize >> 1; // In stereo samples
desired.callback = &fillAudioWrapper;
desired.userdata = (void *) this; // To handle Wrap of func
/* Open the audio device, forcing the desired format */
if (SDL_OpenAudio(&desired, NULL) < 0) {
fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError());
return false;
}
// make an output buffer
outputBuffer = new short[audioBufferSize];
// ready to go
audioReady = true;
return true;
}
void SDLMedia::closeAudio()
{
// Stop Audio to avoid callback
SDL_PauseAudio(1);
SDL_CloseAudio();
delete [] outputBuffer;
outputBuffer = 0;
SDL_QuitSubSystem(SDL_INIT_AUDIO);
audioReady = false;
}
void SDLMedia::startAudioCallback(bool (*proc)(void))
{
userCallback = proc;
// Stop sending silence and start calling audio callback
SDL_PauseAudio(0);
}
void SDLMedia::writeSoundCommand(const void* cmd, int len)
{
if (!audioReady) return;
SDL_LockAudio();
// Discard command if full
if ((cmdFill + len) < 2048) {
memcpy(&cmdQueue[cmdFill], cmd, len);
// We should awake audioSleep - but game become unplayable
// using here an SDL_CondSignal(wakeCond)
cmdFill += len;
}
SDL_UnlockAudio();
}
bool SDLMedia::readSoundCommand(void* cmd, int len)
{
bool result = false;
if (cmdFill >= len) {
memcpy(cmd, cmdQueue, len);
// repack list of command waiting to be processed
memmove(cmdQueue, &cmdQueue[len], cmdFill - len);
cmdFill -= len;
result = true;
}
return result;
}
int SDLMedia::getAudioOutputRate() const
{
return audioOutputRate;
}
int SDLMedia::getAudioBufferSize() const
{
return audioBufferSize;
}
int SDLMedia::getAudioBufferChunkSize() const
{
return audioBufferSize>>1;
}
void SDLMedia::fillAudio (Uint8 * stream, int len)
{
userCallback();
Uint8* soundBuffer = stream;
int transferSize = (audioBufferSize - sampleToSend) * 2;
if (transferSize > len)
transferSize = len;
// just copying into the soundBuffer is enough, SDL is looking for
// something different from silence sample
memcpy(soundBuffer,
(Uint8 *) &outputBuffer[sampleToSend],
transferSize);
sampleToSend += transferSize / 2;
soundBuffer += transferSize;
len -= transferSize;
}
void SDLMedia::fillAudioWrapper (void * userdata, Uint8 * stream, int len)
{
SDLMedia * me = (SDLMedia *) userdata;
me->fillAudio(stream, len);
};
void SDLMedia::writeAudioFrames(
const float* samples, int numFrames)
{
int numSamples = 2 * numFrames;
int limit;
while (numSamples > 0) {
if (numSamples>audioBufferSize)
limit=audioBufferSize;
else
limit=numSamples;
for (int j = 0; j < limit; j++) {
if (samples[j] < -32767.0)
outputBuffer[j] = -32767;
else
if (samples[j] > 32767.0)
outputBuffer[j] = 32767;
else
outputBuffer[j] = short(samples[j]);
}
// fill out the chunk (we never write a partial chunk)
if (limit < audioBufferSize) {
for (int j = limit; j < audioBufferSize; ++j)
outputBuffer[j] = 0;
}
sampleToSend = 0;
samples += audioBufferSize;
numSamples -= audioBufferSize;
}
}
// Setting Audio Driver
void SDLMedia::setDriver(std::string driverName) {
char envAssign[256];
std::string envVar = "SDL_AUDIODRIVER=" + driverName;
strncpy(envAssign, envVar.c_str(), 255);
envAssign[255] = '\0';
putenv(envAssign);
};
// Setting Audio Device
void SDLMedia::setDevice(std::string deviceName) {
char envAssign[256];
std::string envVar = "SDL_PATH_DSP=" + deviceName;
strncpy(envAssign, envVar.c_str(), 255);
envAssign[255] = '\0';
putenv(envAssign);
};
float* SDLMedia::doReadSound(const std::string &filename, int &numFrames,
int &rate) const
{
SDL_AudioSpec wav_spec;
Uint32 wav_length;
Uint8 *wav_buffer;
int ret;
SDL_AudioCVT wav_cvt;
int16_t *cvt16;
int i;
float *data = NULL;
rate = defaultAudioRate;
if (SDL_LoadWAV(filename.c_str(), &wav_spec, &wav_buffer, &wav_length)) {
/* Build AudioCVT */
ret = SDL_BuildAudioCVT(&wav_cvt,
wav_spec.format, wav_spec.channels, wav_spec.freq,
AUDIO_S16SYS, 2, defaultAudioRate);
/* Check that the convert was built */
if (ret == -1) {
printFatalError("Could not build converter for Wav file %s: %s.\n",
filename.c_str(), SDL_GetError());
} else {
/* Setup for conversion */
wav_cvt.buf = (Uint8*)malloc(wav_length * wav_cvt.len_mult);
wav_cvt.len = wav_length;
memcpy(wav_cvt.buf, wav_buffer, wav_length);
/* And now we're ready to convert */
SDL_ConvertAudio(&wav_cvt);
numFrames = (int)(wav_length * wav_cvt.len_ratio / 4);
cvt16 = (int16_t *)wav_cvt.buf;
data = new float[numFrames * 2];
for (i = 0; i < numFrames * 2; i++)
data[i] = cvt16[i];
free(wav_cvt.buf);
}
SDL_FreeWAV(wav_buffer);
}
return data;
}
#endif //HAVE_SDL
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Jeff Myers 10/13/97 changed direct sound cooperative level to
// exclusive for compatibility with NT.
#ifdef HAVE_DSOUND_H
#include "WinMedia.h"
#include "WinWindow.h"
#include "TimeKeeper.h"
#include "Pack.h"
#include <stdio.h>
static const int defaultOutputRate = 22050;
static const int NumChunks = 4;
void (*WinMedia::threadProc)(void*);
void* WinMedia::threadData;
WinMedia::WinMedia(WinWindow* _window) :
window(_window->getHandle()),
audioReady(false),
audioInterface(NULL),
audioPrimaryPort(NULL),
audioPort(NULL),
outputBuffer(NULL),
audioCommandBuffer(NULL),
audioCommandEvent(NULL),
audioCommandMutex(NULL),
audioThread(NULL)
{
}
WinMedia::~WinMedia()
{
}
bool WinMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
// create DirectSound interface pointer
if (DirectSoundCreate(NULL, &audioInterface, NULL) != DS_OK)
return false;
// set cooperative level
if (audioInterface->SetCooperativeLevel(window, DSSCL_EXCLUSIVE) != DS_OK) {
closeAudio();
return false;
}
// create audio command queue
audioCommandBufferHead = 0;
audioCommandBufferTail = 0;
audioCommandBufferLen = 4096;
audioCommandBuffer = new unsigned char[audioCommandBufferLen];
audioCommandEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
audioCommandMutex = CreateMutex(NULL, FALSE, NULL);
// compute desired configuration
audioNumChannels = 2;
audioOutputRate = getAudioOutputRate();
audioBufferChunkSize = (long)(0.1 * audioOutputRate) & ~1;
audioLowWaterMark = (NumChunks - 1) * audioBufferChunkSize;
audioBufferSize = NumChunks * audioBufferChunkSize;
audioBytesPerSample = 2;
audioBytesPerFrame = audioNumChannels * audioBytesPerSample;
// create a `primary sound buffer'; we only need this to force it
// to play at all times (presumably decreasing latency on secondary
// buffers).
DSBUFFERDESC audioBufferParams;
audioBufferParams.dwSize = sizeof(audioBufferParams);
audioBufferParams.dwBufferBytes = 0;
audioBufferParams.dwReserved = 0;
audioBufferParams.lpwfxFormat = NULL;
audioBufferParams.dwFlags = DSBCAPS_PRIMARYBUFFER |
DSBCAPS_CTRLFREQUENCY |
DSBCAPS_GETCURRENTPOSITION2;
HRESULT status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPrimaryPort, NULL);
if (FAILED(status)) {
audioBufferParams.dwFlags = DSBCAPS_PRIMARYBUFFER |
DSBCAPS_GETCURRENTPOSITION2;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPrimaryPort, NULL);
}
if (FAILED(status)) {
audioBufferParams.dwFlags = DSBCAPS_PRIMARYBUFFER;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPrimaryPort, NULL);
}
if (FAILED(status)) {
closeAudio();
return false;
}
// haven't started playing yet
audioPlaying = false;
// have written zero samples so far
audioWritePtr = 0;
// create a `secondary sound buffer'; we need a buffer large enough
// for 3 audioBufferSize chunks. we'll fill it up then wait for it
// to drain below the audioLowWaterMark, then fill it up again.
WAVEFORMATEX waveFormat;
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nChannels = audioNumChannels;
waveFormat.nSamplesPerSec = audioOutputRate;
waveFormat.nBlockAlign = audioBytesPerFrame;
waveFormat.nAvgBytesPerSec = audioBytesPerFrame * waveFormat.nSamplesPerSec;
waveFormat.wBitsPerSample = 8 * audioBytesPerSample;
waveFormat.cbSize = 0;
audioBufferParams.dwSize = sizeof(audioBufferParams);
audioBufferParams.dwBufferBytes = audioBufferSize * audioBytesPerSample;
audioBufferParams.dwReserved = 0;
audioBufferParams.lpwfxFormat = &waveFormat;
audioBufferParams.dwFlags = DSBCAPS_CTRLFREQUENCY |
DSBCAPS_GETCURRENTPOSITION2;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPort, NULL);
if (FAILED(status)) {
audioBufferParams.dwFlags = DSBCAPS_CTRLFREQUENCY;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPort, NULL);
}
if (FAILED(status)) {
audioBufferParams.dwFlags = DSBCAPS_GETCURRENTPOSITION2;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPort, NULL);
}
if (FAILED(status)) {
audioBufferParams.dwFlags = 0;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPort, NULL);
}
if (FAILED(status)) {
closeAudio();
return false;
}
// audioPrimaryPort->Play(0, 0, DSBPLAY_LOOPING);
// make an output buffer
outputBuffer = new short[audioBufferChunkSize];
audioReady = true;
return true;
}
void WinMedia::closeAudio()
{
if (!audioReady) return;
// release memory
delete[] outputBuffer;
// shut down audio
if (audioPort) {
audioPort->Stop();
audioPort->Release();
}
if (audioPrimaryPort) {
audioPrimaryPort->Stop();
audioPrimaryPort->Release();
}
if (audioInterface) audioInterface->Release();
// close audio command queue
if (audioCommandEvent) CloseHandle(audioCommandEvent);
if (audioCommandMutex) CloseHandle(audioCommandMutex);
delete[] audioCommandBuffer;
audioReady = false;
audioInterface = NULL;
audioPrimaryPort = NULL;
audioPort = NULL;
outputBuffer = NULL;
}
bool WinMedia::startAudioThread(
void (*proc)(void*), void* data)
{
if (audioThread || !proc) return false;
threadProc = proc;
threadData = data;
// create thread
DWORD dummy;
audioThread = CreateThread(NULL, 0, audioThreadInit, NULL, 0, &dummy);
return (audioThread != NULL);
}
void WinMedia::stopAudioThread()
{
if (!audioThread) return;
// wait for thread to terminate (don't wait forever, though)
if (WaitForSingleObject(audioThread, 5000) != WAIT_OBJECT_0)
TerminateThread(audioThread, 0);
// free thread
CloseHandle(audioThread);
audioThread = NULL;
}
bool WinMedia::hasAudioThread() const
{
return true;
}
DWORD WINAPI WinMedia::audioThreadInit(void*)
{
// boost the audio thread's priority
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
// call user routine
(*threadProc)(threadData);
return 0;
}
void WinMedia::writeSoundCommand(const void* msg, int len)
{
if (!audioReady) return;
// take ownership of the buffer. if we can't then give up.
if (WaitForSingleObject(audioCommandMutex, INFINITE) != WAIT_OBJECT_0)
return;
// ignore if buffer is overflowing. should expand buffer but if
// overflowing then the consumer is probably dead anyway.
long queueFilled = audioCommandBufferHead - audioCommandBufferTail;
if (queueFilled < 0) queueFilled += audioCommandBufferLen;
if (queueFilled + len < audioCommandBufferLen) {
// add command to queue
const long endLen = audioCommandBufferLen - audioCommandBufferHead;
if (endLen < len) {
memcpy(audioCommandBuffer + audioCommandBufferHead, msg, endLen);
memcpy(audioCommandBuffer, (char*)msg + endLen, len - endLen);
audioCommandBufferHead = len - endLen;
}
else {
memcpy(audioCommandBuffer + audioCommandBufferHead, msg, len);
audioCommandBufferHead += len;
}
// signal non-empty queue
SetEvent(audioCommandEvent);
}
// release hold of buffer
ReleaseMutex(audioCommandMutex);
}
bool WinMedia::readSoundCommand(void* msg, int len)
{
// no event unless signaled non-empty
if (WaitForSingleObject(audioCommandEvent, 0) != WAIT_OBJECT_0)
return false;
// take ownership of the buffer. if we can't then give up after
// resetting the event flag.
if (WaitForSingleObject(audioCommandMutex, INFINITE) != WAIT_OBJECT_0) {
ResetEvent(audioCommandEvent);
return false;
}
// read message
const long endLen = audioCommandBufferLen - audioCommandBufferTail;
if (endLen < len) {
memcpy(msg, audioCommandBuffer + audioCommandBufferTail, endLen);
memcpy((char*)msg + endLen, audioCommandBuffer, len - endLen);
audioCommandBufferTail = len - endLen;
}
else {
memcpy(msg, audioCommandBuffer + audioCommandBufferTail, len);
audioCommandBufferTail += len;
}
// clear event if no more commands pending
if (audioCommandBufferTail == audioCommandBufferHead)
ResetEvent(audioCommandEvent);
// release hold of buffer
ReleaseMutex(audioCommandMutex);
return true;
}
int WinMedia::getAudioOutputRate() const
{
#if defined(HALF_RATE_AUDIO)
return defaultOutputRate / 2;
#else
return defaultOutputRate;
#endif
}
int WinMedia::getAudioBufferSize() const
{
return audioBufferSize / audioNumChannels;
}
int WinMedia::getAudioBufferChunkSize() const
{
return audioBufferChunkSize / audioNumChannels;
}
bool WinMedia::isAudioTooEmpty() const
{
// the write offset returned by GetCurrentPosition() is probably
// useless. the documentation certainly is.
DWORD playOffset, writeOffset;
if (audioPort->GetCurrentPosition(&playOffset, &writeOffset) == DS_OK) {
const int playSamples = playOffset / audioBytesPerSample;
int samplesLeft = audioWritePtr - playSamples;
if (samplesLeft < 0) samplesLeft += audioBufferSize;
return samplesLeft <= audioLowWaterMark;
}
return false;
}
void WinMedia::writeAudioFrames(
const float* samples, int numFrames)
{
// ignore empty buffers
if (numFrames == 0) return;
// first convert the samples to 16 bits signed integers.
// NOTE -- truncate sample buffer if too long. this is not good,
// but we won't send too many samples so we don't care.
int numSamples = audioNumChannels * numFrames;
if (numSamples > audioBufferChunkSize) numSamples = audioBufferChunkSize;
for (int j = 0; j < numSamples; j++) {
if (samples[j] < -32767.0f) outputBuffer[j] = -32767;
else if (samples[j] > 32767.0f) outputBuffer[j] = 32767;
else outputBuffer[j] = (short)samples[j];
}
// lock enough of the buffer for numFrames, starting at the write
// pointer. it's worth noting here that the DirectSound API really
// sucks -- it doesn't abstract away the circularity of the sample
// buffer so we get possibly two pointers to write to, the system
// may capriciously take our sound buffer away so that we have to
// restore it ourselves, the writeOffset returned by
// GetCurrentPosition() is complete fiction so we have to maintain
// it ourselves, and the lock-modify-unlock scheme is totally brain
// dead. *all* this can be fixed with a single function:
// WriteSamples(); it would write just past where we wrote last
// time, automatically restore the buffer, handle the `circularity'
// of the sample buffer, and then DirectSound wouldn't be prone to
// attempts to write at locations that are being played. And,
// surprise!, WriteSamples() is easier to understand, use, and
// implement.
void* ptr1, *ptr2;
DWORD size1, size2;
HRESULT result = audioPort->Lock(audioWritePtr * audioBytesPerSample,
numSamples * audioBytesPerSample,
&ptr1, &size1, &ptr2, &size2, 0);
if (result == DSERR_BUFFERLOST) {
// system took away our buffer. try to get it back.
result = audioPort->Restore();
// if we got it back then try the lock again
if (result == DS_OK)
result = audioPort->Lock(audioWritePtr * audioBytesPerSample,
numSamples * audioBytesPerSample,
&ptr1, &size1, &ptr2, &size2, 0);
}
// if we got the lock the write the samples
if (result == DS_OK) {
memcpy(ptr1, outputBuffer, size1);
if (ptr2)
memcpy(ptr2, outputBuffer + size1 / audioBytesPerSample, size2);
// now unlock the buffer
audioPort->Unlock(ptr1, size1, ptr2, size2);
if (!audioPlaying) {
audioPlaying = true;
audioPort->Play(0, 0, DSBPLAY_LOOPING);
}
// record how many samples written
audioWritePtr += numSamples;
while (audioWritePtr >= audioBufferSize)
audioWritePtr -= audioBufferSize;
}
}
void WinMedia::audioSleep(
bool checkLowWater, double maxTime)
{
// wait for a message on the command queue. do this by waiting
// for the command queue event.
//
// not suprisingly, DirectSound is missing a critical bit of
// functionality -- the ability to sleep until the sound buffer
// has drained below some threshold. we need to simulate that
// behavior here if checkLowWater is true by sleeping briefly
// then checking if the buffer has drained.
//
// never wait longer than maxTime seconds.
if (checkLowWater) {
// start looping
TimeKeeper start = TimeKeeper::getCurrent();
do {
// break if buffer has drained enough
if (isAudioTooEmpty())
break;
// wait. break if command was sent.
if (WaitForSingleObject(audioCommandEvent, 1) == WAIT_OBJECT_0)
break;
} while (maxTime < 0.0 || (TimeKeeper::getCurrent() - start) < maxTime);
}
else {
DWORD timeout = (maxTime >= 0.0) ? (DWORD)(maxTime * 1000.0) : INFINITE;
WaitForSingleObject(audioCommandEvent, timeout);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>include that what has the #def before you check it<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// Jeff Myers 10/13/97 changed direct sound cooperative level to
// exclusive for compatibility with NT.
#include "WinMedia.h"
#include "WinWindow.h"
#include "TimeKeeper.h"
#include "Pack.h"
#include <stdio.h>
#ifdef HAVE_DSOUND_H
static const int defaultOutputRate = 22050;
static const int NumChunks = 4;
void (*WinMedia::threadProc)(void*);
void* WinMedia::threadData;
WinMedia::WinMedia(WinWindow* _window) :
window(_window->getHandle()),
audioReady(false),
audioInterface(NULL),
audioPrimaryPort(NULL),
audioPort(NULL),
outputBuffer(NULL),
audioCommandBuffer(NULL),
audioCommandEvent(NULL),
audioCommandMutex(NULL),
audioThread(NULL)
{
}
WinMedia::~WinMedia()
{
}
bool WinMedia::openAudio()
{
// don't re-initialize
if (audioReady) return false;
// create DirectSound interface pointer
if (DirectSoundCreate(NULL, &audioInterface, NULL) != DS_OK)
return false;
// set cooperative level
if (audioInterface->SetCooperativeLevel(window, DSSCL_EXCLUSIVE) != DS_OK) {
closeAudio();
return false;
}
// create audio command queue
audioCommandBufferHead = 0;
audioCommandBufferTail = 0;
audioCommandBufferLen = 4096;
audioCommandBuffer = new unsigned char[audioCommandBufferLen];
audioCommandEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
audioCommandMutex = CreateMutex(NULL, FALSE, NULL);
// compute desired configuration
audioNumChannels = 2;
audioOutputRate = getAudioOutputRate();
audioBufferChunkSize = (long)(0.1 * audioOutputRate) & ~1;
audioLowWaterMark = (NumChunks - 1) * audioBufferChunkSize;
audioBufferSize = NumChunks * audioBufferChunkSize;
audioBytesPerSample = 2;
audioBytesPerFrame = audioNumChannels * audioBytesPerSample;
// create a `primary sound buffer'; we only need this to force it
// to play at all times (presumably decreasing latency on secondary
// buffers).
DSBUFFERDESC audioBufferParams;
audioBufferParams.dwSize = sizeof(audioBufferParams);
audioBufferParams.dwBufferBytes = 0;
audioBufferParams.dwReserved = 0;
audioBufferParams.lpwfxFormat = NULL;
audioBufferParams.dwFlags = DSBCAPS_PRIMARYBUFFER |
DSBCAPS_CTRLFREQUENCY |
DSBCAPS_GETCURRENTPOSITION2;
HRESULT status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPrimaryPort, NULL);
if (FAILED(status)) {
audioBufferParams.dwFlags = DSBCAPS_PRIMARYBUFFER |
DSBCAPS_GETCURRENTPOSITION2;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPrimaryPort, NULL);
}
if (FAILED(status)) {
audioBufferParams.dwFlags = DSBCAPS_PRIMARYBUFFER;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPrimaryPort, NULL);
}
if (FAILED(status)) {
closeAudio();
return false;
}
// haven't started playing yet
audioPlaying = false;
// have written zero samples so far
audioWritePtr = 0;
// create a `secondary sound buffer'; we need a buffer large enough
// for 3 audioBufferSize chunks. we'll fill it up then wait for it
// to drain below the audioLowWaterMark, then fill it up again.
WAVEFORMATEX waveFormat;
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
waveFormat.nChannels = audioNumChannels;
waveFormat.nSamplesPerSec = audioOutputRate;
waveFormat.nBlockAlign = audioBytesPerFrame;
waveFormat.nAvgBytesPerSec = audioBytesPerFrame * waveFormat.nSamplesPerSec;
waveFormat.wBitsPerSample = 8 * audioBytesPerSample;
waveFormat.cbSize = 0;
audioBufferParams.dwSize = sizeof(audioBufferParams);
audioBufferParams.dwBufferBytes = audioBufferSize * audioBytesPerSample;
audioBufferParams.dwReserved = 0;
audioBufferParams.lpwfxFormat = &waveFormat;
audioBufferParams.dwFlags = DSBCAPS_CTRLFREQUENCY |
DSBCAPS_GETCURRENTPOSITION2;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPort, NULL);
if (FAILED(status)) {
audioBufferParams.dwFlags = DSBCAPS_CTRLFREQUENCY;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPort, NULL);
}
if (FAILED(status)) {
audioBufferParams.dwFlags = DSBCAPS_GETCURRENTPOSITION2;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPort, NULL);
}
if (FAILED(status)) {
audioBufferParams.dwFlags = 0;
status = audioInterface->CreateSoundBuffer(&audioBufferParams,
&audioPort, NULL);
}
if (FAILED(status)) {
closeAudio();
return false;
}
// audioPrimaryPort->Play(0, 0, DSBPLAY_LOOPING);
// make an output buffer
outputBuffer = new short[audioBufferChunkSize];
audioReady = true;
return true;
}
void WinMedia::closeAudio()
{
if (!audioReady) return;
// release memory
delete[] outputBuffer;
// shut down audio
if (audioPort) {
audioPort->Stop();
audioPort->Release();
}
if (audioPrimaryPort) {
audioPrimaryPort->Stop();
audioPrimaryPort->Release();
}
if (audioInterface) audioInterface->Release();
// close audio command queue
if (audioCommandEvent) CloseHandle(audioCommandEvent);
if (audioCommandMutex) CloseHandle(audioCommandMutex);
delete[] audioCommandBuffer;
audioReady = false;
audioInterface = NULL;
audioPrimaryPort = NULL;
audioPort = NULL;
outputBuffer = NULL;
}
bool WinMedia::startAudioThread(
void (*proc)(void*), void* data)
{
if (audioThread || !proc) return false;
threadProc = proc;
threadData = data;
// create thread
DWORD dummy;
audioThread = CreateThread(NULL, 0, audioThreadInit, NULL, 0, &dummy);
return (audioThread != NULL);
}
void WinMedia::stopAudioThread()
{
if (!audioThread) return;
// wait for thread to terminate (don't wait forever, though)
if (WaitForSingleObject(audioThread, 5000) != WAIT_OBJECT_0)
TerminateThread(audioThread, 0);
// free thread
CloseHandle(audioThread);
audioThread = NULL;
}
bool WinMedia::hasAudioThread() const
{
return true;
}
DWORD WINAPI WinMedia::audioThreadInit(void*)
{
// boost the audio thread's priority
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
// call user routine
(*threadProc)(threadData);
return 0;
}
void WinMedia::writeSoundCommand(const void* msg, int len)
{
if (!audioReady) return;
// take ownership of the buffer. if we can't then give up.
if (WaitForSingleObject(audioCommandMutex, INFINITE) != WAIT_OBJECT_0)
return;
// ignore if buffer is overflowing. should expand buffer but if
// overflowing then the consumer is probably dead anyway.
long queueFilled = audioCommandBufferHead - audioCommandBufferTail;
if (queueFilled < 0) queueFilled += audioCommandBufferLen;
if (queueFilled + len < audioCommandBufferLen) {
// add command to queue
const long endLen = audioCommandBufferLen - audioCommandBufferHead;
if (endLen < len) {
memcpy(audioCommandBuffer + audioCommandBufferHead, msg, endLen);
memcpy(audioCommandBuffer, (char*)msg + endLen, len - endLen);
audioCommandBufferHead = len - endLen;
}
else {
memcpy(audioCommandBuffer + audioCommandBufferHead, msg, len);
audioCommandBufferHead += len;
}
// signal non-empty queue
SetEvent(audioCommandEvent);
}
// release hold of buffer
ReleaseMutex(audioCommandMutex);
}
bool WinMedia::readSoundCommand(void* msg, int len)
{
// no event unless signaled non-empty
if (WaitForSingleObject(audioCommandEvent, 0) != WAIT_OBJECT_0)
return false;
// take ownership of the buffer. if we can't then give up after
// resetting the event flag.
if (WaitForSingleObject(audioCommandMutex, INFINITE) != WAIT_OBJECT_0) {
ResetEvent(audioCommandEvent);
return false;
}
// read message
const long endLen = audioCommandBufferLen - audioCommandBufferTail;
if (endLen < len) {
memcpy(msg, audioCommandBuffer + audioCommandBufferTail, endLen);
memcpy((char*)msg + endLen, audioCommandBuffer, len - endLen);
audioCommandBufferTail = len - endLen;
}
else {
memcpy(msg, audioCommandBuffer + audioCommandBufferTail, len);
audioCommandBufferTail += len;
}
// clear event if no more commands pending
if (audioCommandBufferTail == audioCommandBufferHead)
ResetEvent(audioCommandEvent);
// release hold of buffer
ReleaseMutex(audioCommandMutex);
return true;
}
int WinMedia::getAudioOutputRate() const
{
#if defined(HALF_RATE_AUDIO)
return defaultOutputRate / 2;
#else
return defaultOutputRate;
#endif
}
int WinMedia::getAudioBufferSize() const
{
return audioBufferSize / audioNumChannels;
}
int WinMedia::getAudioBufferChunkSize() const
{
return audioBufferChunkSize / audioNumChannels;
}
bool WinMedia::isAudioTooEmpty() const
{
// the write offset returned by GetCurrentPosition() is probably
// useless. the documentation certainly is.
DWORD playOffset, writeOffset;
if (audioPort->GetCurrentPosition(&playOffset, &writeOffset) == DS_OK) {
const int playSamples = playOffset / audioBytesPerSample;
int samplesLeft = audioWritePtr - playSamples;
if (samplesLeft < 0) samplesLeft += audioBufferSize;
return samplesLeft <= audioLowWaterMark;
}
return false;
}
void WinMedia::writeAudioFrames(
const float* samples, int numFrames)
{
// ignore empty buffers
if (numFrames == 0) return;
// first convert the samples to 16 bits signed integers.
// NOTE -- truncate sample buffer if too long. this is not good,
// but we won't send too many samples so we don't care.
int numSamples = audioNumChannels * numFrames;
if (numSamples > audioBufferChunkSize) numSamples = audioBufferChunkSize;
for (int j = 0; j < numSamples; j++) {
if (samples[j] < -32767.0f) outputBuffer[j] = -32767;
else if (samples[j] > 32767.0f) outputBuffer[j] = 32767;
else outputBuffer[j] = (short)samples[j];
}
// lock enough of the buffer for numFrames, starting at the write
// pointer. it's worth noting here that the DirectSound API really
// sucks -- it doesn't abstract away the circularity of the sample
// buffer so we get possibly two pointers to write to, the system
// may capriciously take our sound buffer away so that we have to
// restore it ourselves, the writeOffset returned by
// GetCurrentPosition() is complete fiction so we have to maintain
// it ourselves, and the lock-modify-unlock scheme is totally brain
// dead. *all* this can be fixed with a single function:
// WriteSamples(); it would write just past where we wrote last
// time, automatically restore the buffer, handle the `circularity'
// of the sample buffer, and then DirectSound wouldn't be prone to
// attempts to write at locations that are being played. And,
// surprise!, WriteSamples() is easier to understand, use, and
// implement.
void* ptr1, *ptr2;
DWORD size1, size2;
HRESULT result = audioPort->Lock(audioWritePtr * audioBytesPerSample,
numSamples * audioBytesPerSample,
&ptr1, &size1, &ptr2, &size2, 0);
if (result == DSERR_BUFFERLOST) {
// system took away our buffer. try to get it back.
result = audioPort->Restore();
// if we got it back then try the lock again
if (result == DS_OK)
result = audioPort->Lock(audioWritePtr * audioBytesPerSample,
numSamples * audioBytesPerSample,
&ptr1, &size1, &ptr2, &size2, 0);
}
// if we got the lock the write the samples
if (result == DS_OK) {
memcpy(ptr1, outputBuffer, size1);
if (ptr2)
memcpy(ptr2, outputBuffer + size1 / audioBytesPerSample, size2);
// now unlock the buffer
audioPort->Unlock(ptr1, size1, ptr2, size2);
if (!audioPlaying) {
audioPlaying = true;
audioPort->Play(0, 0, DSBPLAY_LOOPING);
}
// record how many samples written
audioWritePtr += numSamples;
while (audioWritePtr >= audioBufferSize)
audioWritePtr -= audioBufferSize;
}
}
void WinMedia::audioSleep(
bool checkLowWater, double maxTime)
{
// wait for a message on the command queue. do this by waiting
// for the command queue event.
//
// not suprisingly, DirectSound is missing a critical bit of
// functionality -- the ability to sleep until the sound buffer
// has drained below some threshold. we need to simulate that
// behavior here if checkLowWater is true by sleeping briefly
// then checking if the buffer has drained.
//
// never wait longer than maxTime seconds.
if (checkLowWater) {
// start looping
TimeKeeper start = TimeKeeper::getCurrent();
do {
// break if buffer has drained enough
if (isAudioTooEmpty())
break;
// wait. break if command was sent.
if (WaitForSingleObject(audioCommandEvent, 1) == WAIT_OBJECT_0)
break;
} while (maxTime < 0.0 || (TimeKeeper::getCurrent() - start) < maxTime);
}
else {
DWORD timeout = (maxTime >= 0.0) ? (DWORD)(maxTime * 1000.0) : INFINITE;
WaitForSingleObject(audioCommandEvent, timeout);
}
}
#endif
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/* ************************************************************************
* Copyright 2020 Advanced Micro Devices, Inc.
* ************************************************************************ */
#ifndef _ARGUMENT_MODEL_HPP_
#define _ARGUMENT_MODEL_HPP_
#include "hipblas_arguments.hpp"
#include <iostream>
#include <sstream>
// ArgumentModel template has a variadic list of argument enums
template <hipblas_argument... Args>
class ArgumentModel
{
// Whether model has a particular parameter
// TODO: Replace with C++17 fold expression ((Args == param) || ...)
static constexpr bool has(hipblas_argument param)
{
for(auto x : {Args...})
if(x == param)
return true;
return false;
}
public:
void log_perf(std::stringstream& name_line,
std::stringstream& val_line,
const Arguments& arg,
double gpu_us,
double gflops,
double gbytes,
double norm1,
double norm2)
{
constexpr bool has_batch_count = has(e_batch_count);
int batch_count = has_batch_count ? arg.batch_count : 1;
int hot_calls = arg.iters < 1 ? 1 : arg.iters;
// per/us to per/sec *10^6
double hipblas_gflops = gflops * batch_count * hot_calls / gpu_us * 1e6;
double hipblas_GBps = gbytes * batch_count * hot_calls / gpu_us * 1e6;
// append performance fields
name_line << ",hipblas-Gflops,hipblas-GB/s,hipblas-us,";
val_line << ", " << hipblas_gflops << ", " << hipblas_GBps << ", " << gpu_us << ", ";
if(arg.unit_check || arg.norm_check)
{
if(arg.norm_check)
{
name_line << "norm_error_host_ptr,norm_error_device_ptr,";
val_line << norm1 << ", " << norm2 << ", ";
}
}
}
template <typename T>
void log_args(std::ostream& str,
const Arguments& arg,
double gpu_us,
double gflops,
double gpu_bytes = 0,
double norm1 = 0,
double norm2 = 0)
{
std::stringstream name_list;
std::stringstream value_list;
// Output (name, value) pairs to name_list and value_list
auto print = [&, delim = ""](const char* name, auto&& value) mutable {
name_list << delim << name;
value_list << delim << value;
delim = ",";
};
// Args is a parameter pack of type: hipblas_argument...
// The hipblas_argument enum values in Args correspond to the function arguments that
// will be printed by hipblas_test or hipblas_bench. For example, the function:
//
// hipblas_ddot(hipblas_handle handle,
// hipblas_int n,
// const double* x,
// hipblas_int incx,
// const double* y,
// hipblas_int incy,
// double* result);
// will have <Args> = <e_N, e_incx, e_incy>
//
// print is a lambda defined above this comment block
//
// arg is an instance of the Arguments struct
//
// apply is a templated lambda for C++17 and a templated fuctor for C++14
//
// For hipblas_ddot, the following template specialization of apply will be called:
// apply<e_N>(print, arg, T{}), apply<e_incx>(print, arg, T{}),, apply<e_incy>(print, arg, T{})
//
// apply in turn calls print with a string corresponding to the enum, for example "N" and the value of N
//
#if __cplusplus >= 201703L
// C++17
(ArgumentsHelper::apply<Args>(print, arg, T{}), ...);
#else
// C++14. TODO: Remove when C++17 is used
(void)(int[]){(ArgumentsHelper::apply<Args>{}()(print, arg, T{}), 0)...};
#endif
if(arg.timing)
log_perf(name_list, value_list, arg, gpu_us, gflops, gpu_bytes, norm1, norm2);
str << name_list.str() << "\n" << value_list.str() << std::endl;
}
};
#endif
<commit_msg>Divide time by iterations in bench logging (#275)<commit_after>/* ************************************************************************
* Copyright 2020 Advanced Micro Devices, Inc.
* ************************************************************************ */
#ifndef _ARGUMENT_MODEL_HPP_
#define _ARGUMENT_MODEL_HPP_
#include "hipblas_arguments.hpp"
#include <iostream>
#include <sstream>
// ArgumentModel template has a variadic list of argument enums
template <hipblas_argument... Args>
class ArgumentModel
{
// Whether model has a particular parameter
// TODO: Replace with C++17 fold expression ((Args == param) || ...)
static constexpr bool has(hipblas_argument param)
{
for(auto x : {Args...})
if(x == param)
return true;
return false;
}
public:
void log_perf(std::stringstream& name_line,
std::stringstream& val_line,
const Arguments& arg,
double gpu_us,
double gflops,
double gbytes,
double norm1,
double norm2)
{
constexpr bool has_batch_count = has(e_batch_count);
int batch_count = has_batch_count ? arg.batch_count : 1;
int hot_calls = arg.iters < 1 ? 1 : arg.iters;
// per/us to per/sec *10^6
double hipblas_gflops = gflops * batch_count * hot_calls / gpu_us * 1e6;
double hipblas_GBps = gbytes * batch_count * hot_calls / gpu_us * 1e6;
// append performance fields
name_line << ",hipblas-Gflops,hipblas-GB/s,hipblas-us,";
val_line << ", " << hipblas_gflops << ", " << hipblas_GBps << ", " << gpu_us / hot_calls
<< ", ";
if(arg.unit_check || arg.norm_check)
{
if(arg.norm_check)
{
name_line << "norm_error_host_ptr,norm_error_device_ptr,";
val_line << norm1 << ", " << norm2 << ", ";
}
}
}
template <typename T>
void log_args(std::ostream& str,
const Arguments& arg,
double gpu_us,
double gflops,
double gpu_bytes = 0,
double norm1 = 0,
double norm2 = 0)
{
std::stringstream name_list;
std::stringstream value_list;
// Output (name, value) pairs to name_list and value_list
auto print = [&, delim = ""](const char* name, auto&& value) mutable {
name_list << delim << name;
value_list << delim << value;
delim = ",";
};
// Args is a parameter pack of type: hipblas_argument...
// The hipblas_argument enum values in Args correspond to the function arguments that
// will be printed by hipblas_test or hipblas_bench. For example, the function:
//
// hipblas_ddot(hipblas_handle handle,
// hipblas_int n,
// const double* x,
// hipblas_int incx,
// const double* y,
// hipblas_int incy,
// double* result);
// will have <Args> = <e_N, e_incx, e_incy>
//
// print is a lambda defined above this comment block
//
// arg is an instance of the Arguments struct
//
// apply is a templated lambda for C++17 and a templated fuctor for C++14
//
// For hipblas_ddot, the following template specialization of apply will be called:
// apply<e_N>(print, arg, T{}), apply<e_incx>(print, arg, T{}),, apply<e_incy>(print, arg, T{})
//
// apply in turn calls print with a string corresponding to the enum, for example "N" and the value of N
//
#if __cplusplus >= 201703L
// C++17
(ArgumentsHelper::apply<Args>(print, arg, T{}), ...);
#else
// C++14. TODO: Remove when C++17 is used
(void)(int[]){(ArgumentsHelper::apply<Args>{}()(print, arg, T{}), 0)...};
#endif
if(arg.timing)
log_perf(name_list, value_list, arg, gpu_us, gflops, gpu_bytes, norm1, norm2);
str << name_list.str() << "\n" << value_list.str() << std::endl;
}
};
#endif
<|endoftext|>
|
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* Philippe LEDENT <philippe.ledent@etu.univ-grenoble-alpes
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========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========
*.
*/
#define __FFLASFFPACK_SEQUENTIAL
#define ENABLE_ALL_CHECKINGS 1
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iomanip>
#include <iostream>
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "test-utils.h"
#include <givaro/modular.h>
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/ffpack/ffpack.h"
using namespace std;
using namespace FFPACK;
using namespace FFLAS;
using Givaro::Modular;
using Givaro::ModularBalanced;
template<typename Field, class RandIter>
bool check_ftrtri (const Field &F, size_t n, FFLAS_UPLO uplo, FFLAS_DIAG diag, RandIter& Rand){
typedef typename Field::Element Element;
Element * A, * B, * C;
size_t lda = n + (rand() % n );
A = fflas_new(F,n,lda);
B = fflas_new(F,n,lda);
C = fflas_new(F,n,lda);
RandomTriangularMatrix (F, n, n, uplo, diag, true, A, lda, Rand);
fassign (F, n, n, A, lda, B, lda); // copy of A
fassign (F, n, n, A, lda, C, lda); // copy of A
string ss=string((uplo == FflasLower)?"Lower_":"Upper_")+string((diag == FflasUnit)?"Unit":"NonUnit");
cout<<std::left<<"Checking FTRTRI_";
cout.fill('.');
cout.width(30);
cout<<ss;
// << endl;
Timer t; t.clear();
double time=0.0;
t.clear();
t.start();
ftrtri (F, uplo, diag, n, A, lda);
t.stop();
time+=t.usertime();
// B <- A times B
ftrmm(F, FFLAS::FflasRight, uplo, FFLAS::FflasNoTrans, diag, n, n, F.one, A, lda, B, lda);
// Is B the identity matrix ?
bool ok = true;
for(size_t li = 0; (li < n) && ok; li++){
for(size_t co = 0; (co < n) && ok; co++){
ok = ((li == co) && (F.areEqual(B[li*lda+co],F.one))) || (F.areEqual(B[li*lda+co],F.zero));
}
}
if (ok){
cout << "PASSED ("<<time<<")"<<endl;
} else{
//string file = "./mat.sage";
//WriteMatrix(file,F,n,n,C,lda,FFLAS::FflasSageMath);
cout << "FAILED ("<<time<<")"<<endl;
WriteMatrix(std::cout << "\nA" << std::endl, F,n,n,C,lda);
WriteMatrix(std::cout << "\nA^-1" << std::endl, F,n,n,A,lda);
}
fflas_delete(A);
fflas_delete(B);
return ok;
}
template <class Field>
bool run_with_field (Givaro::Integer q, size_t b, size_t n, size_t iters, uint64_t seed){
bool ok = true ;
int nbit=(int)iters;
while (ok && nbit){
//typedef typename Field::Element Element ;
// choose Field
Field* F= chooseField<Field>(q,b);
typename Field::RandIter G(*F,0,seed);
if (F==nullptr)
return true;
cout<<"Checking with ";F->write(cout)<<endl;
ok &= check_ftrtri(*F,n,FflasLower,FflasUnit,G);
ok &= check_ftrtri(*F,n,FflasUpper,FflasUnit,G);
ok &= check_ftrtri(*F,n,FflasLower,FflasNonUnit,G);
ok &= check_ftrtri(*F,n,FflasUpper,FflasNonUnit,G);
nbit--;
delete F;
}
if (!ok)
std::cout << "with seed = "<< seed << std::endl;
return ok;
}
int main(int argc, char** argv)
{
cerr<<setprecision(10);
Givaro::Integer q=-1;
size_t b=0;
size_t n=207;
size_t iters=3;
bool loop=false;
uint64_t seed = time(NULL);
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b },
{ 'n', "-n N", "Set the dimension of the system.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters },
{ 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop },
{ 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed },
END_OF_ARGUMENTS
};
parseArguments(argc,argv,as);
bool ok = true;
do{
ok &= run_with_field<Modular<double> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<double> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<float> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<float> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<int32_t> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<int32_t> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<int64_t> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<int64_t> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<Givaro::Integer> >(q,5,n/4+1,iters,seed);
ok &= run_with_field<Modular<Givaro::Integer> >(q,(b?b:512),n/4+1,iters,seed);
} while (loop && ok);
return !ok ;
}
<commit_msg>adjust size of test<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* Philippe LEDENT <philippe.ledent@etu.univ-grenoble-alpes
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========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========
*.
*/
#define __FFLASFFPACK_SEQUENTIAL
#define ENABLE_ALL_CHECKINGS 1
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iomanip>
#include <iostream>
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/fflas/fflas.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "test-utils.h"
#include <givaro/modular.h>
#include "fflas-ffpack/utils/fflas_io.h"
#include "fflas-ffpack/ffpack/ffpack.h"
using namespace std;
using namespace FFPACK;
using namespace FFLAS;
using Givaro::Modular;
using Givaro::ModularBalanced;
template<typename Field, class RandIter>
bool check_ftrtri (const Field &F, size_t n, FFLAS_UPLO uplo, FFLAS_DIAG diag, RandIter& Rand){
typedef typename Field::Element Element;
Element * A, * B, * C;
size_t lda = n + (rand() % n );
A = fflas_new(F,n,lda);
B = fflas_new(F,n,lda);
C = fflas_new(F,n,lda);
RandomTriangularMatrix (F, n, n, uplo, diag, true, A, lda, Rand);
fassign (F, n, n, A, lda, B, lda); // copy of A
fassign (F, n, n, A, lda, C, lda); // copy of A
string ss=string((uplo == FflasLower)?"Lower_":"Upper_")+string((diag == FflasUnit)?"Unit":"NonUnit");
cout<<std::left<<"Checking FTRTRI_";
cout.fill('.');
cout.width(30);
cout<<ss;
// << endl;
Timer t; t.clear();
double time=0.0;
t.clear();
t.start();
ftrtri (F, uplo, diag, n, A, lda);
t.stop();
time+=t.usertime();
// B <- A times B
ftrmm(F, FFLAS::FflasRight, uplo, FFLAS::FflasNoTrans, diag, n, n, F.one, A, lda, B, lda);
// Is B the identity matrix ?
bool ok = true;
for(size_t li = 0; (li < n) && ok; li++){
for(size_t co = 0; (co < n) && ok; co++){
ok = ((li == co) && (F.areEqual(B[li*lda+co],F.one))) || (F.areEqual(B[li*lda+co],F.zero));
}
}
if (ok){
cout << "PASSED ("<<time<<")"<<endl;
} else{
//string file = "./mat.sage";
//WriteMatrix(file,F,n,n,C,lda,FFLAS::FflasSageMath);
cout << "FAILED ("<<time<<")"<<endl;
WriteMatrix(std::cout << "\nA" << std::endl, F,n,n,C,lda);
WriteMatrix(std::cout << "\nA^-1" << std::endl, F,n,n,A,lda);
}
fflas_delete(A);
fflas_delete(B);
return ok;
}
template <class Field>
bool run_with_field (Givaro::Integer q, size_t b, size_t n, size_t iters, uint64_t seed){
bool ok = true ;
int nbit=(int)iters;
while (ok && nbit){
//typedef typename Field::Element Element ;
// choose Field
Field* F= chooseField<Field>(q,b);
typename Field::RandIter G(*F,0,seed);
if (F==nullptr)
return true;
cout<<"Checking with ";F->write(cout)<<endl;
ok &= check_ftrtri(*F,n,FflasLower,FflasUnit,G);
ok &= check_ftrtri(*F,n,FflasUpper,FflasUnit,G);
ok &= check_ftrtri(*F,n,FflasLower,FflasNonUnit,G);
ok &= check_ftrtri(*F,n,FflasUpper,FflasNonUnit,G);
nbit--;
delete F;
}
if (!ok)
std::cout << "with seed = "<< seed << std::endl;
return ok;
}
int main(int argc, char** argv)
{
cerr<<setprecision(10);
Givaro::Integer q=-1;
size_t b=0;
size_t n=257;
size_t iters=3;
bool loop=false;
uint64_t seed = time(NULL);
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'b', "-b B", "Set the bitsize of the field characteristic.", TYPE_INT , &b },
{ 'n', "-n N", "Set the dimension of the system.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iters },
{ 'l', "-loop Y/N", "run the test in an infinite loop.", TYPE_BOOL , &loop },
{ 's', "-s seed", "Set seed for the random generator", TYPE_INT, &seed },
END_OF_ARGUMENTS
};
parseArguments(argc,argv,as);
bool ok = true;
do{
ok &= run_with_field<Modular<double> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<double> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<float> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<float> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<int32_t> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<int32_t> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<int64_t> >(q,b,n,iters,seed);
ok &= run_with_field<ModularBalanced<int64_t> >(q,b,n,iters,seed);
ok &= run_with_field<Modular<Givaro::Integer> >(q,5,n/6+1,iters,seed);
ok &= run_with_field<Modular<Givaro::Integer> >(q,(b?b:512),n/6+1,iters,seed);
} while (loop && ok);
return !ok ;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TTableHelper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:05:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONNECTIVITY_TABLEHELPER_HXX
#include "connectivity/TTableHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
OTableHelper::OTableHelper( sdbcx::OCollection* _pTables,
const Reference< XConnection >& _xConnection,
sal_Bool _bCase)
:OTable_TYPEDEF(_pTables,_bCase)
,m_xConnection(_xConnection)
{
try
{
m_xMetaData = m_xConnection->getMetaData();
}
catch(const Exception&)
{
}
}
// -------------------------------------------------------------------------
OTableHelper::OTableHelper( sdbcx::OCollection* _pTables,
const Reference< XConnection >& _xConnection,
sal_Bool _bCase,
const ::rtl::OUString& _Name,
const ::rtl::OUString& _Type,
const ::rtl::OUString& _Description ,
const ::rtl::OUString& _SchemaName,
const ::rtl::OUString& _CatalogName
) : OTable_TYPEDEF(_pTables,
_bCase,
_Name,
_Type,
_Description,
_SchemaName,
_CatalogName)
,m_xConnection(_xConnection)
{
try
{
m_xMetaData = m_xConnection->getMetaData();
}
catch(const Exception&)
{
}
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::disposing()
{
OTable_TYPEDEF::disposing();
::osl::MutexGuard aGuard(m_aMutex);
m_xConnection = NULL;
m_xMetaData = NULL;
}
// -------------------------------------------------------------------------
void OTableHelper::refreshColumns()
{
TStringVector aVector;
if(!isNew())
{
Any aCatalog;
if ( m_CatalogName.getLength() )
aCatalog <<= m_CatalogName;
OSL_TRACE( "meta data: %p", getMetaData().get() );
Reference< XResultSet > xResult = getMetaData()->getColumns(
aCatalog,
m_SchemaName,
m_Name,
::rtl::OUString::createFromAscii("%"));
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
while( xResult->next() )
aVector.push_back(xRow->getString(4));
::comphelper::disposeComponent(xResult);
}
}
if(m_pColumns)
m_pColumns->reFill(aVector);
else
m_pColumns = createColumns(aVector);
}
// -------------------------------------------------------------------------
void OTableHelper::refreshPrimaryKeys(std::vector< ::rtl::OUString>& _rKeys)
{
Any aCatalog;
if ( m_CatalogName.getLength() )
aCatalog <<= m_CatalogName;
Reference< XResultSet > xResult = getMetaData()->getPrimaryKeys(aCatalog,m_SchemaName,m_Name);
if(xResult.is())
{
Reference< XRow > xRow(xResult,UNO_QUERY);
if(xResult->next()) // there can be only one primary key
{
::rtl::OUString aPkName = xRow->getString(6);
_rKeys.push_back(aPkName);
}
::comphelper::disposeComponent(xResult);
}
}
// -------------------------------------------------------------------------
void OTableHelper::refreshForgeinKeys(std::vector< ::rtl::OUString>& _rKeys)
{
Any aCatalog;
if ( m_CatalogName.getLength() )
aCatalog <<= m_CatalogName;
Reference< XResultSet > xResult = getMetaData()->getImportedKeys(aCatalog,m_SchemaName,m_Name);
Reference< XRow > xRow(xResult,UNO_QUERY);
if ( xRow.is() )
{
while( xResult->next() )
{
sal_Int32 nKeySeq = xRow->getInt(9);
if ( nKeySeq == 1 )
{ // only append when the sequnce number is 1 to forbid serveral inserting the same key name
::rtl::OUString sFkName = xRow->getString(12);
if ( !xRow->wasNull() && sFkName.getLength() )
_rKeys.push_back(sFkName);
}
}
::comphelper::disposeComponent(xResult);
}
}
// -------------------------------------------------------------------------
void OTableHelper::refreshKeys()
{
TStringVector aVector;
if(!isNew())
{
refreshPrimaryKeys(aVector);
refreshForgeinKeys(aVector);
}
if(m_pKeys)
m_pKeys->reFill(aVector);
else
m_pKeys = createKeys(aVector);
}
// -------------------------------------------------------------------------
void OTableHelper::refreshIndexes()
{
TStringVector aVector;
if(!isNew())
{
// fill indexes
Any aCatalog;
if ( m_CatalogName.getLength() )
aCatalog <<= m_CatalogName;
Reference< XResultSet > xResult = getMetaData()->getIndexInfo(aCatalog,m_SchemaName,m_Name,sal_False,sal_False);
if(xResult.is())
{
Reference< XRow > xRow(xResult,UNO_QUERY);
::rtl::OUString aName;
::rtl::OUString sCatalogSep = getMetaData()->getCatalogSeparator();
::rtl::OUString sPreviousRoundName;
while( xResult->next() )
{
aName = xRow->getString(5);
if(aName.getLength())
aName += sCatalogSep;
aName += xRow->getString(6);
if ( aName.getLength() )
{
// don't insert the name if the last one we inserted was the same
if (sPreviousRoundName != aName)
aVector.push_back(aName);
}
sPreviousRoundName = aName;
}
::comphelper::disposeComponent(xResult);
}
}
if(m_pIndexes)
m_pIndexes->reFill(aVector);
else
m_pIndexes = createIndexes(aVector);
}
// -------------------------------------------------------------------------
// XRename
void SAL_CALL OTableHelper::rename( const ::rtl::OUString& newName ) throw(SQLException, ElementExistException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(
#ifdef GCC
::connectivity::sdbcx::OTableDescriptor_BASE::rBHelper.bDisposed
#else
rBHelper.bDisposed
#endif
);
if(!isNew())
{
::rtl::OUString sSql = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("RENAME "));
if ( m_Type == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")) )
sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" VIEW "));
else
sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" TABLE "));
::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( );
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(getMetaData(),newName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
::rtl::OUString sComposedName;
::dbtools::composeTableName(getMetaData(),m_CatalogName,m_SchemaName,m_Name,sComposedName,sal_True,::dbtools::eInDataManipulation);
sSql += sComposedName
+ ::rtl::OUString::createFromAscii(" TO ");
::dbtools::composeTableName(getMetaData(),sCatalog,sSchema,sTable,sComposedName,sal_True,::dbtools::eInDataManipulation);
sSql += sComposedName;
Reference< XStatement > xStmt = m_xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(sSql);
::comphelper::disposeComponent(xStmt);
}
OTable_TYPEDEF::rename(newName);
}
else
::dbtools::qualifiedNameComponents(getMetaData(),newName,m_CatalogName,m_SchemaName,m_Name,::dbtools::eInTableDefinitions);
}
// -----------------------------------------------------------------------------
Reference< XDatabaseMetaData> OTableHelper::getMetaData() const
{
return m_xMetaData;
}
// -------------------------------------------------------------------------
void SAL_CALL OTableHelper::alterColumnByIndex( sal_Int32 index, const Reference< XPropertySet >& descriptor ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(
#ifdef GCC
::connectivity::sdbcx::OTableDescriptor_BASE::rBHelper.bDisposed
#else
rBHelper.bDisposed
#endif
);
Reference< XPropertySet > xOld;
if(::cppu::extractInterface(xOld,m_pColumns->getByIndex(index)) && xOld.is())
alterColumnByName(getString(xOld->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),descriptor);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTableHelper::getName() throw(RuntimeException)
{
::rtl::OUString sComposedName;
::dbtools::composeTableName(getMetaData(),m_CatalogName,m_SchemaName,m_Name,sComposedName,sal_False,::dbtools::eInDataManipulation);
return sComposedName;
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::acquire() throw()
{
OTable_TYPEDEF::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::release() throw()
{
OTable_TYPEDEF::release();
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS qiq (1.3.104); FILE MERGED 2006/06/27 13:57:06 fs 1.3.104.2: RESYNC: (1.3-1.4); FILE MERGED 2006/05/23 13:24:22 fs 1.3.104.1: some refactoring of compose/quoteTableName and friends, in preparation of #i51143#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TTableHelper.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-07-10 14:19:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONNECTIVITY_TABLEHELPER_HXX
#include "connectivity/TTableHelper.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_KEYTYPE_HPP_
#include <com/sun/star/sdbcx/KeyType.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_
#include <com/sun/star/sdbc/KeyRule.hpp>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
OTableHelper::OTableHelper( sdbcx::OCollection* _pTables,
const Reference< XConnection >& _xConnection,
sal_Bool _bCase)
:OTable_TYPEDEF(_pTables,_bCase)
,m_xConnection(_xConnection)
{
try
{
m_xMetaData = m_xConnection->getMetaData();
}
catch(const Exception&)
{
}
}
// -------------------------------------------------------------------------
OTableHelper::OTableHelper( sdbcx::OCollection* _pTables,
const Reference< XConnection >& _xConnection,
sal_Bool _bCase,
const ::rtl::OUString& _Name,
const ::rtl::OUString& _Type,
const ::rtl::OUString& _Description ,
const ::rtl::OUString& _SchemaName,
const ::rtl::OUString& _CatalogName
) : OTable_TYPEDEF(_pTables,
_bCase,
_Name,
_Type,
_Description,
_SchemaName,
_CatalogName)
,m_xConnection(_xConnection)
{
try
{
m_xMetaData = m_xConnection->getMetaData();
}
catch(const Exception&)
{
}
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::disposing()
{
OTable_TYPEDEF::disposing();
::osl::MutexGuard aGuard(m_aMutex);
m_xConnection = NULL;
m_xMetaData = NULL;
}
// -------------------------------------------------------------------------
void OTableHelper::refreshColumns()
{
TStringVector aVector;
if(!isNew())
{
Any aCatalog;
if ( m_CatalogName.getLength() )
aCatalog <<= m_CatalogName;
OSL_TRACE( "meta data: %p", getMetaData().get() );
Reference< XResultSet > xResult = getMetaData()->getColumns(
aCatalog,
m_SchemaName,
m_Name,
::rtl::OUString::createFromAscii("%"));
if ( xResult.is() )
{
Reference< XRow > xRow(xResult,UNO_QUERY);
while( xResult->next() )
aVector.push_back(xRow->getString(4));
::comphelper::disposeComponent(xResult);
}
}
if(m_pColumns)
m_pColumns->reFill(aVector);
else
m_pColumns = createColumns(aVector);
}
// -------------------------------------------------------------------------
void OTableHelper::refreshPrimaryKeys(std::vector< ::rtl::OUString>& _rKeys)
{
Any aCatalog;
if ( m_CatalogName.getLength() )
aCatalog <<= m_CatalogName;
Reference< XResultSet > xResult = getMetaData()->getPrimaryKeys(aCatalog,m_SchemaName,m_Name);
if(xResult.is())
{
Reference< XRow > xRow(xResult,UNO_QUERY);
if(xResult->next()) // there can be only one primary key
{
::rtl::OUString aPkName = xRow->getString(6);
_rKeys.push_back(aPkName);
}
::comphelper::disposeComponent(xResult);
}
}
// -------------------------------------------------------------------------
void OTableHelper::refreshForgeinKeys(std::vector< ::rtl::OUString>& _rKeys)
{
Any aCatalog;
if ( m_CatalogName.getLength() )
aCatalog <<= m_CatalogName;
Reference< XResultSet > xResult = getMetaData()->getImportedKeys(aCatalog,m_SchemaName,m_Name);
Reference< XRow > xRow(xResult,UNO_QUERY);
if ( xRow.is() )
{
while( xResult->next() )
{
sal_Int32 nKeySeq = xRow->getInt(9);
if ( nKeySeq == 1 )
{ // only append when the sequnce number is 1 to forbid serveral inserting the same key name
::rtl::OUString sFkName = xRow->getString(12);
if ( !xRow->wasNull() && sFkName.getLength() )
_rKeys.push_back(sFkName);
}
}
::comphelper::disposeComponent(xResult);
}
}
// -------------------------------------------------------------------------
void OTableHelper::refreshKeys()
{
TStringVector aVector;
if(!isNew())
{
refreshPrimaryKeys(aVector);
refreshForgeinKeys(aVector);
}
if(m_pKeys)
m_pKeys->reFill(aVector);
else
m_pKeys = createKeys(aVector);
}
// -------------------------------------------------------------------------
void OTableHelper::refreshIndexes()
{
TStringVector aVector;
if(!isNew())
{
// fill indexes
Any aCatalog;
if ( m_CatalogName.getLength() )
aCatalog <<= m_CatalogName;
Reference< XResultSet > xResult = getMetaData()->getIndexInfo(aCatalog,m_SchemaName,m_Name,sal_False,sal_False);
if(xResult.is())
{
Reference< XRow > xRow(xResult,UNO_QUERY);
::rtl::OUString aName;
::rtl::OUString sCatalogSep = getMetaData()->getCatalogSeparator();
::rtl::OUString sPreviousRoundName;
while( xResult->next() )
{
aName = xRow->getString(5);
if(aName.getLength())
aName += sCatalogSep;
aName += xRow->getString(6);
if ( aName.getLength() )
{
// don't insert the name if the last one we inserted was the same
if (sPreviousRoundName != aName)
aVector.push_back(aName);
}
sPreviousRoundName = aName;
}
::comphelper::disposeComponent(xResult);
}
}
if(m_pIndexes)
m_pIndexes->reFill(aVector);
else
m_pIndexes = createIndexes(aVector);
}
// -------------------------------------------------------------------------
// XRename
void SAL_CALL OTableHelper::rename( const ::rtl::OUString& newName ) throw(SQLException, ElementExistException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(
#ifdef GCC
::connectivity::sdbcx::OTableDescriptor_BASE::rBHelper.bDisposed
#else
rBHelper.bDisposed
#endif
);
if(!isNew())
{
::rtl::OUString sSql = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("RENAME "));
if ( m_Type == ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("VIEW")) )
sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" VIEW "));
else
sSql += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" TABLE "));
::rtl::OUString sQuote = getMetaData()->getIdentifierQuoteString( );
::rtl::OUString sCatalog,sSchema,sTable;
::dbtools::qualifiedNameComponents(getMetaData(),newName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
::rtl::OUString sComposedName;
sComposedName = ::dbtools::composeTableName(getMetaData(),m_CatalogName,m_SchemaName,m_Name,sal_True,::dbtools::eInDataManipulation);
sSql += sComposedName
+ ::rtl::OUString::createFromAscii(" TO ");
sComposedName = ::dbtools::composeTableName(getMetaData(),sCatalog,sSchema,sTable,sal_True,::dbtools::eInDataManipulation);
sSql += sComposedName;
Reference< XStatement > xStmt = m_xConnection->createStatement( );
if ( xStmt.is() )
{
xStmt->execute(sSql);
::comphelper::disposeComponent(xStmt);
}
OTable_TYPEDEF::rename(newName);
}
else
::dbtools::qualifiedNameComponents(getMetaData(),newName,m_CatalogName,m_SchemaName,m_Name,::dbtools::eInTableDefinitions);
}
// -----------------------------------------------------------------------------
Reference< XDatabaseMetaData> OTableHelper::getMetaData() const
{
return m_xMetaData;
}
// -------------------------------------------------------------------------
void SAL_CALL OTableHelper::alterColumnByIndex( sal_Int32 index, const Reference< XPropertySet >& descriptor ) throw(SQLException, ::com::sun::star::lang::IndexOutOfBoundsException, RuntimeException)
{
::osl::MutexGuard aGuard(m_aMutex);
checkDisposed(
#ifdef GCC
::connectivity::sdbcx::OTableDescriptor_BASE::rBHelper.bDisposed
#else
rBHelper.bDisposed
#endif
);
Reference< XPropertySet > xOld;
if(::cppu::extractInterface(xOld,m_pColumns->getByIndex(index)) && xOld.is())
alterColumnByName(getString(xOld->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))),descriptor);
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OTableHelper::getName() throw(RuntimeException)
{
::rtl::OUString sComposedName;
sComposedName = ::dbtools::composeTableName(getMetaData(),m_CatalogName,m_SchemaName,m_Name,sal_False,::dbtools::eInDataManipulation);
return sComposedName;
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::acquire() throw()
{
OTable_TYPEDEF::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OTableHelper::release() throw()
{
OTable_TYPEDEF::release();
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* Sponge: hash sha-3 (keccak)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "keccak.H"
#include "action_sponge.H"
#define HASH_SIZE 64
#define RESULT_SIZE 8
#undef TEST /* get faster turn-around time */
#ifdef NO_SYNTH /* TEST */
# define NB_SLICES (4)
# define NB_ROUND (1 << 10)
#else
# ifndef NB_SLICES
# define NB_SLICES (65536) /* for real benchmark */
# endif
# ifndef NB_ROUND
# define NB_ROUND (1 << 16) /* (1 << 24) */ /* for real benchmark */
# endif
#endif
uint64_t sponge (const uint64_t rank)
{
uint64_t magic[8] = {0x0123456789abcdeful,0x13579bdf02468aceul,
0xfdecba9876543210ul,0xeca86420fdb97531ul,
0x571e30cf4b29a86dul,0xd48f0c376e1b29a5ul,
0xc5301e9f6b2ad748ul,0x3894d02e5ba71c6ful};
uint64_t odd[8],even[8],result;
int i,j;
int rnd_nb;
for(i=0;i<RESULT_SIZE;i++) {
#pragma HLS UNROLL
even[i] = magic[i] + rank;
}
//keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE);
keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE);
for(rnd_nb=0;rnd_nb<NB_ROUND;rnd_nb++) {
#pragma HLS UNROLL factor=4
for(j=0;j<4;j++) {
#pragma HLS UNROLL
odd[2*j] ^= ROTL64( even[2*j] , 4*j+1);
odd[2*j+1] = ROTL64( even[2*j+1] + odd[2*j+1], 4*j+3);
}
//keccak((uint8_t*)odd,HASH_SIZE,(uint8_t*)even,HASH_SIZE);
keccak((uint64_t*)odd,HASH_SIZE,(uint64_t*)even,HASH_SIZE);
for(j=0;j<4;j++) {
#pragma HLS UNROLL
even[2*j] += ROTL64( odd[2*j] , 4*j+5);
even[2*j+1] = ROTL64( even[2*j+1] ^ odd[2*j+1], 4*j+7);
}
//keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE);
keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE);
}
result=0;
for(i=0;i<RESULT_SIZE;i++) {
#pragma HLS UNROLL
result += (even[i] ^ odd[i]);
}
return result;
}
/*
* WRITE RESULTS IN MMIO REGS
*
* Always check that ALL Outputs are tied to a value or HLS will generate a
* Action_Output_i and a Action_Output_o registers and address to read results
* will be shifted ...and wrong
* => easy checking in generated files:
* grep 0x184 action_wrapper_ctrl_reg_s_axi.vhd
* this grep should return nothing if no duplication of registers
* (which is expected)
*/
static void write_results(action_output_reg *Action_Output,
action_input_reg *Action_Input,
snapu32_t ReturnCode,
snapu64_t chk_out,
snapu64_t timer_ticks)
{
Action_Output->Retc = ReturnCode;
Action_Output->Data.chk_out = chk_out;
Action_Output->Data.timer_ticks = timer_ticks;
Action_Output->Data.action_version = RELEASE_VERSION;
Action_Output->Reserved = 0;
Action_Output->Data.in = Action_Input->Data.in;
Action_Output->Data.chk_type = Action_Input->Data.chk_type;
Action_Output->Data.chk_in = Action_Input->Data.chk_in;
Action_Output->Data.pe = Action_Input->Data.pe;
Action_Output->Data.nb_pe = Action_Input->Data.nb_pe;
Action_Output->Data.nb_slices = NB_SLICES;
Action_Output->Data.nb_round = NB_ROUND;
}
//-----------------------------------------------------------------------------
//--- MAIN PROGRAM ------------------------------------------------------------
//-----------------------------------------------------------------------------
/**
* Remarks: Using pointers for the din_gmem, ... parameters is requiring to
* to set the depth=... parameter via the pragma below. If missing to do this
* the cosimulation will not work, since the width of the interface cannot
* be determined. Using an array din_gmem[...] works too to fix that.
*/
void action_wrapper(snap_membus_t *din_gmem,
snap_membus_t *dout_gmem,
snap_membus_t *d_ddrmem,
action_input_reg *Action_Input,
action_output_reg *Action_Output)
{
// Host Memory AXI Interface
#pragma HLS INTERFACE m_axi depth=256 port=din_gmem bundle=host_mem
#pragma HLS INTERFACE m_axi depth=256 port=dout_gmem bundle=host_mem
#pragma HLS INTERFACE s_axilite depth=256 port=din_gmem bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite depth=256 port=dout_gmem bundle=ctrl_reg
//DDR memory Interface
#pragma HLS INTERFACE m_axi depth=256 port=d_ddrmem offset=slave bundle=card_mem0
#pragma HLS INTERFACE s_axilite depth=256 port=d_ddrmem bundle=ctrl_reg
// Host Memory AXI Lite Master Interface
#pragma HLS DATA_PACK variable=Action_Input
#pragma HLS INTERFACE s_axilite port=Action_Input offset=0x080 bundle=ctrl_reg
#pragma HLS DATA_PACK variable=Action_Output
#pragma HLS INTERFACE s_axilite port=Action_Output offset=0x104 bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite port=return bundle=ctrl_reg
uint64_t checksum = 0;
uint32_t slice = 0;
uint32_t pe, nb_pe;
uint64_t timer_ticks = 42;
pe = Action_Input->Data.pe;
nb_pe = Action_Input->Data.nb_pe;
/* Intermediate result display */
write_results(Action_Output, Action_Input, RET_CODE_OK,
checksum, timer_ticks);
/* Check if the data alignment matches the expectations */
if (Action_Input->Control.action != SPONGE_ACTION_TYPE) {
write_results(Action_Output, Action_Input, RET_CODE_FAILURE,
checksum, timer_ticks);
return;
}
for (slice = 0; slice < NB_SLICES; slice++) {
#pragma HLS UNROLL factor=4
if (pe == (slice % nb_pe))
checksum ^= sponge(slice);
/* Intermediate result display */
write_results(Action_Output, Action_Input, RET_CODE_OK,
0xfffffffffffffffful, slice);
}
/* Final output register writes */
write_results(Action_Output, Action_Input, RET_CODE_OK,
checksum, timer_ticks);
}
#ifdef NO_SYNTH
/**
* FIXME We need to use action_wrapper from here to get the real thing
* simulated. For now let's take the short path and try without it.
*/
int main(void)
{
uint64_t slice;
uint64_t checksum=0;
short i, rc=0;
typedef struct {
uint32_t pe;
uint32_t nb_pe;
uint64_t checksum;
} arguments_t;
static arguments_t sequence[] = {
{ 0, /*nb_pe =*/ 1, /*expected checksum =*/ 0x948dd5b0109342d4 },
{ 0, /*nb_pe =*/ 2, /*expected checksum =*/ 0x0bca19b17df64085 },
{ 1, /*nb_pe =*/ 2, /*expected checksum =*/ 0x9f47cc016d650251 },
{ 0, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7f13a4a377a2c4fe },
{ 1, /*nb_pe =*/ 4, /*expected checksum =*/ 0xee0710b96b0748fb },
{ 2, /*nb_pe =*/ 4, /*expected checksum =*/ 0x74d9bd120a54847b },
{ 3, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7140dcb806624aaa },
};
for(i=0; i < 7; i++) {
checksum = 0;
for(slice=0;slice<NB_SLICES;slice++) {
if(sequence[i].pe == (slice % sequence[i].nb_pe))
checksum ^= sponge(slice);
}
printf("pe=%d - nb_pe=%d - processed checksum=%016llx ",
sequence[i].pe,
sequence[i].nb_pe,
(unsigned long long) checksum);
if (sequence[i].checksum == checksum) {
printf(" ==> CORRECT\n");
rc |= 0;
}
else {
printf(" ==> ERROR: expected checksum=%016llx\n",
(unsigned long long) sequence[i].checksum);
rc |= 1;
}
}
if (rc != 0)
printf("\n\t Checksums are given with use of -DTEST "
"flag. Please check you have set it!\n\n");
return rc;
}
#endif // end of NO_SYNTH flag
<commit_msg>HLS Sponge: Beautify code<commit_after>/*
* Sponge: hash sha-3 (keccak)
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "keccak.H"
#include "action_sponge.H"
#define HASH_SIZE 64
#define RESULT_SIZE 8
#undef TEST /* get faster turn-around time */
#ifdef NO_SYNTH /* TEST */
# define NB_SLICES (4)
# define NB_ROUND (1 << 10)
#else
# ifndef NB_SLICES
# define NB_SLICES (65536) /* for real benchmark */
# endif
# ifndef NB_ROUND
# define NB_ROUND (1 << 16) /* (1 << 24) */ /* for real benchmark */
# endif
#endif
uint64_t sponge(const uint64_t rank)
{
uint64_t magic[8] = {0x0123456789abcdeful,0x13579bdf02468aceul,
0xfdecba9876543210ul,0xeca86420fdb97531ul,
0x571e30cf4b29a86dul,0xd48f0c376e1b29a5ul,
0xc5301e9f6b2ad748ul,0x3894d02e5ba71c6ful};
uint64_t odd[8],even[8],result;
int i,j;
int rnd_nb;
for(i=0;i<RESULT_SIZE;i++) {
#pragma HLS UNROLL
even[i] = magic[i] + rank;
}
//keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE);
keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE);
for(rnd_nb=0;rnd_nb<NB_ROUND;rnd_nb++) {
#pragma HLS UNROLL factor=4
for(j=0;j<4;j++) {
#pragma HLS UNROLL
odd[2*j] ^= ROTL64( even[2*j] , 4*j+1);
odd[2*j+1] = ROTL64( even[2*j+1] + odd[2*j+1], 4*j+3);
}
//keccak((uint8_t*)odd,HASH_SIZE,(uint8_t*)even,HASH_SIZE);
keccak((uint64_t*)odd,HASH_SIZE,(uint64_t*)even,HASH_SIZE);
for(j=0;j<4;j++) {
#pragma HLS UNROLL
even[2*j] += ROTL64( odd[2*j] , 4*j+5);
even[2*j+1] = ROTL64( even[2*j+1] ^ odd[2*j+1], 4*j+7);
}
//keccak((uint8_t*)even,HASH_SIZE,(uint8_t*)odd,HASH_SIZE);
keccak((uint64_t*)even,HASH_SIZE,(uint64_t*)odd,HASH_SIZE);
}
result=0;
for(i=0;i<RESULT_SIZE;i++) {
#pragma HLS UNROLL
result += (even[i] ^ odd[i]);
}
return result;
}
/*
* WRITE RESULTS IN MMIO REGS
*
* Always check that ALL Outputs are tied to a value or HLS will generate a
* Action_Output_i and a Action_Output_o registers and address to read results
* will be shifted ...and wrong
* => easy checking in generated files:
* grep 0x184 action_wrapper_ctrl_reg_s_axi.vhd
* this grep should return nothing if no duplication of registers
* (which is expected)
*/
static void write_results(action_output_reg *Action_Output,
action_input_reg *Action_Input,
snapu32_t ReturnCode,
snapu64_t chk_out,
snapu64_t timer_ticks)
{
Action_Output->Retc = ReturnCode;
Action_Output->Data.chk_out = chk_out;
Action_Output->Data.timer_ticks = timer_ticks;
Action_Output->Data.action_version = RELEASE_VERSION;
Action_Output->Reserved = 0;
Action_Output->Data.in = Action_Input->Data.in;
Action_Output->Data.chk_type = Action_Input->Data.chk_type;
Action_Output->Data.chk_in = Action_Input->Data.chk_in;
Action_Output->Data.pe = Action_Input->Data.pe;
Action_Output->Data.nb_pe = Action_Input->Data.nb_pe;
Action_Output->Data.nb_slices = NB_SLICES;
Action_Output->Data.nb_round = NB_ROUND;
}
//-----------------------------------------------------------------------------
//--- MAIN PROGRAM ------------------------------------------------------------
//-----------------------------------------------------------------------------
/**
* Remarks: Using pointers for the din_gmem, ... parameters is requiring to
* to set the depth=... parameter via the pragma below. If missing to do this
* the cosimulation will not work, since the width of the interface cannot
* be determined. Using an array din_gmem[...] works too to fix that.
*/
void action_wrapper(snap_membus_t *din_gmem,
snap_membus_t *dout_gmem,
snap_membus_t *d_ddrmem,
action_input_reg *Action_Input,
action_output_reg *Action_Output)
{
// Host Memory AXI Interface
#pragma HLS INTERFACE m_axi depth=256 port=din_gmem bundle=host_mem
#pragma HLS INTERFACE m_axi depth=256 port=dout_gmem bundle=host_mem
#pragma HLS INTERFACE s_axilite depth=256 port=din_gmem bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite depth=256 port=dout_gmem bundle=ctrl_reg
//DDR memory Interface
#pragma HLS INTERFACE m_axi depth=256 port=d_ddrmem offset=slave bundle=card_mem0
#pragma HLS INTERFACE s_axilite depth=256 port=d_ddrmem bundle=ctrl_reg
// Host Memory AXI Lite Master Interface
#pragma HLS DATA_PACK variable=Action_Input
#pragma HLS INTERFACE s_axilite port=Action_Input offset=0x080 bundle=ctrl_reg
#pragma HLS DATA_PACK variable=Action_Output
#pragma HLS INTERFACE s_axilite port=Action_Output offset=0x104 bundle=ctrl_reg
#pragma HLS INTERFACE s_axilite port=return bundle=ctrl_reg
uint64_t checksum = 0;
uint32_t slice = 0;
uint32_t pe, nb_pe;
uint64_t timer_ticks = 42;
pe = Action_Input->Data.pe;
nb_pe = Action_Input->Data.nb_pe;
/* Intermediate result display */
write_results(Action_Output, Action_Input, RET_CODE_OK,
checksum, timer_ticks);
/* Check if the data alignment matches the expectations */
if (Action_Input->Control.action != SPONGE_ACTION_TYPE) {
write_results(Action_Output, Action_Input, RET_CODE_FAILURE,
checksum, timer_ticks);
return;
}
for (slice = 0; slice < NB_SLICES; slice++) {
#pragma HLS UNROLL factor=4
if (pe == (slice % nb_pe))
checksum ^= sponge(slice);
/* Intermediate result display */
write_results(Action_Output, Action_Input, RET_CODE_OK,
0xfffffffffffffffful, slice);
}
/* Final output register writes */
write_results(Action_Output, Action_Input, RET_CODE_OK,
checksum, timer_ticks);
}
#ifdef NO_SYNTH
/**
* FIXME We need to use action_wrapper from here to get the real thing
* simulated. For now let's take the short path and try without it.
*
* Works only for the TEST set of parameters.
*/
int main(void)
{
uint64_t slice;
uint64_t checksum=0;
short i, rc=0;
typedef struct {
uint32_t pe;
uint32_t nb_pe;
uint64_t checksum;
} arguments_t;
static arguments_t sequence[] = {
{ 0, /*nb_pe =*/ 1, /*expected checksum =*/ 0x948dd5b0109342d4 },
{ 0, /*nb_pe =*/ 2, /*expected checksum =*/ 0x0bca19b17df64085 },
{ 1, /*nb_pe =*/ 2, /*expected checksum =*/ 0x9f47cc016d650251 },
{ 0, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7f13a4a377a2c4fe },
{ 1, /*nb_pe =*/ 4, /*expected checksum =*/ 0xee0710b96b0748fb },
{ 2, /*nb_pe =*/ 4, /*expected checksum =*/ 0x74d9bd120a54847b },
{ 3, /*nb_pe =*/ 4, /*expected checksum =*/ 0x7140dcb806624aaa },
};
for(i=0; i < 7; i++) {
checksum = 0;
for(slice=0;slice<NB_SLICES;slice++) {
if(sequence[i].pe == (slice % sequence[i].nb_pe))
checksum ^= sponge(slice);
}
printf("pe=%d - nb_pe=%d - processed checksum=%016llx ",
sequence[i].pe,
sequence[i].nb_pe,
(unsigned long long)checksum);
if (sequence[i].checksum == checksum) {
printf(" ==> CORRECT\n");
rc |= 0;
}
else {
printf(" ==> ERROR: expected checksum=%016llx\n",
(unsigned long long)sequence[i].checksum);
rc |= 1;
}
}
if (rc != 0)
printf("\n\t Checksums are given with use of -DTEST "
"flag. Please check you have set it!\n\n");
return rc;
}
#endif // end of NO_SYNTH flag
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 - 2016, Roland Bock
* 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 "TabSample.h"
#include <cassert>
#include <sqlpp11/alias_provider.h>
#include <sqlpp11/functions.h>
#include <sqlpp11/insert.h>
#include <sqlpp11/mysql/connection.h>
#include <sqlpp11/remove.h>
#include <sqlpp11/select.h>
#include <sqlpp11/transaction.h>
#include <sqlpp11/update.h>
#include <iostream>
#include <vector>
const auto library_raii = sqlpp::mysql::scoped_library_initializer_t{0, nullptr, nullptr};
SQLPP_ALIAS_PROVIDER(left)
namespace sql = sqlpp::mysql;
const auto tab = TabSample{};
void testPreparedStatementResult (sql::connection& db)
{
auto preparedSelectAll = db.prepare(sqlpp::select(count(tab.alpha)).from(tab).unconditionally());
auto preparedUpdateAll = db.prepare(sqlpp::update(tab).set(tab.gamma = false).unconditionally());
uint32_t count = 0;
{
// explicit result scope
// if results are released update should execute without exception
auto result = db(preparedSelectAll);
count = result.front().count;
}
db(preparedUpdateAll);
}
int main()
{
auto config = std::make_shared<sql::connection_config>();
config->user = "root";
config->database = "sqlpp_mysql";
config->debug = true;
try
{
sql::connection db(config);
}
catch (const sqlpp::exception& e)
{
std::cerr << "For testing, you'll need to create a database sqlpp_mysql for user root (no password)" << std::endl;
std::cerr << e.what() << std::endl;
return 1;
}
try
{
sql::connection db(config);
db.execute(R"(DROP TABLE IF EXISTS tab_sample)");
db.execute(R"(CREATE TABLE tab_sample (
alpha bigint(20) AUTO_INCREMENT,
beta varchar(255) DEFAULT NULL,
gamma bool DEFAULT NULL,
PRIMARY KEY (alpha)
))");
db.execute(R"(DROP TABLE IF EXISTS tab_foo)");
db.execute(R"(CREATE TABLE tab_foo (
omega bigint(20) DEFAULT NULL
))");
testPreparedStatementResult(db);
}
catch (const std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
}
<commit_msg>Fix warning<commit_after>/*
* Copyright (c) 2013 - 2016, Roland Bock
* 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 "TabSample.h"
#include <cassert>
#include <sqlpp11/alias_provider.h>
#include <sqlpp11/functions.h>
#include <sqlpp11/insert.h>
#include <sqlpp11/mysql/connection.h>
#include <sqlpp11/remove.h>
#include <sqlpp11/select.h>
#include <sqlpp11/transaction.h>
#include <sqlpp11/update.h>
#include <iostream>
#include <vector>
const auto library_raii = sqlpp::mysql::scoped_library_initializer_t{0, nullptr, nullptr};
SQLPP_ALIAS_PROVIDER(left)
namespace sql = sqlpp::mysql;
const auto tab = TabSample{};
void testPreparedStatementResult (sql::connection& db)
{
auto preparedSelectAll = db.prepare(sqlpp::select(count(tab.alpha)).from(tab).unconditionally());
auto preparedUpdateAll = db.prepare(sqlpp::update(tab).set(tab.gamma = false).unconditionally());
{
// explicit result scope
// if results are released update should execute without exception
auto result = db(preparedSelectAll);
std::ignore = result.front().count;
}
db(preparedUpdateAll);
}
int main()
{
auto config = std::make_shared<sql::connection_config>();
config->user = "root";
config->database = "sqlpp_mysql";
config->debug = true;
try
{
sql::connection db(config);
}
catch (const sqlpp::exception& e)
{
std::cerr << "For testing, you'll need to create a database sqlpp_mysql for user root (no password)" << std::endl;
std::cerr << e.what() << std::endl;
return 1;
}
try
{
sql::connection db(config);
db.execute(R"(DROP TABLE IF EXISTS tab_sample)");
db.execute(R"(CREATE TABLE tab_sample (
alpha bigint(20) AUTO_INCREMENT,
beta varchar(255) DEFAULT NULL,
gamma bool DEFAULT NULL,
PRIMARY KEY (alpha)
))");
db.execute(R"(DROP TABLE IF EXISTS tab_foo)");
db.execute(R"(CREATE TABLE tab_foo (
omega bigint(20) DEFAULT NULL
))");
testPreparedStatementResult(db);
}
catch (const std::exception& e)
{
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
}
<|endoftext|>
|
<commit_before>//===--- RequirementMachineRequests.cpp -----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the main entry points into the requirement machine
// via the request evaluator.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Statistic.h"
using namespace swift;
#define DEBUG_TYPE "Serialization"
STATISTIC(NumLazyRequirementSignaturesLoaded,
"# of lazily-deserialized requirement signatures loaded");
#undef DEBUG_TYPE
ArrayRef<Requirement>
RequirementSignatureRequest::evaluate(Evaluator &evaluator,
ProtocolDecl *proto) const {
ASTContext &ctx = proto->getASTContext();
// First check if we have a deserializable requirement signature.
if (proto->hasLazyRequirementSignature()) {
++NumLazyRequirementSignaturesLoaded;
// FIXME: (transitional) increment the redundant "always-on" counter.
if (ctx.Stats)
++ctx.Stats->getFrontendCounters().NumLazyRequirementSignaturesLoaded;
auto contextData = static_cast<LazyProtocolData *>(
ctx.getOrCreateLazyContextData(proto, nullptr));
SmallVector<Requirement, 8> requirements;
contextData->loader->loadRequirementSignature(
proto, contextData->requirementSignatureData, requirements);
if (requirements.empty())
return None;
return ctx.AllocateCopy(requirements);
}
GenericSignatureBuilder builder(proto->getASTContext());
// Add all of the generic parameters.
for (auto gp : *proto->getGenericParams())
builder.addGenericParameter(gp);
// Add the conformance of 'self' to the protocol.
auto selfType =
proto->getSelfInterfaceType()->castTo<GenericTypeParamType>();
auto requirement =
Requirement(RequirementKind::Conformance, selfType,
proto->getDeclaredInterfaceType());
builder.addRequirement(
requirement,
GenericSignatureBuilder::RequirementSource::forRequirementSignature(
builder, selfType, proto),
nullptr);
auto reqSignature = std::move(builder).computeGenericSignature(
/*allowConcreteGenericParams=*/false,
/*requirementSignatureSelfProto=*/proto);
return reqSignature.getRequirements();
}
<commit_msg>RequirementMachine: Wire up protocol requirement signature minimization<commit_after>//===--- RequirementMachineRequests.cpp -----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the main entry points into the requirement machine
// via the request evaluator.
//
//===----------------------------------------------------------------------===//
#include "RequirementMachine.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Statistic.h"
using namespace swift;
using namespace rewriting;
#define DEBUG_TYPE "Serialization"
STATISTIC(NumLazyRequirementSignaturesLoaded,
"# of lazily-deserialized requirement signatures loaded");
#undef DEBUG_TYPE
ArrayRef<Requirement>
RequirementSignatureRequest::evaluate(Evaluator &evaluator,
ProtocolDecl *proto) const {
ASTContext &ctx = proto->getASTContext();
// First check if we have a deserializable requirement signature.
if (proto->hasLazyRequirementSignature()) {
++NumLazyRequirementSignaturesLoaded;
// FIXME: (transitional) increment the redundant "always-on" counter.
if (ctx.Stats)
++ctx.Stats->getFrontendCounters().NumLazyRequirementSignaturesLoaded;
auto contextData = static_cast<LazyProtocolData *>(
ctx.getOrCreateLazyContextData(proto, nullptr));
SmallVector<Requirement, 8> requirements;
contextData->loader->loadRequirementSignature(
proto, contextData->requirementSignatureData, requirements);
if (requirements.empty())
return None;
return ctx.AllocateCopy(requirements);
}
auto buildViaGSB = [&]() {
GenericSignatureBuilder builder(proto->getASTContext());
// Add all of the generic parameters.
for (auto gp : *proto->getGenericParams())
builder.addGenericParameter(gp);
// Add the conformance of 'self' to the protocol.
auto selfType =
proto->getSelfInterfaceType()->castTo<GenericTypeParamType>();
auto requirement =
Requirement(RequirementKind::Conformance, selfType,
proto->getDeclaredInterfaceType());
builder.addRequirement(
requirement,
GenericSignatureBuilder::RequirementSource::forRequirementSignature(
builder, selfType, proto),
nullptr);
auto reqSignature = std::move(builder).computeGenericSignature(
/*allowConcreteGenericParams=*/false,
/*requirementSignatureSelfProto=*/proto);
return reqSignature.getRequirements();
};
auto buildViaRQM = [&]() {
// We build requirement signatures for all protocols in a strongly connected
// component at the same time.
auto *machine = ctx.getOrCreateRequirementMachine(proto);
auto requirements = machine->computeMinimalRequirements();
bool debug = machine->getDebugOptions().contains(DebugFlags::Minimization);
// The requirement signature for the actual protocol that the result
// was kicked off with.
ArrayRef<Requirement> result;
for (const auto &pair : requirements) {
auto *otherProto = pair.first;
const auto &reqs = pair.second;
// setRequirementSignature() doesn't take ownership of the memory, so
// we have to make a copy of the std::vector temporary.
ArrayRef<Requirement> reqsCopy = ctx.AllocateCopy(reqs);
// Don't call setRequirementSignature() on the original proto; the
// request evaluator will do it for us.
if (otherProto == proto)
result = reqsCopy;
else
const_cast<ProtocolDecl *>(otherProto)->setRequirementSignature(reqsCopy);
// Dump the result if requested.
if (debug) {
llvm::dbgs() << "Protocol " << otherProto->getName() << ": ";
auto sig = GenericSignature::get(
otherProto->getGenericSignature().getGenericParams(),
reqsCopy);
llvm::dbgs() << sig << "\n";
}
}
// Return the result for the specific protocol this request was kicked off on.
return result;
};
switch (ctx.LangOpts.RequirementMachineProtocolSignatures) {
case RequirementMachineMode::Disabled:
return buildViaGSB();
case RequirementMachineMode::Enabled:
return buildViaRQM();
case RequirementMachineMode::Verify:
abort();
}
}
<|endoftext|>
|
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-tsdb/StreamChunk.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/uri.h>
#include <fnord-base/util/Base64.h>
#include <fnord-base/util/binarymessagewriter.h>
#include <fnord-base/wallclock.h>
#include <fnord-msg/MessageEncoder.h>
namespace fnord {
namespace tsdb {
RefPtr<StreamChunk> StreamChunk::create(
const String& streamchunk_key,
const String& stream_key,
RefPtr<StreamProperties> config,
TSDBNodeRef* node) {
return RefPtr<StreamChunk>(
new StreamChunk(
streamchunk_key,
stream_key,
config,
node));
}
RefPtr<StreamChunk> StreamChunk::reopen(
const String& stream_key,
const StreamChunkState& state,
RefPtr<StreamProperties> config,
TSDBNodeRef* node) {
return RefPtr<StreamChunk>(
new StreamChunk(
stream_key,
state,
config,
node));
}
String StreamChunk::streamChunkKeyFor(
const String& stream_key,
DateTime time,
const StreamProperties& properties) {
util::BinaryMessageWriter buf(stream_key.size() + 32);
auto cs = properties.chunk_size.microseconds();
auto ts = (time.unixMicros() / cs) * cs / kMicrosPerSecond;
buf.append(stream_key.data(), stream_key.size());
buf.appendUInt8(27);
buf.appendVarUInt(ts);
return String((char *) buf.data(), buf.size());
}
Vector<String> StreamChunk::streamChunkKeysFor(
const String& stream_key,
DateTime from,
DateTime until,
const StreamProperties& properties) {
auto cs = properties.chunk_size.microseconds();
auto first_chunk = (from.unixMicros() / cs) * cs;
auto last_chunk = (until.unixMicros() / cs) * cs;
Vector<String> res;
for (auto t = first_chunk; t <= last_chunk; t += cs) {
res.emplace_back(streamChunkKeyFor(stream_key, t, properties));
}
return res;
}
StreamChunk::StreamChunk(
const String& streamchunk_key,
const String& stream_key,
RefPtr<StreamProperties> config,
TSDBNodeRef* node) :
stream_key_(stream_key),
key_(streamchunk_key),
config_(config),
node_(node),
records_(
config->schema,
FileUtil::joinPaths(
node->db_path,
StringUtil::stripShell(stream_key) + ".")),
replication_scheduled_(false),
compaction_scheduled_(false),
last_compaction_(0) {
records_.setMaxDatafileSize(config_->max_datafile_size);
}
StreamChunk::StreamChunk(
const String& streamchunk_key,
const StreamChunkState& state,
RefPtr<StreamProperties> config,
TSDBNodeRef* node) :
stream_key_(state.stream_key),
key_(streamchunk_key),
config_(config),
node_(node),
records_(
config->schema,
FileUtil::joinPaths(
node->db_path,
StringUtil::stripShell(state.stream_key) + "."),
state.record_state),
replication_scheduled_(false),
compaction_scheduled_(false),
last_compaction_(0) {
if (records_.commitlogSize() > 0) {
scheduleCompaction();
}
node_->replicationq.insert(this, WallClock::unixMicros());
records_.setMaxDatafileSize(config_->max_datafile_size);
}
void StreamChunk::insertRecord(
uint64_t record_id,
const Buffer& record) {
std::unique_lock<std::mutex> lk(mutex_);
auto old_ver = records_.version();
records_.addRecord(record_id, record);
if (records_.version() != old_ver) {
commitState();
}
scheduleCompaction();
}
void StreamChunk::scheduleCompaction() {
if (compaction_scheduled_) {
return;
}
auto now = WallClock::unixMicros();
auto interval = config_->compaction_interval.microseconds();
auto next = last_compaction_.unixMicros() + interval;
auto compaction_delay = 0;
if (next > now) {
compaction_delay = next - now;
}
node_->compactionq.insert(this, now + compaction_delay);
compaction_scheduled_ = true;
}
void StreamChunk::compact() {
std::unique_lock<std::mutex> lk(mutex_);
compaction_scheduled_ = false;
last_compaction_ = DateTime::now();
lk.unlock();
Set<String> deleted_files;
records_.compact(&deleted_files);
lk.lock();
commitState();
lk.unlock();
node_->replicationq.insert(this, WallClock::unixMicros());
for (const auto& f : deleted_files) {
FileUtil::rm(f);
}
}
void StreamChunk::replicate() {
std::unique_lock<std::mutex> lk(replication_mutex_);
auto cur_offset = records_.numRecords();
auto replicas = node_->replication_scheme->replicasFor(key_);
bool dirty = false;
bool needs_replication = false;
bool has_error = false;
for (const auto& r : replicas) {
auto& off = replicated_offsets_[r.unique_id];
if (off < cur_offset) {
try {
auto num_replicated = replicateTo(r.addr, off);
dirty = true;
off += num_replicated;
if (off < cur_offset) {
needs_replication = true;
}
} catch (const std::exception& e) {
has_error = true;
fnord::logError(
"tsdb.replication",
e,
"Error while replicating stream '$0' to '$1'",
stream_key_,
r.addr);
}
}
}
if (dirty) {
std::unique_lock<std::mutex> lk(mutex_);
commitState();
}
if (needs_replication) {
node_->replicationq.insert(this, WallClock::unixMicros());
} else if (has_error) {
node_->replicationq.insert(
this,
WallClock::unixMicros() + 30 * kMicrosPerSecond);
}
}
uint64_t StreamChunk::replicateTo(const String& addr, uint64_t offset) {
util::BinaryMessageWriter batch;
size_t batch_size = 100;
size_t n = 0;
records_.fetchRecords(offset, batch_size, [this, &batch, &n] (
uint64_t record_id,
const msg::MessageObject& message) {
++n;
Buffer msg_buf;
msg::MessageEncoder::encode(message, *config_->schema, &msg_buf);
batch.appendUInt64(record_id);
batch.appendVarUInt(msg_buf.size());
batch.append(msg_buf.data(), msg_buf.size());
});
String encoded_key;
util::Base64::encode(key_, &encoded_key);
URI uri(StringUtil::format(
"http://$0/tsdb/replicate?stream=$1&chunk=$2",
addr,
URI::urlEncode(stream_key_),
URI::urlEncode(encoded_key)));
http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());
req.addHeader("Host", uri.hostAndPort());
req.addHeader("Content-Type", "application/fnord-msg");
req.addBody(batch.data(), batch.size());
auto res = node_->http->executeRequest(req);
res.wait();
const auto& r = res.get();
if (r.statusCode() != 201) {
RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString());
}
return n;
}
Vector<String> StreamChunk::listFiles() const {
return records_.listDatafiles();
}
void StreamChunk::commitState() {
StreamChunkState state;
state.record_state = records_.getState();
state.stream_key = stream_key_;
util::BinaryMessageWriter buf;
state.encode(&buf);
auto txn = node_->db->startTransaction(false);
txn->update(key_.data(), key_.size(), buf.data(), buf.size());
txn->commit();
}
void StreamChunkState::encode(
util::BinaryMessageWriter* writer) const {
writer->appendLenencString(stream_key);
record_state.encode(writer);
}
void StreamChunkState::decode(util::BinaryMessageReader* reader) {
stream_key = reader->readLenencString();
record_state.decode(reader);
}
}
}
<commit_msg>30s commit interval<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <fnord-tsdb/StreamChunk.h>
#include <fnord-base/io/fileutil.h>
#include <fnord-base/uri.h>
#include <fnord-base/util/Base64.h>
#include <fnord-base/util/binarymessagewriter.h>
#include <fnord-base/wallclock.h>
#include <fnord-msg/MessageEncoder.h>
namespace fnord {
namespace tsdb {
RefPtr<StreamChunk> StreamChunk::create(
const String& streamchunk_key,
const String& stream_key,
RefPtr<StreamProperties> config,
TSDBNodeRef* node) {
return RefPtr<StreamChunk>(
new StreamChunk(
streamchunk_key,
stream_key,
config,
node));
}
RefPtr<StreamChunk> StreamChunk::reopen(
const String& stream_key,
const StreamChunkState& state,
RefPtr<StreamProperties> config,
TSDBNodeRef* node) {
return RefPtr<StreamChunk>(
new StreamChunk(
stream_key,
state,
config,
node));
}
String StreamChunk::streamChunkKeyFor(
const String& stream_key,
DateTime time,
const StreamProperties& properties) {
util::BinaryMessageWriter buf(stream_key.size() + 32);
auto cs = properties.chunk_size.microseconds();
auto ts = (time.unixMicros() / cs) * cs / kMicrosPerSecond;
buf.append(stream_key.data(), stream_key.size());
buf.appendUInt8(27);
buf.appendVarUInt(ts);
return String((char *) buf.data(), buf.size());
}
Vector<String> StreamChunk::streamChunkKeysFor(
const String& stream_key,
DateTime from,
DateTime until,
const StreamProperties& properties) {
auto cs = properties.chunk_size.microseconds();
auto first_chunk = (from.unixMicros() / cs) * cs;
auto last_chunk = (until.unixMicros() / cs) * cs;
Vector<String> res;
for (auto t = first_chunk; t <= last_chunk; t += cs) {
res.emplace_back(streamChunkKeyFor(stream_key, t, properties));
}
return res;
}
StreamChunk::StreamChunk(
const String& streamchunk_key,
const String& stream_key,
RefPtr<StreamProperties> config,
TSDBNodeRef* node) :
stream_key_(stream_key),
key_(streamchunk_key),
config_(config),
node_(node),
records_(
config->schema,
FileUtil::joinPaths(
node->db_path,
StringUtil::stripShell(stream_key) + ".")),
replication_scheduled_(false),
compaction_scheduled_(false),
last_compaction_(0) {
records_.setMaxDatafileSize(config_->max_datafile_size);
}
StreamChunk::StreamChunk(
const String& streamchunk_key,
const StreamChunkState& state,
RefPtr<StreamProperties> config,
TSDBNodeRef* node) :
stream_key_(state.stream_key),
key_(streamchunk_key),
config_(config),
node_(node),
records_(
config->schema,
FileUtil::joinPaths(
node->db_path,
StringUtil::stripShell(state.stream_key) + "."),
state.record_state),
replication_scheduled_(false),
compaction_scheduled_(false),
last_compaction_(0) {
if (records_.commitlogSize() > 0) {
scheduleCompaction();
}
node_->replicationq.insert(this, WallClock::unixMicros());
records_.setMaxDatafileSize(config_->max_datafile_size);
}
void StreamChunk::insertRecord(
uint64_t record_id,
const Buffer& record) {
std::unique_lock<std::mutex> lk(mutex_);
auto old_ver = records_.version();
records_.addRecord(record_id, record);
if (records_.version() != old_ver) {
commitState();
}
scheduleCompaction();
}
void StreamChunk::scheduleCompaction() {
if (compaction_scheduled_) {
return;
}
auto now = WallClock::unixMicros();
auto interval = config_->compaction_interval.microseconds();
auto next = last_compaction_.unixMicros() + interval;
auto compaction_delay = 0;
if (next > now) {
compaction_delay = next - now;
}
node_->compactionq.insert(this, now + compaction_delay);
compaction_scheduled_ = true;
}
void StreamChunk::compact() {
std::unique_lock<std::mutex> lk(mutex_);
compaction_scheduled_ = false;
last_compaction_ = DateTime::now();
lk.unlock();
Set<String> deleted_files;
records_.compact(&deleted_files);
lk.lock();
commitState();
lk.unlock();
node_->replicationq.insert(this, WallClock::unixMicros());
for (const auto& f : deleted_files) {
FileUtil::rm(f);
}
}
void StreamChunk::replicate() {
std::unique_lock<std::mutex> lk(replication_mutex_);
auto cur_offset = records_.numRecords();
auto replicas = node_->replication_scheme->replicasFor(key_);
bool dirty = false;
bool needs_replication = false;
bool has_error = false;
for (const auto& r : replicas) {
auto& off = replicated_offsets_[r.unique_id];
if (off < cur_offset) {
try {
auto num_replicated = replicateTo(r.addr, off);
dirty = true;
off += num_replicated;
if (off < cur_offset) {
needs_replication = true;
}
} catch (const std::exception& e) {
has_error = true;
fnord::logError(
"tsdb.replication",
e,
"Error while replicating stream '$0' to '$1'",
stream_key_,
r.addr);
}
}
}
if (dirty) {
std::unique_lock<std::mutex> lk(mutex_);
commitState();
}
if (needs_replication) {
node_->replicationq.insert(this, WallClock::unixMicros());
} else if (has_error) {
node_->replicationq.insert(
this,
WallClock::unixMicros() + 30 * kMicrosPerSecond);
}
}
uint64_t StreamChunk::replicateTo(const String& addr, uint64_t offset) {
util::BinaryMessageWriter batch;
size_t batch_size = 4096;
size_t n = 0;
records_.fetchRecords(offset, batch_size, [this, &batch, &n] (
uint64_t record_id,
const msg::MessageObject& message) {
++n;
Buffer msg_buf;
msg::MessageEncoder::encode(message, *config_->schema, &msg_buf);
batch.appendUInt64(record_id);
batch.appendVarUInt(msg_buf.size());
batch.append(msg_buf.data(), msg_buf.size());
});
String encoded_key;
util::Base64::encode(key_, &encoded_key);
URI uri(StringUtil::format(
"http://$0/tsdb/replicate?stream=$1&chunk=$2",
addr,
URI::urlEncode(stream_key_),
URI::urlEncode(encoded_key)));
http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());
req.addHeader("Host", uri.hostAndPort());
req.addHeader("Content-Type", "application/fnord-msg");
req.addBody(batch.data(), batch.size());
auto res = node_->http->executeRequest(req);
res.wait();
const auto& r = res.get();
if (r.statusCode() != 201) {
RAISEF(kRuntimeError, "received non-201 response: $0", r.body().toString());
}
return n;
}
Vector<String> StreamChunk::listFiles() const {
return records_.listDatafiles();
}
void StreamChunk::commitState() {
StreamChunkState state;
state.record_state = records_.getState();
state.stream_key = stream_key_;
util::BinaryMessageWriter buf;
state.encode(&buf);
auto txn = node_->db->startTransaction(false);
txn->update(key_.data(), key_.size(), buf.data(), buf.size());
txn->commit();
}
void StreamChunkState::encode(
util::BinaryMessageWriter* writer) const {
writer->appendLenencString(stream_key);
record_state.encode(writer);
}
void StreamChunkState::decode(util::BinaryMessageReader* reader) {
stream_key = reader->readLenencString();
record_state.decode(reader);
}
}
}
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2015, Google 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <node.h>
#include <nan.h>
#include <v8.h>
#include "grpc/grpc.h"
#include "call.h"
#include "channel.h"
#include "event.h"
#include "server.h"
#include "completion_queue_async_worker.h"
#include "credentials.h"
#include "server_credentials.h"
using v8::Handle;
using v8::Value;
using v8::Object;
using v8::Uint32;
using v8::String;
void InitStatusConstants(Handle<Object> exports) {
NanScope();
Handle<Object> status = Object::New();
exports->Set(NanNew("status"), status);
Handle<Value> OK(NanNew<Uint32, uint32_t>(GRPC_STATUS_OK));
status->Set(NanNew("OK"), OK);
Handle<Value> CANCELLED(NanNew<Uint32, uint32_t>(GRPC_STATUS_CANCELLED));
status->Set(NanNew("CANCELLED"), CANCELLED);
Handle<Value> UNKNOWN(NanNew<Uint32, uint32_t>(GRPC_STATUS_UNKNOWN));
status->Set(NanNew("UNKNOWN"), UNKNOWN);
Handle<Value> INVALID_ARGUMENT(
NanNew<Uint32, uint32_t>(GRPC_STATUS_INVALID_ARGUMENT));
status->Set(NanNew("INVALID_ARGUMENT"), INVALID_ARGUMENT);
Handle<Value> DEADLINE_EXCEEDED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_DEADLINE_EXCEEDED));
status->Set(NanNew("DEADLINE_EXCEEDED"), DEADLINE_EXCEEDED);
Handle<Value> NOT_FOUND(NanNew<Uint32, uint32_t>(GRPC_STATUS_NOT_FOUND));
status->Set(NanNew("NOT_FOUND"), NOT_FOUND);
Handle<Value> ALREADY_EXISTS(
NanNew<Uint32, uint32_t>(GRPC_STATUS_ALREADY_EXISTS));
status->Set(NanNew("ALREADY_EXISTS"), ALREADY_EXISTS);
Handle<Value> PERMISSION_DENIED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_PERMISSION_DENIED));
status->Set(NanNew("PERMISSION_DENIED"), PERMISSION_DENIED);
Handle<Value> UNAUTHENTICATED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_UNAUTHENTICATED));
status->Set(NanNew("UNAUTHENTICATED"), UNAUTHENTICATED);
Handle<Value> RESOURCE_EXHAUSTED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_RESOURCE_EXHAUSTED));
status->Set(NanNew("RESOURCE_EXHAUSTED"), RESOURCE_EXHAUSTED);
Handle<Value> FAILED_PRECONDITION(
NanNew<Uint32, uint32_t>(GRPC_STATUS_FAILED_PRECONDITION));
status->Set(NanNew("FAILED_PRECONDITION"), FAILED_PRECONDITION);
Handle<Value> ABORTED(NanNew<Uint32, uint32_t>(GRPC_STATUS_ABORTED));
status->Set(NanNew("ABORTED"), ABORTED);
Handle<Value> OUT_OF_RANGE(
NanNew<Uint32, uint32_t>(GRPC_STATUS_OUT_OF_RANGE));
status->Set(NanNew("OUT_OF_RANGE"), OUT_OF_RANGE);
Handle<Value> UNIMPLEMENTED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_UNIMPLEMENTED));
status->Set(NanNew("UNIMPLEMENTED"), UNIMPLEMENTED);
Handle<Value> INTERNAL(NanNew<Uint32, uint32_t>(GRPC_STATUS_INTERNAL));
status->Set(NanNew("INTERNAL"), INTERNAL);
Handle<Value> UNAVAILABLE(NanNew<Uint32, uint32_t>(GRPC_STATUS_UNAVAILABLE));
status->Set(NanNew("UNAVAILABLE"), UNAVAILABLE);
Handle<Value> DATA_LOSS(NanNew<Uint32, uint32_t>(GRPC_STATUS_DATA_LOSS));
status->Set(NanNew("DATA_LOSS"), DATA_LOSS);
}
void InitCallErrorConstants(Handle<Object> exports) {
NanScope();
Handle<Object> call_error = Object::New();
exports->Set(NanNew("callError"), call_error);
Handle<Value> OK(NanNew<Uint32, uint32_t>(GRPC_CALL_OK));
call_error->Set(NanNew("OK"), OK);
Handle<Value> ERROR(NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR));
call_error->Set(NanNew("ERROR"), ERROR);
Handle<Value> NOT_ON_SERVER(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_ON_SERVER));
call_error->Set(NanNew("NOT_ON_SERVER"), NOT_ON_SERVER);
Handle<Value> NOT_ON_CLIENT(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_ON_CLIENT));
call_error->Set(NanNew("NOT_ON_CLIENT"), NOT_ON_CLIENT);
Handle<Value> ALREADY_INVOKED(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_ALREADY_INVOKED));
call_error->Set(NanNew("ALREADY_INVOKED"), ALREADY_INVOKED);
Handle<Value> NOT_INVOKED(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_INVOKED));
call_error->Set(NanNew("NOT_INVOKED"), NOT_INVOKED);
Handle<Value> ALREADY_FINISHED(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_ALREADY_FINISHED));
call_error->Set(NanNew("ALREADY_FINISHED"), ALREADY_FINISHED);
Handle<Value> TOO_MANY_OPERATIONS(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_TOO_MANY_OPERATIONS));
call_error->Set(NanNew("TOO_MANY_OPERATIONS"), TOO_MANY_OPERATIONS);
Handle<Value> INVALID_FLAGS(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_INVALID_FLAGS));
call_error->Set(NanNew("INVALID_FLAGS"), INVALID_FLAGS);
}
void InitOpTypeConstants(Handle<Object> exports) {
NanScope();
Handle<Object> op_type = Object::New();
exports->Set(NanNew("opType"), op_type);
Handle<Value> SEND_INITIAL_METADATA(
NanNew<Uint32, uint32_t>(GRPC_OP_SEND_INITIAL_METADATA));
op_type->Set(NanNew("SEND_INITIAL_METADATA"), SEND_INITIAL_METADATA);
Handle<Value> SEND_MESSAGE(
NanNew<Uint32, uint32_t>(GRPC_OP_SEND_MESSAGE));
op_type->Set(NanNew("SEND_MESSAGE"), SEND_MESSAGE);
Handle<Value> SEND_CLOSE_FROM_CLIENT(
NanNew<Uint32, uint32_t>(GRPC_OP_SEND_CLOSE_FROM_CLIENT));
op_type->Set(NanNew("SEND_CLOSE_FROM_CLIENT"), SEND_CLOSE_FROM_CLIENT);
Handle<Value> SEND_STATUS_FROM_SERVER(
NanNew<Uint32, uint32_t>(GRPC_OP_SEND_STATUS_FROM_SERVER));
op_type->Set(NanNew("SEND_STATUS_FROM_SERVER"), SEND_STATUS_FROM_SERVER);
Handle<Value> RECV_INITIAL_METADATA(
NanNew<Uint32, uint32_t>(GRPC_OP_RECV_INITIAL_METADATA));
op_type->Set(NanNew("RECV_INITIAL_METADATA"), RECV_INITIAL_METADATA);
Handle<Value> RECV_MESSAGE(
NanNew<Uint32, uint32_t>(GRPC_OP_RECV_MESSAGE));
op_type->Set(NanNew("RECV_MESSAGE"), RECV_MESSAGE);
Handle<Value> RECV_STATUS_ON_CLIENT(
NanNew<Uint32, uint32_t>(GRPC_OP_RECV_STATUS_ON_CLIENT));
op_type->Set(NanNew("RECV_STATUS_ON_CLIENT"), RECV_STATUS_ON_CLIENT);
Handle<Value> RECV_CLOSE_ON_SERVER(
NanNew<Uint32, uint32_t>(GRPC_OP_RECV_CLOSE_ON_SERVER));
op_type->Set(NanNew("RECV_CLOSE_ON_SERVER"), RECV_CLOSE_ON_SERVER);
}
void init(Handle<Object> exports) {
NanScope();
grpc_init();
InitStatusConstants(exports);
InitCallErrorConstants(exports);
InitOpTypeConstants(exports);
grpc::node::Call::Init(exports);
grpc::node::Channel::Init(exports);
grpc::node::Server::Init(exports);
grpc::node::CompletionQueueAsyncWorker::Init(exports);
grpc::node::Credentials::Init(exports);
grpc::node::ServerCredentials::Init(exports);
}
NODE_MODULE(grpc, init)
<commit_msg>Removed reference to non-existent header<commit_after>/*
*
* Copyright 2015, Google 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <node.h>
#include <nan.h>
#include <v8.h>
#include "grpc/grpc.h"
#include "call.h"
#include "channel.h"
#include "server.h"
#include "completion_queue_async_worker.h"
#include "credentials.h"
#include "server_credentials.h"
using v8::Handle;
using v8::Value;
using v8::Object;
using v8::Uint32;
using v8::String;
void InitStatusConstants(Handle<Object> exports) {
NanScope();
Handle<Object> status = Object::New();
exports->Set(NanNew("status"), status);
Handle<Value> OK(NanNew<Uint32, uint32_t>(GRPC_STATUS_OK));
status->Set(NanNew("OK"), OK);
Handle<Value> CANCELLED(NanNew<Uint32, uint32_t>(GRPC_STATUS_CANCELLED));
status->Set(NanNew("CANCELLED"), CANCELLED);
Handle<Value> UNKNOWN(NanNew<Uint32, uint32_t>(GRPC_STATUS_UNKNOWN));
status->Set(NanNew("UNKNOWN"), UNKNOWN);
Handle<Value> INVALID_ARGUMENT(
NanNew<Uint32, uint32_t>(GRPC_STATUS_INVALID_ARGUMENT));
status->Set(NanNew("INVALID_ARGUMENT"), INVALID_ARGUMENT);
Handle<Value> DEADLINE_EXCEEDED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_DEADLINE_EXCEEDED));
status->Set(NanNew("DEADLINE_EXCEEDED"), DEADLINE_EXCEEDED);
Handle<Value> NOT_FOUND(NanNew<Uint32, uint32_t>(GRPC_STATUS_NOT_FOUND));
status->Set(NanNew("NOT_FOUND"), NOT_FOUND);
Handle<Value> ALREADY_EXISTS(
NanNew<Uint32, uint32_t>(GRPC_STATUS_ALREADY_EXISTS));
status->Set(NanNew("ALREADY_EXISTS"), ALREADY_EXISTS);
Handle<Value> PERMISSION_DENIED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_PERMISSION_DENIED));
status->Set(NanNew("PERMISSION_DENIED"), PERMISSION_DENIED);
Handle<Value> UNAUTHENTICATED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_UNAUTHENTICATED));
status->Set(NanNew("UNAUTHENTICATED"), UNAUTHENTICATED);
Handle<Value> RESOURCE_EXHAUSTED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_RESOURCE_EXHAUSTED));
status->Set(NanNew("RESOURCE_EXHAUSTED"), RESOURCE_EXHAUSTED);
Handle<Value> FAILED_PRECONDITION(
NanNew<Uint32, uint32_t>(GRPC_STATUS_FAILED_PRECONDITION));
status->Set(NanNew("FAILED_PRECONDITION"), FAILED_PRECONDITION);
Handle<Value> ABORTED(NanNew<Uint32, uint32_t>(GRPC_STATUS_ABORTED));
status->Set(NanNew("ABORTED"), ABORTED);
Handle<Value> OUT_OF_RANGE(
NanNew<Uint32, uint32_t>(GRPC_STATUS_OUT_OF_RANGE));
status->Set(NanNew("OUT_OF_RANGE"), OUT_OF_RANGE);
Handle<Value> UNIMPLEMENTED(
NanNew<Uint32, uint32_t>(GRPC_STATUS_UNIMPLEMENTED));
status->Set(NanNew("UNIMPLEMENTED"), UNIMPLEMENTED);
Handle<Value> INTERNAL(NanNew<Uint32, uint32_t>(GRPC_STATUS_INTERNAL));
status->Set(NanNew("INTERNAL"), INTERNAL);
Handle<Value> UNAVAILABLE(NanNew<Uint32, uint32_t>(GRPC_STATUS_UNAVAILABLE));
status->Set(NanNew("UNAVAILABLE"), UNAVAILABLE);
Handle<Value> DATA_LOSS(NanNew<Uint32, uint32_t>(GRPC_STATUS_DATA_LOSS));
status->Set(NanNew("DATA_LOSS"), DATA_LOSS);
}
void InitCallErrorConstants(Handle<Object> exports) {
NanScope();
Handle<Object> call_error = Object::New();
exports->Set(NanNew("callError"), call_error);
Handle<Value> OK(NanNew<Uint32, uint32_t>(GRPC_CALL_OK));
call_error->Set(NanNew("OK"), OK);
Handle<Value> ERROR(NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR));
call_error->Set(NanNew("ERROR"), ERROR);
Handle<Value> NOT_ON_SERVER(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_ON_SERVER));
call_error->Set(NanNew("NOT_ON_SERVER"), NOT_ON_SERVER);
Handle<Value> NOT_ON_CLIENT(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_ON_CLIENT));
call_error->Set(NanNew("NOT_ON_CLIENT"), NOT_ON_CLIENT);
Handle<Value> ALREADY_INVOKED(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_ALREADY_INVOKED));
call_error->Set(NanNew("ALREADY_INVOKED"), ALREADY_INVOKED);
Handle<Value> NOT_INVOKED(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_INVOKED));
call_error->Set(NanNew("NOT_INVOKED"), NOT_INVOKED);
Handle<Value> ALREADY_FINISHED(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_ALREADY_FINISHED));
call_error->Set(NanNew("ALREADY_FINISHED"), ALREADY_FINISHED);
Handle<Value> TOO_MANY_OPERATIONS(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_TOO_MANY_OPERATIONS));
call_error->Set(NanNew("TOO_MANY_OPERATIONS"), TOO_MANY_OPERATIONS);
Handle<Value> INVALID_FLAGS(
NanNew<Uint32, uint32_t>(GRPC_CALL_ERROR_INVALID_FLAGS));
call_error->Set(NanNew("INVALID_FLAGS"), INVALID_FLAGS);
}
void InitOpTypeConstants(Handle<Object> exports) {
NanScope();
Handle<Object> op_type = Object::New();
exports->Set(NanNew("opType"), op_type);
Handle<Value> SEND_INITIAL_METADATA(
NanNew<Uint32, uint32_t>(GRPC_OP_SEND_INITIAL_METADATA));
op_type->Set(NanNew("SEND_INITIAL_METADATA"), SEND_INITIAL_METADATA);
Handle<Value> SEND_MESSAGE(
NanNew<Uint32, uint32_t>(GRPC_OP_SEND_MESSAGE));
op_type->Set(NanNew("SEND_MESSAGE"), SEND_MESSAGE);
Handle<Value> SEND_CLOSE_FROM_CLIENT(
NanNew<Uint32, uint32_t>(GRPC_OP_SEND_CLOSE_FROM_CLIENT));
op_type->Set(NanNew("SEND_CLOSE_FROM_CLIENT"), SEND_CLOSE_FROM_CLIENT);
Handle<Value> SEND_STATUS_FROM_SERVER(
NanNew<Uint32, uint32_t>(GRPC_OP_SEND_STATUS_FROM_SERVER));
op_type->Set(NanNew("SEND_STATUS_FROM_SERVER"), SEND_STATUS_FROM_SERVER);
Handle<Value> RECV_INITIAL_METADATA(
NanNew<Uint32, uint32_t>(GRPC_OP_RECV_INITIAL_METADATA));
op_type->Set(NanNew("RECV_INITIAL_METADATA"), RECV_INITIAL_METADATA);
Handle<Value> RECV_MESSAGE(
NanNew<Uint32, uint32_t>(GRPC_OP_RECV_MESSAGE));
op_type->Set(NanNew("RECV_MESSAGE"), RECV_MESSAGE);
Handle<Value> RECV_STATUS_ON_CLIENT(
NanNew<Uint32, uint32_t>(GRPC_OP_RECV_STATUS_ON_CLIENT));
op_type->Set(NanNew("RECV_STATUS_ON_CLIENT"), RECV_STATUS_ON_CLIENT);
Handle<Value> RECV_CLOSE_ON_SERVER(
NanNew<Uint32, uint32_t>(GRPC_OP_RECV_CLOSE_ON_SERVER));
op_type->Set(NanNew("RECV_CLOSE_ON_SERVER"), RECV_CLOSE_ON_SERVER);
}
void init(Handle<Object> exports) {
NanScope();
grpc_init();
InitStatusConstants(exports);
InitCallErrorConstants(exports);
InitOpTypeConstants(exports);
grpc::node::Call::Init(exports);
grpc::node::Channel::Init(exports);
grpc::node::Server::Init(exports);
grpc::node::CompletionQueueAsyncWorker::Init(exports);
grpc::node::Credentials::Init(exports);
grpc::node::ServerCredentials::Init(exports);
}
NODE_MODULE(grpc, init)
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <math.h>
#include <tuple>
#include <vector>
//#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <iostream>
#include <string>
#include <string.h>
#include <iomanip>
#include <locale>
#include <sstream>
#include <omp.h>
#include <algorithm>
#include <tclap/CmdLine.h>
#include "tuple_key_fix.h"
#include "dataload.h"
#define min(a,b) (a<b ? (a) : (b))
#define max(a,b) (a>b ? (a) : (b))
enum ScoringMethods { SVDDecomposition, ALSDecomposition, TransE, TransH, Jaccard, CommonNeighbours, PreferentialAttachment, Random, None };
struct Data
{
double* u;
double* v;
double* sv;
int nsv;
int subnsv;
int numD;
std::vector<int> *neighbours;
double* transE_Entities;
double* transE_Relations;
double* transH_Entities;
double* transH_Hyperplanes;
double* transH_Relations;
Data() {
u = 0;
v = 0;
sv = 0;
nsv = 0;
subnsv = 0;
numD = 0;
neighbours = 0;
transE_Entities = 0;
transE_Relations = 0;
transH_Entities = 0;
transH_Hyperplanes = 0;
transH_Relations = 0;
}
};
float H1(int i,
std::unordered_map<int,int> *occurrences,
int sentenceCount)
{
float N_i = (float)(*occurrences)[i];
float N = (float)sentenceCount;
float score = -(N_i/N) * log(N_i/N) - ((N-N_i)/N) * log((N-N_i)/N);
return score;
}
float H2(int i, int j,
std::unordered_map<std::tuple<int,int>,int> *cooccurrences,
std::unordered_map<int,int> *occurrences,
int sentenceCount)
{
auto key = std::make_tuple ( min(i,j), max(i,j) );
float N_ij = 0.0f;
if (cooccurrences->count(key) > 0)
N_ij = (float)(*cooccurrences)[key];
float N_i = (float)(*occurrences)[i];
float N_j = (float)(*occurrences)[j];
float N = (float)sentenceCount;
if (N_ij==0 || (N_j-N_ij)==0 || (N_i-N_ij)==0 || (N-N_j-N_i)==0)
{
return 0.0;
}
else
{
//print "N_i=%f N_j=%f N_ij=%f N=%f" % (N_i,N_j,N_ij,N)
//score = -(N_ij/N) * log(N_ij/N) - ((N_j-N_ij)/N) * log((N_j-N_ij)/N) - ((N_i-N_ij)/N) * log((N_i-N_ij)/N) - ((N-N_j-N_i)/N) * log((N-N_j-N_i)/N)
float score = -(N_ij/N) * log(N_ij/N);
score += - ((N_j-N_ij)/N) * log((N_j-N_ij)/N);
score += - ((N_i-N_ij)/N) * log((N_i-N_ij)/N);
score += - ((N-N_j-N_i)/N) * log((N-N_j-N_i)/N);
return score;
}
}
float U(int i, int j,
std::unordered_map<std::tuple<int,int>,int> *cooccurrences,
std::unordered_map<int,int> *occurrences,
int sentenceCount)
{
float H_i = H1(i,occurrences,sentenceCount);
float H_j = H1(j,occurrences,sentenceCount);
float H_i_j = H2(i,j,cooccurrences,occurrences,sentenceCount);
float numerator = H_i + H_j - H_i_j;
float denominator = 0.5 * (H_i + H_j);
//printf("H2score=%f numerator=%f denominator=%f\n", H2score,numerator,denominator);
if (denominator == 0)
return 0.0;
else
return numerator/denominator;
}
int main(int argc, char** argv)
{
try
{
TCLAP::CmdLine cmd("Calculates an ANNI curve given occurrence and cooccurrence data", ' ', "1.0");
//TCLAP::ValueArg<int> argDim("","dim","Dimension of the square matrix",true,0,"integer",cmd);
TCLAP::ValueArg<std::string> argCooccurrenceData("","cooccurrenceData","BLAH",true,"","string",cmd);
TCLAP::ValueArg<std::string> argOccurrenceData("","occurrenceData","BLAH",true,"","string",cmd);
TCLAP::ValueArg<int> argSentenceCount("","sentenceCount","BLAH",true,0,"integer",cmd);
TCLAP::ValueArg<std::string> argVectorsToCalculate("","vectorsToCalculate","BLAH",true,"","string",cmd);
TCLAP::ValueArg<std::string> argOutIndex("","outIndexFile","BLAH",true,"","string",cmd);
TCLAP::ValueArg<std::string> argOutVector("","outVectorFile","BLAH",true,"","string",cmd);
//TCLAP::ValueArg<std::string> argOccurrenceData("","occurrenceData","BLAH",true,"","string",cmd);
//TCLAP::ValueArg<std::string> argOutfile("","outFile","Path to file to contain curve points",true,"","string",cmd);
cmd.parse( argc, argv );
int sentenceCount = argSentenceCount.getValue();
const char *outIndexFilename = argOutIndex.getValue().c_str();
const char *outVectorFilename = argOutVector.getValue().c_str();
printf("generateAnniVectors v1.0\n\n");
//int *cooccurrenceData, trainSize;
//loadSymmetricTextCoords(argCooccurrenceData.getValue().c_str(), &trainCoords, &trainSize, dim);
printf("Loading cooccurrence data...\n");
std::unordered_map<std::tuple<int,int>,int> cooccurrences = loadCooccurrences(argCooccurrenceData.getValue().c_str());
printf("%lu cooccurrences loaded\n", cooccurrences.size());
printf("Loading occurrence data...\n");
std::unordered_map<int,int> occurrences = loadOccurrences(argOccurrenceData.getValue().c_str());
printf("%lu occurrences loaded\n", occurrences.size());
printf("Loading vectors to calculate..\n");
std::unordered_set<int> vectorsToCalculate = loadVectorsToCalculate(argVectorsToCalculate.getValue().c_str());
printf("%lu vectors to calculate loaded\n", vectorsToCalculate.size());
printf("Converting sets to arrays for use with OpenMP..\n");
int vectorsToCalculate_array_size = vectorsToCalculate.size();
int *vectorsToCalculate_array = (int*)malloc(vectorsToCalculate_array_size * sizeof(int));
std::copy(std::begin(vectorsToCalculate), std::end(vectorsToCalculate), vectorsToCalculate_array);
std::unordered_set<int> tmpSeen;
for ( auto it = cooccurrences.begin(); it != cooccurrences.end(); ++it )
{
std::tuple<int,int> t = it->first;
tmpSeen.insert(std::get<0>(t));
tmpSeen.insert(std::get<1>(t));
}
int seen_size = tmpSeen.size();
int *seen = (int*)malloc(seen_size * sizeof(int));
{
int i = 0;
for ( auto it = tmpSeen.begin(); it != tmpSeen.end(); ++it )
seen[i++] = *it;
}
printf("Conversion complete\n");
printf("Sorting lists...\n");
std::sort(vectorsToCalculate_array, vectorsToCalculate_array + vectorsToCalculate_array_size);
std::sort(seen, seen + seen_size);
printf("Sorting complete\n");
FILE *outIndexFile = fopen(outIndexFilename, "w");
FILE *outVectorFile = fopen(outVectorFilename, "w");
//const char *outFilename = argOutfile.getValue().c_str();
//for ( auto it1 = vectorsToCalculate.begin(); it1 != vectorsToCalculate.end(); ++it1 )
printf("vectorsToCalculate_array_size=%d\n",vectorsToCalculate_array_size);
printf("seen_size=%d\n",seen_size);
float *allTmpData = (float*)malloc(omp_get_max_threads()*seen_size*sizeof(float));
int complete = 0;
#pragma omp parallel for
for ( int i=0; i<vectorsToCalculate_array_size; i++ )
{
float *tmpData = &allTmpData[seen_size*omp_get_thread_num()];
//int v1 = *it1;
int v1 = vectorsToCalculate_array[i];
//for ( auto it2 = occurrences.begin(); it2 != occurrences.end(); ++it2 )
//fprintf(outIndexFile,"%d\n", v1);
for ( int j=0; j<seen_size; j++ )
{
//int v2 = it2->first;
int v2 = seen[j];
//auto key = std::make_tuple (v1,v2);
float Uvalue = U(v1,v2, &cooccurrences, &occurrences, sentenceCount);
//printf("%d\t%d\t%f\n", v1, v2, Uvalue);
//auto key = std::make_tuple ( min(v1,v2), max(v1,v2) );
//printf("%d\t%d\t%f\t\t%d\t%d\t%d\t%d\n", v1, v2, Uvalue, cooccurrences[key], occurrences[v1], occurrences[v2], sentenceCount);
//fprintf(outVectorFile, "%f ", Uvalue);
tmpData[j] = Uvalue;
}
//fprintf(outVectorFile, "\n");
#pragma omp critical
{
if ((complete%1000)==0)
{
time_t rawtime;
struct tm * timeinfo;
char timebuffer[256];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime(timebuffer, sizeof(timebuffer), "%a %b %d %H:%M:%S %Y", timeinfo);
printf("%s : %d / %d\n", timebuffer, complete, vectorsToCalculate_array_size);
}
fprintf(outIndexFile,"%d\n", v1);
fwrite(tmpData, sizeof(float), seen_size, outVectorFile);
complete++;
}
//break;
}
fclose(outIndexFile);
fclose(outVectorFile);
//free(vectorsToCalculate_array);
//free(seen);
}
catch (TCLAP::ArgException &e) // catch any exceptions
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
return 255;
}
return 0;
}
<commit_msg>Update to anni vector maths<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <math.h>
#include <tuple>
#include <vector>
//#include <map>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <iostream>
#include <string>
#include <string.h>
#include <iomanip>
#include <locale>
#include <sstream>
#include <omp.h>
#include <algorithm>
#include <tclap/CmdLine.h>
#include "tuple_key_fix.h"
#include "dataload.h"
#define min(a,b) (a<b ? (a) : (b))
#define max(a,b) (a>b ? (a) : (b))
enum ScoringMethods { SVDDecomposition, ALSDecomposition, TransE, TransH, Jaccard, CommonNeighbours, PreferentialAttachment, Random, None };
struct Data
{
double* u;
double* v;
double* sv;
int nsv;
int subnsv;
int numD;
std::vector<int> *neighbours;
double* transE_Entities;
double* transE_Relations;
double* transH_Entities;
double* transH_Hyperplanes;
double* transH_Relations;
Data() {
u = 0;
v = 0;
sv = 0;
nsv = 0;
subnsv = 0;
numD = 0;
neighbours = 0;
transE_Entities = 0;
transE_Relations = 0;
transH_Entities = 0;
transH_Hyperplanes = 0;
transH_Relations = 0;
}
};
float H1(int i,
std::unordered_map<int,int> *occurrences,
int sentenceCount)
{
float N_i = (float)(*occurrences)[i];
float N = (float)sentenceCount;
float score = -(N_i/N) * log(N_i/N) - ((N-N_i)/N) * log((N-N_i)/N);
return score;
}
float H2(int i, int j,
std::unordered_map<std::tuple<int,int>,int> *cooccurrences,
std::unordered_map<int,int> *occurrences,
int sentenceCount)
{
auto key = std::make_tuple ( min(i,j), max(i,j) );
float N_ij = 0.0f;
if (cooccurrences->count(key) > 0)
N_ij = (float)(*cooccurrences)[key];
float N_i = (float)(*occurrences)[i];
float N_j = (float)(*occurrences)[j];
float N = (float)sentenceCount;
int useOld = 0;
if (useOld == 1)
{
if (N_ij==0 || (N_j-N_ij)==0 || (N_i-N_ij)==0 || (N-N_j-N_i)==0)
{
return 0.0;
}
else
{
float score = -(N_ij/N) * log(N_ij/N);
score += - ((N_j-N_ij)/N) * log((N_j-N_ij)/N);
score += - ((N_i-N_ij)/N) * log((N_i-N_ij)/N);
score += - ((N-N_j-N_i)/N) * log((N-N_j-N_i)/N);
return score;
}
}
else
{
float score = 0.0;
if (N_ij != 0)
score += -(N_ij/N) * log(N_ij/N);
if ((N_j-N_ij) != 0)
score += - ((N_j-N_ij)/N) * log((N_j-N_ij)/N);
if ((N_i-N_ij) != 0)
score += - ((N_i-N_ij)/N) * log((N_i-N_ij)/N);
if ((N-N_j-N_i) != 0)
score += - ((N-N_j-N_i)/N) * log((N-N_j-N_i)/N);
return score;
}
}
float U(int i, int j,
std::unordered_map<std::tuple<int,int>,int> *cooccurrences,
std::unordered_map<int,int> *occurrences,
int sentenceCount)
{
float H_i = H1(i,occurrences,sentenceCount);
float H_j = H1(j,occurrences,sentenceCount);
float H_i_j = H2(i,j,cooccurrences,occurrences,sentenceCount);
float numerator = H_i + H_j - H_i_j;
float denominator = 0.5 * (H_i + H_j);
//if (i<10 and j<10)
// printf("DEBUG\t%d\t%d\t%f\t%f\t%f\t%f\t%f\t%f\n",i,j,H_i,H_j,H_i_j,numerator,denominator,numerator/denominator);
//printf("H2score=%f numerator=%f denominator=%f\n", H2score,numerator,denominator);
if (denominator == 0)
return 0.0;
else
return numerator/denominator;
}
int main(int argc, char** argv)
{
try
{
TCLAP::CmdLine cmd("Calculates an ANNI curve given occurrence and cooccurrence data", ' ', "1.0");
//TCLAP::ValueArg<int> argDim("","dim","Dimension of the square matrix",true,0,"integer",cmd);
TCLAP::ValueArg<std::string> argCooccurrenceData("","cooccurrenceData","BLAH",true,"","string",cmd);
TCLAP::ValueArg<std::string> argOccurrenceData("","occurrenceData","BLAH",true,"","string",cmd);
TCLAP::ValueArg<int> argSentenceCount("","sentenceCount","BLAH",true,0,"integer",cmd);
TCLAP::ValueArg<std::string> argVectorsToCalculate("","vectorsToCalculate","BLAH",true,"","string",cmd);
TCLAP::ValueArg<std::string> argOutIndex("","outIndexFile","BLAH",true,"","string",cmd);
TCLAP::ValueArg<std::string> argOutVector("","outVectorFile","BLAH",true,"","string",cmd);
//TCLAP::ValueArg<std::string> argOccurrenceData("","occurrenceData","BLAH",true,"","string",cmd);
//TCLAP::ValueArg<std::string> argOutfile("","outFile","Path to file to contain curve points",true,"","string",cmd);
cmd.parse( argc, argv );
int sentenceCount = argSentenceCount.getValue();
const char *outIndexFilename = argOutIndex.getValue().c_str();
const char *outVectorFilename = argOutVector.getValue().c_str();
printf("generateAnniVectors v1.0\n\n");
//int *cooccurrenceData, trainSize;
//loadSymmetricTextCoords(argCooccurrenceData.getValue().c_str(), &trainCoords, &trainSize, dim);
printf("Loading cooccurrence data...\n");
std::unordered_map<std::tuple<int,int>,int> cooccurrences = loadCooccurrences(argCooccurrenceData.getValue().c_str());
printf("%lu cooccurrences loaded\n", cooccurrences.size());
printf("Loading occurrence data...\n");
std::unordered_map<int,int> occurrences = loadOccurrences(argOccurrenceData.getValue().c_str());
printf("%lu occurrences loaded\n", occurrences.size());
printf("Loading vectors to calculate..\n");
std::unordered_set<int> vectorsToCalculate = loadVectorsToCalculate(argVectorsToCalculate.getValue().c_str());
printf("%lu vectors to calculate loaded\n", vectorsToCalculate.size());
printf("Converting sets to arrays for use with OpenMP..\n");
int vectorsToCalculate_array_size = vectorsToCalculate.size();
int *vectorsToCalculate_array = (int*)malloc(vectorsToCalculate_array_size * sizeof(int));
std::copy(std::begin(vectorsToCalculate), std::end(vectorsToCalculate), vectorsToCalculate_array);
std::unordered_set<int> tmpSeen;
for ( auto it = cooccurrences.begin(); it != cooccurrences.end(); ++it )
{
std::tuple<int,int> t = it->first;
tmpSeen.insert(std::get<0>(t));
tmpSeen.insert(std::get<1>(t));
}
int seen_size = tmpSeen.size();
int *seen = (int*)malloc(seen_size * sizeof(int));
{
int i = 0;
for ( auto it = tmpSeen.begin(); it != tmpSeen.end(); ++it )
seen[i++] = *it;
}
printf("Conversion complete\n");
printf("Sorting lists...\n");
std::sort(vectorsToCalculate_array, vectorsToCalculate_array + vectorsToCalculate_array_size);
std::sort(seen, seen + seen_size);
printf("Sorting complete\n");
FILE *outIndexFile = fopen(outIndexFilename, "w");
FILE *outVectorFile = fopen(outVectorFilename, "w");
//const char *outFilename = argOutfile.getValue().c_str();
//for ( auto it1 = vectorsToCalculate.begin(); it1 != vectorsToCalculate.end(); ++it1 )
printf("vectorsToCalculate_array_size=%d\n",vectorsToCalculate_array_size);
printf("seen_size=%d\n",seen_size);
float *allTmpData = (float*)malloc(omp_get_max_threads()*seen_size*sizeof(float));
int complete = 0;
#pragma omp parallel for
for ( int i=0; i<vectorsToCalculate_array_size; i++ )
{
float *tmpData = &allTmpData[seen_size*omp_get_thread_num()];
//int v1 = *it1;
int v1 = vectorsToCalculate_array[i];
//for ( auto it2 = occurrences.begin(); it2 != occurrences.end(); ++it2 )
//fprintf(outIndexFile,"%d\n", v1);
for ( int j=0; j<seen_size; j++ )
{
//int v2 = it2->first;
int v2 = seen[j];
//auto key = std::make_tuple (v1,v2);
float Uvalue = U(v1,v2, &cooccurrences, &occurrences, sentenceCount);
//printf("%d\t%d\t%f\n", v1, v2, Uvalue);
//auto key = std::make_tuple ( min(v1,v2), max(v1,v2) );
//printf("%d\t%d\t%f\t\t%d\t%d\t%d\t%d\n", v1, v2, Uvalue, cooccurrences[key], occurrences[v1], occurrences[v2], sentenceCount);
//fprintf(outVectorFile, "%f ", Uvalue);
tmpData[j] = Uvalue;
}
//fprintf(outVectorFile, "\n");
#pragma omp critical
{
if ((complete%1000)==0)
{
time_t rawtime;
struct tm * timeinfo;
char timebuffer[256];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime(timebuffer, sizeof(timebuffer), "%a %b %d %H:%M:%S %Y", timeinfo);
printf("%s : %d / %d\n", timebuffer, complete, vectorsToCalculate_array_size);
}
fprintf(outIndexFile,"%d\n", v1);
fwrite(tmpData, sizeof(float), seen_size, outVectorFile);
complete++;
}
//break;
}
fclose(outIndexFile);
fclose(outVectorFile);
//free(vectorsToCalculate_array);
//free(seen);
}
catch (TCLAP::ArgException &e) // catch any exceptions
{
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
return 255;
}
return 0;
}
<|endoftext|>
|
<commit_before>
#undef NDEBUG /* ensure tests always assert. */
#include "upb_table.h"
#include "upb_string.h"
#include "test_util.h"
#include <assert.h>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <ext/hash_map>
#include <sys/resource.h>
#include <iostream>
bool benchmark = false;
using std::string;
using std::vector;
typedef struct {
upb_inttable_entry e;
uint32_t value; /* key*2 */
} inttable_entry;
typedef struct {
upb_strtable_entry e;
int32_t value; /* ASCII Value of first letter */
} strtable_entry;
double get_usertime()
{
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
return usage.ru_utime.tv_sec + (usage.ru_utime.tv_usec/1000000.0);
}
/* num_entries must be a power of 2. */
void test_strtable(const vector<string>& keys, uint32_t num_to_insert)
{
/* Initialize structures. */
upb_strtable table;
std::map<string, int32_t> m;
upb_strtable_init(&table, 0, sizeof(strtable_entry));
std::set<string> all;
for(size_t i = 0; i < num_to_insert; i++) {
const string& key = keys[i];
all.insert(key);
strtable_entry e;
e.value = key[0];
upb_string *str = upb_strduplen(key.c_str(), key.size());
e.e.key = str;
upb_strtable_insert(&table, &e.e);
upb_string_unref(str); // The table still owns a ref.
m[key] = key[0];
}
/* Test correctness. */
for(uint32_t i = 0; i < keys.size(); i++) {
const string& key = keys[i];
upb_string *str = upb_strduplen(key.c_str(), key.size());
strtable_entry *e = (strtable_entry*)upb_strtable_lookup(&table, str);
if(m.find(key) != m.end()) { /* Assume map implementation is correct. */
assert(e);
assert(upb_streql(e->e.key, str));
assert(e->value == key[0]);
assert(m[key] == key[0]);
} else {
assert(e == NULL);
}
upb_string_unref(str);
}
strtable_entry *e;
for(e = (strtable_entry*)upb_strtable_begin(&table); e;
e = (strtable_entry*)upb_strtable_next(&table, &e->e)) {
string tmp(upb_string_getrobuf(e->e.key), upb_string_len(e->e.key));
std::set<string>::iterator i = all.find(tmp);
assert(i != all.end());
all.erase(i);
}
assert(all.empty());
upb_strtable_free(&table);
}
/* num_entries must be a power of 2. */
void test_inttable(int32_t *keys, size_t num_entries)
{
/* Initialize structures. */
upb_inttable table;
uint32_t largest_key = 0;
std::map<uint32_t, uint32_t> m;
__gnu_cxx::hash_map<uint32_t, uint32_t> hm;
upb_inttable_init(&table, num_entries, sizeof(inttable_entry));
for(size_t i = 0; i < num_entries; i++) {
int32_t key = keys[i];
largest_key = UPB_MAX((int32_t)largest_key, key);
inttable_entry e;
e.e.key = key;
e.value = key*2;
upb_inttable_insert(&table, &e.e);
m[key] = key*2;
hm[key] = key*2;
}
/* Test correctness. */
for(uint32_t i = 1; i <= largest_key; i++) {
inttable_entry *e = (inttable_entry*)upb_inttable_lookup(
&table, i);
if(m.find(i) != m.end()) { /* Assume map implementation is correct. */
assert(e);
assert(e->e.key == i);
assert(e->value == i*2);
assert(m[i] == i*2);
assert(hm[i] == i*2);
} else {
assert(e == NULL);
}
}
if(!benchmark) {
upb_inttable_free(&table);
return;
}
/* Test performance. We only test lookups for keys that are known to exist. */
uintptr_t x = 0;
const unsigned int iterations = 0xFFFFFF;
const int32_t mask = num_entries - 1;
printf("Measuring sequential loop overhead...");
fflush(stdout);
double before = get_usertime();
for(unsigned int i = 0; i < iterations; i++) {
int32_t key = keys[i & mask];
x += key;
}
double seq_overhead = get_usertime() - before;
printf("%0.3f seconds for %d iterations\n", seq_overhead, iterations);
printf("Measuring random loop overhead...");
rand();
fflush(stdout);
before = get_usertime();
for(unsigned int i = 0; i < iterations; i++) {
int32_t key = keys[rand() & mask];
x += key;
}
double rand_overhead = get_usertime() - before;
printf("%0.3f seconds for %d iterations\n", rand_overhead, iterations);
printf("upb_table(seq): ");
fflush(stdout);
before = get_usertime();
for(unsigned int i = 0; i < iterations; i++) {
int32_t key = keys[i & mask];
inttable_entry *e = (inttable_entry*)upb_inttable_lookup(&table, key);
x += (uintptr_t)e;
}
double total = get_usertime() - before;
double without_overhead = total - seq_overhead;
printf("%0.3f seconds (%0.3f - %0.3f overhead) for %d iterations. %s/s\n", without_overhead, total, seq_overhead, iterations, eng(iterations/without_overhead, 3, false));
printf("upb_table(rand): ");
fflush(stdout);
before = get_usertime();
for(unsigned int i = 0; i < iterations; i++) {
int32_t key = keys[rand() & mask];
inttable_entry *e = (inttable_entry*)upb_inttable_lookup(&table, key);
x += (uintptr_t)e;
}
total = get_usertime() - before;
without_overhead = total - rand_overhead;
printf("%0.3f seconds (%0.3f - %0.3f overhead) for %d iterations. %s/s\n", without_overhead, total, rand_overhead, iterations, eng(iterations/without_overhead, 3, false));
printf("map(seq): ");
fflush(stdout);
before = get_usertime();
for(unsigned int i = 0; i < iterations; i++) {
int32_t key = keys[i & mask];
x += m[key];
}
total = get_usertime() - before;
without_overhead = total - seq_overhead;
printf("%0.3f seconds (%0.3f - %0.3f overhead) for %d iterations. %s/s\n", without_overhead, total, seq_overhead, iterations, eng(iterations/without_overhead, 3, false));
printf("map(rand): ");
fflush(stdout);
before = get_usertime();
for(unsigned int i = 0; i < iterations; i++) {
int32_t key = keys[rand() & mask];
x += m[key];
}
total = get_usertime() - before;
without_overhead = total - rand_overhead;
printf("%0.3f seconds (%0.3f - %0.3f overhead) for %d iterations. %s/s\n", without_overhead, total, rand_overhead, iterations, eng(iterations/without_overhead, 3, false));
printf("hash_map(seq): ");
fflush(stdout);
before = get_usertime();
for(unsigned int i = 0; i < iterations; i++) {
int32_t key = keys[i & mask];
x += hm[key];
}
total = get_usertime() - before;
without_overhead = total - seq_overhead;
printf("%0.3f seconds (%0.3f - %0.3f overhead) for %d iterations. %s/s\n", without_overhead, total, seq_overhead, iterations, eng(iterations/without_overhead, 3, false));
printf("hash_map(rand): ");
fflush(stdout);
before = get_usertime();
for(unsigned int i = 0; i < iterations; i++) {
int32_t key = keys[rand() & mask];
x += hm[key];
}
total = get_usertime() - before;
without_overhead = total - rand_overhead;
printf("%0.3f seconds (%0.3f - %0.3f overhead) for %d iterations. %s/s\n\n", without_overhead, total, rand_overhead, iterations, eng(iterations/without_overhead, 3, false));
upb_inttable_free(&table);
}
int32_t *get_contiguous_keys(int32_t num)
{
int32_t *buf = new int32_t[num];
for(int32_t i = 0; i < num; i++)
buf[i] = i+1;
return buf;
}
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--benchmark") == 0) benchmark = true;
}
vector<string> keys;
keys.push_back("google.protobuf.FileDescriptorSet");
keys.push_back("google.protobuf.FileDescriptorProto");
keys.push_back("google.protobuf.DescriptorProto");
keys.push_back("google.protobuf.DescriptorProto.ExtensionRange");
keys.push_back("google.protobuf.FieldDescriptorProto");
keys.push_back("google.protobuf.EnumDescriptorProto");
keys.push_back("google.protobuf.EnumValueDescriptorProto");
keys.push_back("google.protobuf.ServiceDescriptorProto");
keys.push_back("google.protobuf.MethodDescriptorProto");
keys.push_back("google.protobuf.FileOptions");
keys.push_back("google.protobuf.MessageOptions");
keys.push_back("google.protobuf.FieldOptions");
keys.push_back("google.protobuf.EnumOptions");
keys.push_back("google.protobuf.EnumValueOptions");
keys.push_back("google.protobuf.ServiceOptions");
keys.push_back("google.protobuf.MethodOptions");
keys.push_back("google.protobuf.UninterpretedOption");
keys.push_back("google.protobuf.UninterpretedOption.NamePart");
test_strtable(keys, 18);
int32_t *keys1 = get_contiguous_keys(8);
printf("Contiguous 1-8 ====\n");
test_inttable(keys1, 8);
delete[] keys1;
int32_t *keys2 = get_contiguous_keys(64);
printf("Contiguous 1-64 ====\n");
test_inttable(keys2, 64);
delete[] keys2;
int32_t *keys3 = get_contiguous_keys(512);
printf("Contiguous 1-512 ====\n");
test_inttable(keys3, 512);
delete[] keys3;
int32_t *keys4 = new int32_t[64];
for(int32_t i = 0; i < 64; i++) {
if(i < 32)
keys4[i] = i+1;
else
keys4[i] = 10101+i;
}
printf("1-32 and 10133-10164 ====\n");
test_inttable(keys4, 64);
delete[] keys4;
}
<commit_msg>Improved table benchmark accuracy and output formatting.<commit_after>
#undef NDEBUG /* ensure tests always assert. */
#include "upb_table.h"
#include "upb_string.h"
#include "test_util.h"
#include <assert.h>
#include <map>
#include <string>
#include <vector>
#include <set>
#include <ext/hash_map>
#include <sys/resource.h>
#include <iostream>
bool benchmark = false;
#define CPU_TIME_PER_TEST 0.5
using std::string;
using std::vector;
typedef struct {
upb_inttable_entry e;
uint32_t value; /* key*2 */
} inttable_entry;
typedef struct {
upb_strtable_entry e;
int32_t value; /* ASCII Value of first letter */
} strtable_entry;
double get_usertime()
{
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
return usage.ru_utime.tv_sec + (usage.ru_utime.tv_usec/1000000.0);
}
/* num_entries must be a power of 2. */
void test_strtable(const vector<string>& keys, uint32_t num_to_insert)
{
/* Initialize structures. */
upb_strtable table;
std::map<string, int32_t> m;
upb_strtable_init(&table, 0, sizeof(strtable_entry));
std::set<string> all;
for(size_t i = 0; i < num_to_insert; i++) {
const string& key = keys[i];
all.insert(key);
strtable_entry e;
e.value = key[0];
upb_string *str = upb_strduplen(key.c_str(), key.size());
e.e.key = str;
upb_strtable_insert(&table, &e.e);
upb_string_unref(str); // The table still owns a ref.
m[key] = key[0];
}
/* Test correctness. */
for(uint32_t i = 0; i < keys.size(); i++) {
const string& key = keys[i];
upb_string *str = upb_strduplen(key.c_str(), key.size());
strtable_entry *e = (strtable_entry*)upb_strtable_lookup(&table, str);
if(m.find(key) != m.end()) { /* Assume map implementation is correct. */
assert(e);
assert(upb_streql(e->e.key, str));
assert(e->value == key[0]);
assert(m[key] == key[0]);
} else {
assert(e == NULL);
}
upb_string_unref(str);
}
strtable_entry *e;
for(e = (strtable_entry*)upb_strtable_begin(&table); e;
e = (strtable_entry*)upb_strtable_next(&table, &e->e)) {
string tmp(upb_string_getrobuf(e->e.key), upb_string_len(e->e.key));
std::set<string>::iterator i = all.find(tmp);
assert(i != all.end());
all.erase(i);
}
assert(all.empty());
upb_strtable_free(&table);
}
/* num_entries must be a power of 2. */
void test_inttable(int32_t *keys, uint16_t num_entries)
{
/* Initialize structures. */
upb_inttable table;
uint32_t largest_key = 0;
std::map<uint32_t, uint32_t> m;
__gnu_cxx::hash_map<uint32_t, uint32_t> hm;
upb_inttable_init(&table, num_entries, sizeof(inttable_entry));
for(size_t i = 0; i < num_entries; i++) {
int32_t key = keys[i];
largest_key = UPB_MAX((int32_t)largest_key, key);
inttable_entry e;
e.e.key = key;
e.value = key*2;
upb_inttable_insert(&table, &e.e);
m[key] = key*2;
hm[key] = key*2;
}
/* Test correctness. */
for(uint32_t i = 1; i <= largest_key; i++) {
inttable_entry *e = (inttable_entry*)upb_inttable_lookup(
&table, i);
if(m.find(i) != m.end()) { /* Assume map implementation is correct. */
assert(e);
assert(e->e.key == i);
assert(e->value == i*2);
assert(m[i] == i*2);
assert(hm[i] == i*2);
} else {
assert(e == NULL);
}
}
if(!benchmark) {
upb_inttable_free(&table);
return;
}
/* Test performance. We only test lookups for keys that are known to exist. */
uint16_t rand_order[num_entries];
for(uint16_t i = 0; i < num_entries; i++) {
rand_order[i] = i;
}
for(uint16_t i = num_entries - 1; i >= 1; i--) {
uint16_t rand_i = (random() / (double)RAND_MAX) * i;
assert(rand_i <= i);
uint16_t tmp = rand_order[rand_i];
rand_order[rand_i] = rand_order[i];
rand_order[i] = tmp;
}
uintptr_t x = 0;
const int mask = num_entries - 1;
int time_mask = 0xffff;
printf("upb_inttable(seq): ");
fflush(stdout);
double before = get_usertime();
unsigned int i;
for(i = 0; true; i++) {
if ((i & time_mask) == 0 && (get_usertime() - before) > CPU_TIME_PER_TEST) break;
int32_t key = keys[i & mask];
inttable_entry *e = (inttable_entry*)upb_inttable_lookup(&table, key);
x += (uintptr_t)e;
}
double total = get_usertime() - before;
printf("%s/s\n", eng(i/total, 3, false));
printf("upb_inttable(rand): ");
fflush(stdout);
before = get_usertime();
for(i = 0; true; i++) {
if ((i & time_mask) == 0 && (get_usertime() - before) > CPU_TIME_PER_TEST) break;
int32_t key = keys[rand_order[i & mask]];
inttable_entry *e = (inttable_entry*)upb_inttable_lookup(&table, key);
x += (uintptr_t)e;
}
total = get_usertime() - before;
printf("%s/s\n", eng(i/total, 3, false));
printf("std::map<int32_t, int32_t>(seq): ");
fflush(stdout);
before = get_usertime();
for(i = 0; true; i++) {
if ((i & time_mask) == 0 && (get_usertime() - before) > CPU_TIME_PER_TEST) break;
int32_t key = keys[i & mask];
x += m[key];
}
total = get_usertime() - before;
printf("%s/s\n", eng(i/total, 3, false));
printf("std::map<int32_t, int32_t>(rand): ");
fflush(stdout);
before = get_usertime();
for(i = 0; true; i++) {
if ((i & time_mask) == 0 && (get_usertime() - before) > CPU_TIME_PER_TEST) break;
int32_t key = keys[rand_order[i & mask]];
x += m[key];
}
total = get_usertime() - before;
printf("%s/s\n", eng(i/total, 3, false));
printf("__gnu_cxx::hash_map<uint32_t, uint32_t>(seq): ");
fflush(stdout);
before = get_usertime();
for(i = 0; true; i++) {
if ((i & time_mask) == 0 && (get_usertime() - before) > CPU_TIME_PER_TEST) break;
int32_t key = keys[rand_order[i & mask]];
x += hm[key];
}
total = get_usertime() - before;
printf("%s/s\n", eng(i/total, 3, false));
printf("__gnu_cxx::hash_map<uint32_t, uint32_t>(rand): ");
fflush(stdout);
before = get_usertime();
for(i = 0; true; i++) {
if ((i & time_mask) == 0 && (get_usertime() - before) > CPU_TIME_PER_TEST) break;
int32_t key = keys[rand_order[i & mask]];
x += hm[key];
}
total = get_usertime() - before;
printf("%s/s\n\n", eng(i/total, 3, false));
upb_inttable_free(&table);
}
int32_t *get_contiguous_keys(int32_t num)
{
int32_t *buf = new int32_t[num];
for(int32_t i = 0; i < num; i++)
buf[i] = i+1;
return buf;
}
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--benchmark") == 0) benchmark = true;
}
vector<string> keys;
keys.push_back("google.protobuf.FileDescriptorSet");
keys.push_back("google.protobuf.FileDescriptorProto");
keys.push_back("google.protobuf.DescriptorProto");
keys.push_back("google.protobuf.DescriptorProto.ExtensionRange");
keys.push_back("google.protobuf.FieldDescriptorProto");
keys.push_back("google.protobuf.EnumDescriptorProto");
keys.push_back("google.protobuf.EnumValueDescriptorProto");
keys.push_back("google.protobuf.ServiceDescriptorProto");
keys.push_back("google.protobuf.MethodDescriptorProto");
keys.push_back("google.protobuf.FileOptions");
keys.push_back("google.protobuf.MessageOptions");
keys.push_back("google.protobuf.FieldOptions");
keys.push_back("google.protobuf.EnumOptions");
keys.push_back("google.protobuf.EnumValueOptions");
keys.push_back("google.protobuf.ServiceOptions");
keys.push_back("google.protobuf.MethodOptions");
keys.push_back("google.protobuf.UninterpretedOption");
keys.push_back("google.protobuf.UninterpretedOption.NamePart");
test_strtable(keys, 18);
printf("Benchmarking hash lookups in an integer-keyed hash table.\n");
printf("\n");
int32_t *keys1 = get_contiguous_keys(8);
printf("Table size: 8, keys: 1-8 ====\n");
test_inttable(keys1, 8);
delete[] keys1;
int32_t *keys2 = get_contiguous_keys(64);
printf("Table size: 64, keys: 1-64 ====\n");
test_inttable(keys2, 64);
delete[] keys2;
int32_t *keys3 = get_contiguous_keys(512);
printf("Table size: 512, keys: 1-512 ====\n");
test_inttable(keys3, 512);
delete[] keys3;
int32_t *keys4 = new int32_t[64];
for(int32_t i = 0; i < 64; i++) {
if(i < 32)
keys4[i] = i+1;
else
keys4[i] = 10101+i;
}
printf("Table size: 64, keys: 1-32 and 10133-10164 ====\n");
test_inttable(keys4, 64);
delete[] keys4;
}
<|endoftext|>
|
<commit_before>#include <Python.h>
#include <structmember.h>
#include <rank_unrank.h>
/*
* This is a wrapper around rank_unrank.cc, to create the fte.cDFA
* python module.
*/
// Our custom DFAObject for holding and transporting a DFA*.
typedef struct {
PyObject_HEAD
DFA *obj;
} DFAObject;
// Our dealloc function for cleaning up when our fte.cDFA.DFA object is deleted.
static void
DFA_dealloc(PyObject* self)
{
DFAObject *pDFAObject = (DFAObject*)self;
if (pDFAObject->obj != NULL)
delete pDFAObject->obj;
if (self != NULL)
PyObject_Del(self);
}
// The wrapper for calling DFA::rank.
// Takes a string as input and returns an integer.
static PyObject * DFA__rank(PyObject *self, PyObject *args) {
char* word;
uint32_t len;
if (!PyArg_ParseTuple(args, "s#", &word, &len))
return NULL;
// Copy our input word into a string.
// We have to do the following, because we may have NUL-bytes in our strings.
const std::string str_word = std::string(word, len);
// Verify our environment is sane and perform ranking.
DFAObject *pDFAObject = (DFAObject*)self;
if (pDFAObject->obj == NULL)
return NULL;
mpz_class result;
try {
result = pDFAObject->obj->rank(str_word);
} catch (std::exception& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
return 0;
}
// Set our c_out value
uint32_t base = 10;
std::string to_convert = result.get_str(base);
PyObject *retval = PyLong_FromString((char*)(to_convert.c_str()), NULL, base);
return retval;
}
// Wrapper for DFA::unrank.
// On input of an integer, returns a string.
static PyObject * DFA__unrank(PyObject *self, PyObject *args) {
PyObject* c;
if (!PyArg_ParseTuple(args, "O", &c))
return NULL;
//PyNumber to mpz_class
int base = 16;
PyObject* b64 = PyNumber_ToBase(c, base);
if (!b64) {
return NULL;
}
const char* the_c_str = PyString_AsString(b64);
if (!the_c_str) {
Py_DECREF(b64);
return NULL;
}
mpz_class to_unrank(the_c_str, 0);
Py_DECREF(b64);
Py_DECREF(the_c_str);
// Verify our environment is sane and perform unranking.
DFAObject *pDFAObject = (DFAObject*)self;
if (pDFAObject->obj == NULL)
return NULL;
std::string result;
try {
result = pDFAObject->obj->unrank(to_unrank);
} catch (std::exception& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
return 0;
}
// Format our std::string as a python string and return it.
PyObject* retval = Py_BuildValue("s#", result.c_str(), result.length());
return retval;
}
// Takes as input two integers [min, max].
// Returns the number of strings in our language that are at least
// length min and no longer than length max, inclusive.
static PyObject * DFA__getNumWordsInLanguage(PyObject *self, PyObject *args) {
PyObject* retval;
uint32_t min_val;
uint32_t max_val;
if (!PyArg_ParseTuple(args, "ii", &min_val, &max_val))
return NULL;
// Verify our environment is sane, then call getNumWordsInLanguage.
DFAObject *pDFAObject = (DFAObject*)self;
if (pDFAObject->obj == NULL)
return NULL;
mpz_class num_words = pDFAObject->obj->getNumWordsInLanguage(min_val, max_val);
// Convert the resulting integer to a string.
// -- Is there a better way?
uint32_t base = 10;
uint32_t num_words_str_len = num_words.get_str().length();
char *num_words_str = new char[num_words_str_len + 1];
strcpy(num_words_str, num_words.get_str().c_str());
retval = PyLong_FromString(num_words_str, NULL, base);
// cleanup
delete [] num_words_str;
return retval;
}
// Boilerplat python object alloc.
static PyObject *
DFA_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
DFAObject *self;
self = (DFAObject *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
// Our initialization function for fte.cDFA.DFA
// On input of a [str, int], where str is a regex,
// returns an fte.cDFA.DFA object that can perform ranking/unranking
// See rank_unrank.h for the significance of the input parameters.
static int
DFA_init(DFAObject *self, PyObject *args, PyObject *kwds)
{
// TODO: Figure out why the standard PyArg_ParseTuple pattern
// doesn't work.
// see: https://github.com/kpdyer/libfte/issues/94
//if (!PyArg_ParseTuple(args, "s#i", ®ex, &len, &max_len))
// return -1;
PyObject *arg0 = PyTuple_GetItem(args, 0);
if (!PyString_Check(arg0)) {
PyErr_SetString(PyExc_RuntimeError, "First argument must be a string");
return 0;
}
const char* regex = PyString_AsString(arg0);
PyObject *arg1 = PyTuple_GetItem(args, 1);
if (!PyInt_Check(arg1)) {
PyErr_SetString(PyExc_RuntimeError, "Second argument must be an int");
return 0;
}
uint32_t max_len = PyInt_AsLong(arg1);
// Try to initialize our DFA object.
// An exception is thrown if the input AT&T FST is not formatted as we expect.
// See DFA::_validate for a list of assumptions.
try {
const std::string str_regex = std::string(regex);
DFA *dfa = new DFA(str_regex, max_len);
self->obj = dfa;
} catch (std::exception& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
return 0;
}
return 0;
}
// Methods in fte.cDFA.DFA
static PyMethodDef DFA_methods[] = {
{"rank", DFA__rank, METH_VARARGS, NULL},
{"unrank", DFA__unrank, METH_VARARGS, NULL},
{"getNumWordsInLanguage", DFA__getNumWordsInLanguage, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
// Boilerplate DFAType structure that contains the structure of the fte.cDFA.DFA type
static PyTypeObject DFAType = {
PyObject_HEAD_INIT(NULL)
0,
"DFA",
sizeof(DFAObject),
0,
DFA_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE, /*tp_flags*/
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DFA_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DFA_init, /* tp_init */
0, /* tp_alloc */
DFA_new, /* tp_new */
0, /* tp_free */
};
// Methods in our fte.cDFA package
static PyMethodDef ftecDFAMethods[] = {
{NULL, NULL, 0, NULL}
};
// Main entry point for the fte.cDFA module.
#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initcDFA(void)
{
if (PyType_Ready(&DFAType) < 0)
return;
PyObject *m;
m = Py_InitModule("cDFA", ftecDFAMethods);
if (m == NULL)
return;
Py_INCREF(&DFAType);
PyModule_AddObject(m, "DFA", (PyObject *)&DFAType);
}
<commit_msg>Removing an unnecessary Py_DECREF that can cause a segmentation fault.<commit_after>#include <Python.h>
#include <structmember.h>
#include <rank_unrank.h>
/*
* This is a wrapper around rank_unrank.cc, to create the fte.cDFA
* python module.
*/
// Our custom DFAObject for holding and transporting a DFA*.
typedef struct {
PyObject_HEAD
DFA *obj;
} DFAObject;
// Our dealloc function for cleaning up when our fte.cDFA.DFA object is deleted.
static void
DFA_dealloc(PyObject* self)
{
DFAObject *pDFAObject = (DFAObject*)self;
if (pDFAObject->obj != NULL)
delete pDFAObject->obj;
if (self != NULL)
PyObject_Del(self);
}
// The wrapper for calling DFA::rank.
// Takes a string as input and returns an integer.
static PyObject * DFA__rank(PyObject *self, PyObject *args) {
char* word;
uint32_t len;
if (!PyArg_ParseTuple(args, "s#", &word, &len))
return NULL;
// Copy our input word into a string.
// We have to do the following, because we may have NUL-bytes in our strings.
const std::string str_word = std::string(word, len);
// Verify our environment is sane and perform ranking.
DFAObject *pDFAObject = (DFAObject*)self;
if (pDFAObject->obj == NULL)
return NULL;
mpz_class result;
try {
result = pDFAObject->obj->rank(str_word);
} catch (std::exception& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
return 0;
}
// Set our c_out value
uint32_t base = 10;
std::string to_convert = result.get_str(base);
PyObject *retval = PyLong_FromString((char*)(to_convert.c_str()), NULL, base);
return retval;
}
// Wrapper for DFA::unrank.
// On input of an integer, returns a string.
static PyObject * DFA__unrank(PyObject *self, PyObject *args) {
PyObject* c;
if (!PyArg_ParseTuple(args, "O", &c))
return NULL;
//PyNumber to mpz_class
int base = 16;
PyObject* b64 = PyNumber_ToBase(c, base);
if (!b64) {
return NULL;
}
const char* the_c_str = PyString_AsString(b64);
if (!the_c_str) {
Py_DECREF(b64);
return NULL;
}
mpz_class to_unrank(the_c_str, 0);
the_c_str = NULL;
Py_DECREF(b64);
// Verify our environment is sane and perform unranking.
DFAObject *pDFAObject = (DFAObject*)self;
if (pDFAObject->obj == NULL)
return NULL;
std::string result;
try {
result = pDFAObject->obj->unrank(to_unrank);
} catch (std::exception& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
return 0;
}
// Format our std::string as a python string and return it.
PyObject* retval = Py_BuildValue("s#", result.c_str(), result.length());
return retval;
}
// Takes as input two integers [min, max].
// Returns the number of strings in our language that are at least
// length min and no longer than length max, inclusive.
static PyObject * DFA__getNumWordsInLanguage(PyObject *self, PyObject *args) {
PyObject* retval;
uint32_t min_val;
uint32_t max_val;
if (!PyArg_ParseTuple(args, "ii", &min_val, &max_val))
return NULL;
// Verify our environment is sane, then call getNumWordsInLanguage.
DFAObject *pDFAObject = (DFAObject*)self;
if (pDFAObject->obj == NULL)
return NULL;
mpz_class num_words = pDFAObject->obj->getNumWordsInLanguage(min_val, max_val);
// Convert the resulting integer to a string.
// -- Is there a better way?
uint32_t base = 10;
uint32_t num_words_str_len = num_words.get_str().length();
char *num_words_str = new char[num_words_str_len + 1];
strcpy(num_words_str, num_words.get_str().c_str());
retval = PyLong_FromString(num_words_str, NULL, base);
// cleanup
delete [] num_words_str;
return retval;
}
// Boilerplat python object alloc.
static PyObject *
DFA_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
DFAObject *self;
self = (DFAObject *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
// Our initialization function for fte.cDFA.DFA
// On input of a [str, int], where str is a regex,
// returns an fte.cDFA.DFA object that can perform ranking/unranking
// See rank_unrank.h for the significance of the input parameters.
static int
DFA_init(DFAObject *self, PyObject *args, PyObject *kwds)
{
// TODO: Figure out why the standard PyArg_ParseTuple pattern
// doesn't work.
// see: https://github.com/kpdyer/libfte/issues/94
//if (!PyArg_ParseTuple(args, "s#i", ®ex, &len, &max_len))
// return -1;
PyObject *arg0 = PyTuple_GetItem(args, 0);
if (!PyString_Check(arg0)) {
PyErr_SetString(PyExc_RuntimeError, "First argument must be a string");
return 0;
}
const char* regex = PyString_AsString(arg0);
PyObject *arg1 = PyTuple_GetItem(args, 1);
if (!PyInt_Check(arg1)) {
PyErr_SetString(PyExc_RuntimeError, "Second argument must be an int");
return 0;
}
uint32_t max_len = PyInt_AsLong(arg1);
// Try to initialize our DFA object.
// An exception is thrown if the input AT&T FST is not formatted as we expect.
// See DFA::_validate for a list of assumptions.
try {
const std::string str_regex = std::string(regex);
DFA *dfa = new DFA(str_regex, max_len);
self->obj = dfa;
} catch (std::exception& e) {
PyErr_SetString(PyExc_RuntimeError, e.what());
return 0;
}
return 0;
}
// Methods in fte.cDFA.DFA
static PyMethodDef DFA_methods[] = {
{"rank", DFA__rank, METH_VARARGS, NULL},
{"unrank", DFA__unrank, METH_VARARGS, NULL},
{"getNumWordsInLanguage", DFA__getNumWordsInLanguage, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
// Boilerplate DFAType structure that contains the structure of the fte.cDFA.DFA type
static PyTypeObject DFAType = {
PyObject_HEAD_INIT(NULL)
0,
"DFA",
sizeof(DFAObject),
0,
DFA_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT |
Py_TPFLAGS_BASETYPE, /*tp_flags*/
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
DFA_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)DFA_init, /* tp_init */
0, /* tp_alloc */
DFA_new, /* tp_new */
0, /* tp_free */
};
// Methods in our fte.cDFA package
static PyMethodDef ftecDFAMethods[] = {
{NULL, NULL, 0, NULL}
};
// Main entry point for the fte.cDFA module.
#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initcDFA(void)
{
if (PyType_Ready(&DFAType) < 0)
return;
PyObject *m;
m = Py_InitModule("cDFA", ftecDFAMethods);
if (m == NULL)
return;
Py_INCREF(&DFAType);
PyModule_AddObject(m, "DFA", (PyObject *)&DFAType);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser_prefs.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_dom_ui.h"
#include "chrome/browser/extensions/extensions_ui.h"
#include "chrome/browser/external_protocol_handler.h"
#include "chrome/browser/form_field_history_manager.h"
#include "chrome/browser/geolocation/access_token_store.h"
#include "chrome/browser/google_url_tracker.h"
#include "chrome/browser/host_content_settings_map.h"
#include "chrome/browser/host_zoom_map.h"
#include "chrome/browser/intranet_redirect_detector.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/net/dns_global.h"
#include "chrome/browser/page_info_model.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/browser/renderer_host/browser_render_process_host.h"
#include "chrome/browser/renderer_host/web_cache_manager.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/search_engines/keyword_editor_controller.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/browser/session_startup_pref.h"
#include "chrome/browser/ssl/ssl_manager.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/task_manager.h"
#if defined(TOOLKIT_VIEWS) // TODO(port): whittle this down as we port
#include "chrome/browser/views/browser_actions_container.h"
#include "chrome/browser/views/frame/browser_view.h"
#endif
#if defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/browser_window_gtk.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/preferences.h"
#endif
#if defined(OS_WIN)
// TODO: port me.
#include "chrome/browser/cookie_modal_dialog.h"
#endif
namespace browser {
void RegisterAllPrefs(PrefService* user_prefs, PrefService* local_state) {
RegisterLocalState(local_state);
RegisterUserPrefs(user_prefs);
}
void RegisterLocalState(PrefService* local_state) {
// Prefs in Local State
Browser::RegisterPrefs(local_state);
WebCacheManager::RegisterPrefs(local_state);
ExternalProtocolHandler::RegisterPrefs(local_state);
GoogleURLTracker::RegisterPrefs(local_state);
IntranetRedirectDetector::RegisterPrefs(local_state);
KeywordEditorController::RegisterPrefs(local_state);
MetricsLog::RegisterPrefs(local_state);
MetricsService::RegisterPrefs(local_state);
SafeBrowsingService::RegisterPrefs(local_state);
browser_shutdown::RegisterPrefs(local_state);
chrome_browser_net::RegisterPrefs(local_state);
bookmark_utils::RegisterPrefs(local_state);
PageInfoModel::RegisterPrefs(local_state);
#if defined(TOOLKIT_VIEWS) // TODO(port): whittle this down as we port
BrowserView::RegisterBrowserViewPrefs(local_state);
#endif
TaskManager::RegisterPrefs(local_state);
#if defined(OS_WIN)
CookiePromptModalDialog::RegisterPrefs(local_state);
#endif
AccessTokenStore::RegisterPrefs(local_state);
}
void RegisterUserPrefs(PrefService* user_prefs) {
// User prefs
AutoFillManager::RegisterUserPrefs(user_prefs);
SessionStartupPref::RegisterUserPrefs(user_prefs);
Browser::RegisterUserPrefs(user_prefs);
PasswordManager::RegisterUserPrefs(user_prefs);
chrome_browser_net::RegisterUserPrefs(user_prefs);
DownloadManager::RegisterUserPrefs(user_prefs);
SSLManager::RegisterUserPrefs(user_prefs);
bookmark_utils::RegisterUserPrefs(user_prefs);
FormFieldHistoryManager::RegisterUserPrefs(user_prefs);
TabContents::RegisterUserPrefs(user_prefs);
TemplateURLPrepopulateData::RegisterUserPrefs(user_prefs);
ExtensionDOMUI::RegisterUserPrefs(user_prefs);
ExtensionsUI::RegisterUserPrefs(user_prefs);
NewTabUI::RegisterUserPrefs(user_prefs);
HostContentSettingsMap::RegisterUserPrefs(user_prefs);
HostZoomMap::RegisterUserPrefs(user_prefs);
DevToolsManager::RegisterUserPrefs(user_prefs);
Blacklist::RegisterUserPrefs(user_prefs);
#if defined(TOOLKIT_VIEWS) // TODO(port): whittle this down as we port.
BrowserActionsContainer::RegisterUserPrefs(user_prefs);
#endif
#if defined(TOOLKIT_GTK)
BrowserWindowGtk::RegisterUserPrefs(user_prefs);
#endif
#if defined(OS_CHROMEOS)
chromeos::Preferences::RegisterUserPrefs(user_prefs);
#endif
}
} // namespace browser
<commit_msg>Switch browser prefs to use the higher level geolocation::RegisterPrefs method rather than call into random internal component of geolocaiton (and so avoid the associated header file dependency bloat) geolocation_prefs.h was already added in http://src.chromium.org/viewvc/chrome?view=rev&revision=39232 I just forgot to include this edit<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/browser_prefs.h"
#include "chrome/browser/autofill/autofill_manager.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/debugger/devtools_manager.h"
#include "chrome/browser/dom_ui/new_tab_ui.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_dom_ui.h"
#include "chrome/browser/extensions/extensions_ui.h"
#include "chrome/browser/external_protocol_handler.h"
#include "chrome/browser/form_field_history_manager.h"
#include "chrome/browser/geolocation/geolocation_prefs.h"
#include "chrome/browser/google_url_tracker.h"
#include "chrome/browser/host_content_settings_map.h"
#include "chrome/browser/host_zoom_map.h"
#include "chrome/browser/intranet_redirect_detector.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/net/dns_global.h"
#include "chrome/browser/page_info_model.h"
#include "chrome/browser/password_manager/password_manager.h"
#include "chrome/browser/privacy_blacklist/blacklist.h"
#include "chrome/browser/renderer_host/browser_render_process_host.h"
#include "chrome/browser/renderer_host/web_cache_manager.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/search_engines/keyword_editor_controller.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/browser/session_startup_pref.h"
#include "chrome/browser/ssl/ssl_manager.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/task_manager.h"
#if defined(TOOLKIT_VIEWS) // TODO(port): whittle this down as we port
#include "chrome/browser/views/browser_actions_container.h"
#include "chrome/browser/views/frame/browser_view.h"
#endif
#if defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/browser_window_gtk.h"
#endif
#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/preferences.h"
#endif
#if defined(OS_WIN)
// TODO: port me.
#include "chrome/browser/cookie_modal_dialog.h"
#endif
namespace browser {
void RegisterAllPrefs(PrefService* user_prefs, PrefService* local_state) {
RegisterLocalState(local_state);
RegisterUserPrefs(user_prefs);
}
void RegisterLocalState(PrefService* local_state) {
// Prefs in Local State
Browser::RegisterPrefs(local_state);
WebCacheManager::RegisterPrefs(local_state);
ExternalProtocolHandler::RegisterPrefs(local_state);
GoogleURLTracker::RegisterPrefs(local_state);
IntranetRedirectDetector::RegisterPrefs(local_state);
KeywordEditorController::RegisterPrefs(local_state);
MetricsLog::RegisterPrefs(local_state);
MetricsService::RegisterPrefs(local_state);
SafeBrowsingService::RegisterPrefs(local_state);
browser_shutdown::RegisterPrefs(local_state);
chrome_browser_net::RegisterPrefs(local_state);
bookmark_utils::RegisterPrefs(local_state);
PageInfoModel::RegisterPrefs(local_state);
#if defined(TOOLKIT_VIEWS) // TODO(port): whittle this down as we port
BrowserView::RegisterBrowserViewPrefs(local_state);
#endif
TaskManager::RegisterPrefs(local_state);
#if defined(OS_WIN)
CookiePromptModalDialog::RegisterPrefs(local_state);
#endif
geolocation::RegisterPrefs(local_state);
}
void RegisterUserPrefs(PrefService* user_prefs) {
// User prefs
AutoFillManager::RegisterUserPrefs(user_prefs);
SessionStartupPref::RegisterUserPrefs(user_prefs);
Browser::RegisterUserPrefs(user_prefs);
PasswordManager::RegisterUserPrefs(user_prefs);
chrome_browser_net::RegisterUserPrefs(user_prefs);
DownloadManager::RegisterUserPrefs(user_prefs);
SSLManager::RegisterUserPrefs(user_prefs);
bookmark_utils::RegisterUserPrefs(user_prefs);
FormFieldHistoryManager::RegisterUserPrefs(user_prefs);
TabContents::RegisterUserPrefs(user_prefs);
TemplateURLPrepopulateData::RegisterUserPrefs(user_prefs);
ExtensionDOMUI::RegisterUserPrefs(user_prefs);
ExtensionsUI::RegisterUserPrefs(user_prefs);
NewTabUI::RegisterUserPrefs(user_prefs);
HostContentSettingsMap::RegisterUserPrefs(user_prefs);
HostZoomMap::RegisterUserPrefs(user_prefs);
DevToolsManager::RegisterUserPrefs(user_prefs);
Blacklist::RegisterUserPrefs(user_prefs);
#if defined(TOOLKIT_VIEWS) // TODO(port): whittle this down as we port.
BrowserActionsContainer::RegisterUserPrefs(user_prefs);
#endif
#if defined(TOOLKIT_GTK)
BrowserWindowGtk::RegisterUserPrefs(user_prefs);
#endif
#if defined(OS_CHROMEOS)
chromeos::Preferences::RegisterUserPrefs(user_prefs);
#endif
}
} // namespace browser
<|endoftext|>
|
<commit_before><commit_msg>Marking the CrossSiteInfiniteBeforeUnloadAsync test as flaky as it fails randomly on the valgrind Linux builder.<commit_after><|endoftext|>
|
<commit_before>// Copyright 2015 Google Inc. 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.
// Tests for writing out the basic record types.
#include <iostream>
using namespace std;
#include <sys/stat.h>
#include <string>
#include "gsf.h"
#include "gsf_ft.h"
#include "gsf_test_util.h"
#include "gtest/gtest.h"
namespace generic_sensor_format {
namespace test {
namespace {
TEST(GsfWriteSimple, HeaderOnly) {
int handle;
char filename[] = "sample-header-only.gsf";
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(24, buf.st_size);
}
void ValidateWriteComment(const char *filename,
bool checksum,
int expected_write_size,
const char *comment,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 44);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_COMMENT, 0};
gsfRecords record;
record.comment = GsfComment({1, 2}, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes
= gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
VerifyComment(record.comment, read_record.comment);
}
TEST(GsfWriteSimple, CommentEmpty) {
char filename[] = "sample-comment-empty.gsf";
char comment[] = "";
ValidateWriteComment(filename, false, 20, comment, 44);
}
TEST(GsfWriteSimple, CommentEmptyChecksum) {
char filename[] = "sample-comment-empty-checksum.gsf";
char comment[] = "";
ValidateWriteComment(filename, true, 24, comment, 48);
}
TEST(GsfWriteSimple, CommentUpTo5) {
char filename1[] = "sample-comment-1.gsf";
char comment1[] = "a";
ValidateWriteComment(filename1, false, 24, comment1, 48);
char filename2[] = "sample-comment-2.gsf";
char comment2[] = "ab";
ValidateWriteComment(filename2, false, 24, comment2, 48);
char filename3[] = "sample-comment-3.gsf";
char comment3[] = "abc";
ValidateWriteComment(filename3, false, 24, comment3, 48);
char filename4[] = "sample-comment-4.gsf";
char comment4[] = "abcd";
ValidateWriteComment(filename4, false, 24, comment4, 48);
char filename5[] = "sample-comment-5.gsf";
char comment5[] = "abcde";
ValidateWriteComment(filename5, false, 28, comment5, 52);
}
TEST(GsfWriteSimple, CommentLarge) {
char filename[] = "sample-comment-large.gsf";
char comment[] =
"ab"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"de";
ValidateWriteComment(filename, false, 656, comment, 680);
}
void ValidateWriteHistory(const char *filename,
bool checksum,
int expected_write_size,
const char *host_name,
const char *operator_name,
const char *command_line,
const char *comment,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 28);
ASSERT_NE(nullptr, host_name);
ASSERT_LE(strlen(host_name), GSF_HOST_NAME_LENGTH);
ASSERT_NE(nullptr, operator_name);
ASSERT_LE(strlen(operator_name), GSF_OPERATOR_LENGTH);
ASSERT_NE(nullptr, command_line);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 52);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_HISTORY, 0};
gsfRecords record;
record.history
= GsfHistory({1, 2}, host_name, operator_name, command_line, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes
= gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_HISTORY, data_id.recordID);
VerifyHistory(record.history, read_record.history);
}
TEST(GsfWriteSimple, History) {
ValidateWriteHistory(
"sample-history-empty.gsf", false, 28, "", "", "", "", 52);
ValidateWriteHistory(
"sample-history-empty-checksum.gsf", true, 32, "", "", "", "", 56);
ValidateWriteHistory(
"sample-history-1.gsf", false, 32, "a", "b", "c", "d", 56);
ValidateWriteHistory(
"sample-history-longer.gsf", false, 40, "ab", "cde", "fghi", "jklm", 64);
}
} // namespace
} // namespace test
} // namespace generic_sensor_format
<commit_msg>List the records that need to be tested.<commit_after>// Copyright 2015 Google Inc. 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.
// Tests for writing out the basic record types.
#include <iostream>
using namespace std;
#include <sys/stat.h>
#include <string>
#include "gsf.h"
#include "gsf_ft.h"
#include "gsf_test_util.h"
#include "gtest/gtest.h"
namespace generic_sensor_format {
namespace test {
namespace {
TEST(GsfWriteSimple, HeaderOnly) {
int handle;
char filename[] = "sample-header-only.gsf";
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(24, buf.st_size);
}
// TODO(schwehr): GSF_RECORD_SWATH_BATHYMETRY_PING.
// TODO(schwehr): GSF_RECORD_SOUND_VELOCITY_PROFILE
// TODO(schwehr): GSF_RECORD_PROCESSING_PARAMETERS
// TODO(schwehr): GSF_RECORD_SENSOR_PARAMETERS
void ValidateWriteComment(const char *filename,
bool checksum,
int expected_write_size,
const char *comment,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 20);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 44);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_COMMENT, 0};
gsfRecords record;
record.comment = GsfComment({1, 2}, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes
= gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
VerifyComment(record.comment, read_record.comment);
}
TEST(GsfWriteSimple, CommentEmpty) {
char filename[] = "sample-comment-empty.gsf";
char comment[] = "";
ValidateWriteComment(filename, false, 20, comment, 44);
}
TEST(GsfWriteSimple, CommentEmptyChecksum) {
char filename[] = "sample-comment-empty-checksum.gsf";
char comment[] = "";
ValidateWriteComment(filename, true, 24, comment, 48);
}
TEST(GsfWriteSimple, CommentUpTo5) {
char filename1[] = "sample-comment-1.gsf";
char comment1[] = "a";
ValidateWriteComment(filename1, false, 24, comment1, 48);
char filename2[] = "sample-comment-2.gsf";
char comment2[] = "ab";
ValidateWriteComment(filename2, false, 24, comment2, 48);
char filename3[] = "sample-comment-3.gsf";
char comment3[] = "abc";
ValidateWriteComment(filename3, false, 24, comment3, 48);
char filename4[] = "sample-comment-4.gsf";
char comment4[] = "abcd";
ValidateWriteComment(filename4, false, 24, comment4, 48);
char filename5[] = "sample-comment-5.gsf";
char comment5[] = "abcde";
ValidateWriteComment(filename5, false, 28, comment5, 52);
}
TEST(GsfWriteSimple, CommentLarge) {
char filename[] = "sample-comment-large.gsf";
char comment[] =
"ab"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
"de";
ValidateWriteComment(filename, false, 656, comment, 680);
}
void ValidateWriteHistory(const char *filename,
bool checksum,
int expected_write_size,
const char *host_name,
const char *operator_name,
const char *command_line,
const char *comment,
int expected_file_size) {
ASSERT_NE(nullptr, filename);
ASSERT_GE(expected_write_size, 28);
ASSERT_NE(nullptr, host_name);
ASSERT_LE(strlen(host_name), GSF_HOST_NAME_LENGTH);
ASSERT_NE(nullptr, operator_name);
ASSERT_LE(strlen(operator_name), GSF_OPERATOR_LENGTH);
ASSERT_NE(nullptr, command_line);
ASSERT_NE(nullptr, comment);
ASSERT_GE(expected_file_size, 52);
int handle;
ASSERT_EQ(0, gsfOpen(filename, GSF_CREATE, &handle));
gsfDataID data_id = {checksum, 0, GSF_RECORD_HISTORY, 0};
gsfRecords record;
record.history
= GsfHistory({1, 2}, host_name, operator_name, command_line, comment);
ASSERT_EQ(expected_write_size, gsfWrite(handle, &data_id, &record));
ASSERT_EQ(0, gsfClose(handle));
struct stat buf;
ASSERT_EQ(0, stat(filename, &buf));
ASSERT_EQ(expected_file_size, buf.st_size);
ASSERT_EQ(0, gsfOpen(filename, GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfRecords read_record;
const int num_bytes
= gsfRead(handle, GSF_NEXT_RECORD, &data_id, &read_record, nullptr, 0);
ASSERT_EQ(expected_write_size, num_bytes);
ASSERT_EQ(GSF_RECORD_HISTORY, data_id.recordID);
VerifyHistory(record.history, read_record.history);
}
TEST(GsfWriteSimple, History) {
ValidateWriteHistory(
"sample-history-empty.gsf", false, 28, "", "", "", "", 52);
ValidateWriteHistory(
"sample-history-empty-checksum.gsf", true, 32, "", "", "", "", 56);
ValidateWriteHistory(
"sample-history-1.gsf", false, 32, "a", "b", "c", "d", 56);
ValidateWriteHistory(
"sample-history-longer.gsf", false, 40, "ab", "cde", "fghi", "jklm", 64);
}
// TODO(schwehr): GSF_RECORD_NAVIGATION_ERROR
// TODO(schwehr): GSF_RECORD_SWATH_BATHY_SUMMARY
// TODO(schwehr): GSF_RECORD_SINGLE_BEAM_PING
// TODO(schwehr): GSF_RECORD_HV_NAVIGATION_ERROR
// TODO(schwehr): GSF_RECORD_ATTITUDE
} // namespace
} // namespace test
} // namespace generic_sensor_format
<|endoftext|>
|
<commit_before>//===---- ClangQuery.cpp - clang-query tool -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool is for interactive exploration of the Clang AST using AST matchers.
// It currently allows the user to enter a matcher at an interactive prompt and
// view the resulting bindings as diagnostics, AST pretty prints or AST dumps.
// Example session:
//
// $ cat foo.c
// void foo(void) {}
// $ clang-query foo.c --
// clang-query> match functionDecl()
//
// Match #1:
//
// foo.c:1:1: note: "root" binds here
// void foo(void) {}
// ^~~~~~~~~~~~~~~~~
// 1 match.
//
//===----------------------------------------------------------------------===//
#include "Query.h"
#include "QueryParser.h"
#include "QuerySession.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/LineEditor/LineEditor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include <fstream>
#include <string>
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::ast_matchers::dynamic;
using namespace clang::query;
using namespace clang::tooling;
using namespace llvm;
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::OptionCategory ClangQueryCategory("clang-query options");
static cl::list<std::string> Commands("c", cl::desc("Specify command to run"),
cl::value_desc("command"),
cl::cat(ClangQueryCategory));
static cl::list<std::string> CommandFiles("f",
cl::desc("Read commands from file"),
cl::value_desc("file"),
cl::cat(ClangQueryCategory));
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
if (!Commands.empty() && !CommandFiles.empty()) {
llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
return 1;
}
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
std::vector<std::unique_ptr<ASTUnit>> ASTs;
if (Tool.buildASTs(ASTs) != 0)
return 1;
QuerySession QS(ASTs);
if (!Commands.empty()) {
for (auto I = Commands.begin(), E = Commands.end(); I != E; ++I) {
QueryRef Q = QueryParser::parse(*I, QS);
if (!Q->run(llvm::outs(), QS))
return 1;
}
} else if (!CommandFiles.empty()) {
for (auto I = CommandFiles.begin(), E = CommandFiles.end(); I != E; ++I) {
std::ifstream Input(I->c_str());
if (!Input.is_open()) {
llvm::errs() << argv[0] << ": cannot open " << *I << "\n";
return 1;
}
while (Input.good()) {
std::string Line;
std::getline(Input, Line);
QueryRef Q = QueryParser::parse(Line, QS);
if (!Q->run(llvm::outs(), QS))
return 1;
}
}
} else {
LineEditor LE("clang-query");
LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
return QueryParser::complete(Line, Pos, QS);
});
while (llvm::Optional<std::string> Line = LE.readLine()) {
QueryRef Q = QueryParser::parse(*Line, QS);
Q->run(llvm::outs(), QS);
llvm::outs().flush();
if (QS.Terminate)
break;
}
}
return 0;
}
<commit_msg>Extract runCommandsInFile method<commit_after>//===---- ClangQuery.cpp - clang-query tool -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tool is for interactive exploration of the Clang AST using AST matchers.
// It currently allows the user to enter a matcher at an interactive prompt and
// view the resulting bindings as diagnostics, AST pretty prints or AST dumps.
// Example session:
//
// $ cat foo.c
// void foo(void) {}
// $ clang-query foo.c --
// clang-query> match functionDecl()
//
// Match #1:
//
// foo.c:1:1: note: "root" binds here
// void foo(void) {}
// ^~~~~~~~~~~~~~~~~
// 1 match.
//
//===----------------------------------------------------------------------===//
#include "Query.h"
#include "QueryParser.h"
#include "QuerySession.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/LineEditor/LineEditor.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include <fstream>
#include <string>
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::ast_matchers::dynamic;
using namespace clang::query;
using namespace clang::tooling;
using namespace llvm;
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::OptionCategory ClangQueryCategory("clang-query options");
static cl::list<std::string> Commands("c", cl::desc("Specify command to run"),
cl::value_desc("command"),
cl::cat(ClangQueryCategory));
static cl::list<std::string> CommandFiles("f",
cl::desc("Read commands from file"),
cl::value_desc("file"),
cl::cat(ClangQueryCategory));
bool runCommandsInFile(const char *ExeName, std::string const &FileName,
QuerySession &QS) {
std::ifstream Input(FileName.c_str());
if (!Input.is_open()) {
llvm::errs() << ExeName << ": cannot open " << FileName << "\n";
return 1;
}
while (Input.good()) {
std::string Line;
std::getline(Input, Line);
QueryRef Q = QueryParser::parse(Line, QS);
if (!Q->run(llvm::outs(), QS))
return true;
}
return false;
}
int main(int argc, const char **argv) {
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
CommonOptionsParser OptionsParser(argc, argv, ClangQueryCategory);
if (!Commands.empty() && !CommandFiles.empty()) {
llvm::errs() << argv[0] << ": cannot specify both -c and -f\n";
return 1;
}
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
std::vector<std::unique_ptr<ASTUnit>> ASTs;
if (Tool.buildASTs(ASTs) != 0)
return 1;
QuerySession QS(ASTs);
if (!Commands.empty()) {
for (auto I = Commands.begin(), E = Commands.end(); I != E; ++I) {
QueryRef Q = QueryParser::parse(*I, QS);
if (!Q->run(llvm::outs(), QS))
return 1;
}
} else if (!CommandFiles.empty()) {
for (auto I = CommandFiles.begin(), E = CommandFiles.end(); I != E; ++I) {
if (runCommandsInFile(argv[0], *I, QS))
return 1;
}
} else {
LineEditor LE("clang-query");
LE.setListCompleter([&QS](StringRef Line, size_t Pos) {
return QueryParser::complete(Line, Pos, QS);
});
while (llvm::Optional<std::string> Line = LE.readLine()) {
QueryRef Q = QueryParser::parse(*Line, QS);
Q->run(llvm::outs(), QS);
llvm::outs().flush();
if (QS.Terminate)
break;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_SERIALIZER_HPP
#define TOML11_SERIALIZER_HPP
#include "value.hpp"
#include "lexer.hpp"
#include <limits>
namespace toml
{
struct serializer
{
serializer(const std::size_t w = 80,
const int float_prec = std::numeric_limits<toml::floating>::max_digits10,
const bool can_be_inlined = false,
std::vector<toml::key> ks = {})
: can_be_inlined_(can_be_inlined), float_prec_(float_prec), width_(w),
keys_(std::move(ks))
{}
~serializer() = default;
std::string operator()(const toml::boolean& b) const
{
return b ? "true" : "false";
}
std::string operator()(const integer i) const
{
return std::to_string(i);
}
std::string operator()(const toml::floating f) const
{
std::string token = [=] {
// every float value needs decimal point (or exponent).
std::ostringstream oss;
oss << std::setprecision(float_prec_) << std::showpoint << f;
return oss.str();
}();
if(token.back() == '.') // 1. => 1.0
{
token += '0';
}
const auto e = std::find_if(token.cbegin(), token.cend(),
[](const char c) -> bool {
return c == 'E' || c == 'e';
});
if(e == token.cend())
{
return token; // there is no exponent part. just return it.
}
// zero-prefix in an exponent is not allowed in TOML.
// remove it if it exists.
bool sign_exists = false;
std::size_t zero_prefix = 0;
for(auto iter = std::next(e), iend = token.cend(); iter != iend; ++iter)
{
if(*iter == '+' || *iter == '-'){sign_exists = true; continue;}
if(*iter == '0'){zero_prefix += 1;}
else {break;}
}
if(zero_prefix != 0)
{
const auto offset = std::distance(token.cbegin(), e) +
(sign_exists ? 2 : 1);
token.erase(offset, zero_prefix);
}
return token;
}
std::string operator()(const string& s) const
{
if(s.kind == string_t::basic)
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend())
{
// if linefeed is contained, make it multiline-string.
const std::string open("\"\"\"\n");
const std::string close("\\\n\"\"\"");
return open + this->escape_ml_basic_string(s.str) + close;
}
// no linefeed. try to make it oneline-string.
std::string oneline = this->escape_basic_string(s.str);
if(oneline.size() + 2 < width_ || width_ < 2)
{
const std::string quote("\"");
return quote + oneline + quote;
}
// the line is too long compared to the specified width.
// split it into multiple lines.
std::string token("\"\"\"\n");
while(!oneline.empty())
{
if(oneline.size() < width_)
{
token += oneline;
oneline.clear();
}
else if(oneline.at(width_-2) == '\\')
{
token += oneline.substr(0, width_-2);
token += "\\\n";
oneline.erase(0, width_-2);
}
else
{
token += oneline.substr(0, width_-1);
token += "\\\n";
oneline.erase(0, width_-1);
}
}
return token + std::string("\\\n\"\"\"");
}
else // the string `s` is literal-string.
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() ||
std::find(s.str.cbegin(), s.str.cend(), '\'') != s.str.cend() )
{
const std::string open("'''\n");
const std::string close("'''");
return open + s.str + close;
}
else
{
const std::string quote("'");
return quote + s.str + quote;
}
}
}
std::string operator()(const local_date& d) const
{
std::ostringstream oss;
oss << d;
return oss.str();
}
std::string operator()(const local_time& t) const
{
std::ostringstream oss;
oss << t;
return oss.str();
}
std::string operator()(const local_datetime& dt) const
{
std::ostringstream oss;
oss << dt;
return oss.str();
}
std::string operator()(const offset_datetime& odt) const
{
std::ostringstream oss;
oss << odt;
return oss.str();
}
std::string operator()(const array& v) const
{
if(!v.empty() && v.front().is(value_t::Table))// v is an array of tables
{
// if it's not inlined, we need to add `[[table.key]]`.
// but if it can be inlined, we need `table.key = [...]`.
if(this->can_be_inlined_)
{
std::string token;
if(!keys_.empty())
{
token += this->serialize_key(keys_.back());
token += " = ";
}
bool width_exceeds = false;
token += "[\n";
for(const auto& item : v)
{
const auto t =
this->make_inline_table(item.cast<value_t::Table>());
if(t.size() + 1 > width_ || // +1 for the last comma {...},
std::find(t.cbegin(), t.cend(), '\n') != t.cend())
{
width_exceeds = true;
break;
}
token += t;
token += ",\n";
}
if(!width_exceeds)
{
token += "]\n";
return token;
}
// if width_exceeds, serialize it as [[array.of.tables]].
}
std::string token;
for(const auto& item : v)
{
token += "[[";
token += this->serialize_dotted_key(keys_);
token += "]]\n";
token += this->make_multiline_table(item.cast<value_t::Table>());
}
return token;
}
if(v.empty())
{
return std::string("[]");
}
// not an array of tables. normal array. first, try to make it inline.
{
const auto inl = this->make_inline_array(v);
if(inl.size() < this->width_ &&
std::find(inl.cbegin(), inl.cend(), '\n') == inl.cend())
{
return inl;
}
}
// if the length exceeds this->width_, print multiline array
std::string token;
std::string current_line;
token += "[\n";
for(const auto& item : v)
{
const auto next_elem = toml::visit(*this, item);
if(current_line.size() + next_elem.size() + 1 < this->width_)
{
current_line += next_elem;
current_line += ',';
}
else if(current_line.empty())
{
// the next elem cannot be within the width.
token += next_elem;
token += ",\n";
}
else
{
token += current_line;
token += ",\n";
current_line = next_elem;
}
}
token += "]\n";
return token;
}
std::string operator()(const table& v) const
{
if(this->can_be_inlined_)
{
std::string token;
if(!this->keys_.empty())
{
token += this->serialize_key(this->keys_.back());
token += " = ";
}
token += this->make_inline_table(v);
if(token.size() < this->width_)
{
return token;
}
}
std::string token;
if(!keys_.empty())
{
token += '[';
token += this->serialize_dotted_key(keys_);
token += "]\n";
}
token += this->make_multiline_table(v);
return token;
}
private:
std::string serialize_key(const toml::key& key) const
{
detail::location<toml::key> loc(key, key);
detail::lex_unquoted_key::invoke(loc);
if(loc.iter() == loc.end())
{
return key; // all the tokens are consumed. the key is unquoted-key.
}
std::string token("\"");
token += this->escape_basic_string(key);
token += "\"";
return token;
}
std::string serialize_dotted_key(const std::vector<toml::key>& keys) const
{
std::string token;
if(keys.empty()){return token;}
for(const auto& k : keys)
{
token += this->serialize_key(k);
token += '.';
}
token.erase(token.size() - 1, 1); // remove trailing `.`
return token;
}
std::string escape_basic_string(const std::string& s) const
{
//XXX assuming `s` is a valid utf-8 sequence.
std::string retval;
for(const char c : s)
{
switch(c)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\\n"; break;}
case '\r': {retval += "\\r"; break;}
default : {retval += c; break;}
}
}
return retval;
}
std::string escape_ml_basic_string(const std::string& s) const
{
std::string retval;
for(auto i=s.cbegin(), e=s.cend(); i!=e; ++i)
{
switch(*i)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\n"; break;}
case '\r':
{
if(std::next(i) != e && *std::next(i) == '\n')
{
retval += "\r\n";
++i;
}
else
{
retval += "\\r";
}
break;
}
default: {retval += *i; break;}
}
}
return retval;
}
std::string make_inline_array(const array& v) const
{
std::string token;
token += '[';
bool is_first = true;
for(const auto& item : v)
{
if(is_first) {is_first = false;} else {token += ',';}
token += visit(serializer(std::numeric_limits<std::size_t>::max(),
this->float_prec_, true), item);
}
token += ']';
return token;
}
std::string make_inline_table(const table& v) const
{
assert(this->can_be_inlined_);
std::string token;
token += '{';
bool is_first = true;
for(const auto& kv : v)
{
// in inline tables, trailing comma is not allowed (toml-lang #569).
if(is_first) {is_first = false;} else {token += ',';}
token += this->serialize_key(kv.first);
token += '=';
token += visit(serializer(std::numeric_limits<std::size_t>::max(),
this->float_prec_, true), kv.second);
}
token += '}';
return token;
}
std::string make_multiline_table(const table& v) const
{
std::string token;
// print non-table stuff first. because after printing [foo.bar], the
// remaining non-table values will be assigned into [foo.bar], not [foo]
for(const auto kv : v)
{
if(kv.second.is(value_t::Table) || is_array_of_tables(kv.second))
{
continue;
}
const auto key_and_sep = this->serialize_key(kv.first) + " = ";
const auto residual_width = this->width_ - key_and_sep.size();
token += key_and_sep;
token += visit(serializer(residual_width, this->float_prec_, true),
kv.second);
token += '\n';
}
// normal tables / array of tables
// after multiline table appeared, the other tables cannot be inline
// because the table would be assigned into the table.
// [foo]
// ...
// bar = {...} # <- bar will be a member of [foo].
bool multiline_table_printed = false;
for(const auto& kv : v)
{
if(!kv.second.is(value_t::Table) && !is_array_of_tables(kv.second))
{
continue; // other stuff are already serialized. skip them.
}
std::vector<toml::key> ks(this->keys_);
ks.push_back(kv.first);
auto tmp = visit(serializer(
this->width_, this->float_prec_, !multiline_table_printed, ks),
kv.second);
if((!multiline_table_printed) &&
std::find(tmp.cbegin(), tmp.cend(), '\n') != tmp.cend())
{
multiline_table_printed = true;
}
else
{
// still inline tables only.
tmp += '\n';
}
token += tmp;
}
return token;
}
bool is_array_of_tables(const value& v) const
{
if(!v.is(value_t::Array)) {return false;}
const auto& a = v.cast<value_t::Array>();
return !a.empty() && a.front().is(value_t::Table);
}
private:
bool can_be_inlined_;
int float_prec_;
std::size_t width_;
std::vector<toml::key> keys_;
};
inline std::string
format(const value& v, std::size_t w = 80,
int fprec = std::numeric_limits<toml::floating>::max_digits10)
{
return visit(serializer(w, fprec, true), v);
}
inline std::string
format(const table& t, std::size_t w = 80,
int fprec = std::numeric_limits<toml::floating>::max_digits10)
{
return serializer(w, fprec, true)(t);
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const value& v)
{
// get status of std::setw(). if the width is narrower than 5 chars, ignore.
const auto w = os.width();
const auto fprec = os.precision();
os << visit(serializer((w > 5 ? w : 80), fprec, false), v);
return os;
}
} // toml
#endif// TOML11_SERIALIZER_HPP
<commit_msg>fix: avoid width overflow<commit_after>// Copyright Toru Niina 2019.
// Distributed under the MIT License.
#ifndef TOML11_SERIALIZER_HPP
#define TOML11_SERIALIZER_HPP
#include "value.hpp"
#include "lexer.hpp"
#include <limits>
namespace toml
{
struct serializer
{
serializer(const std::size_t w = 80,
const int float_prec = std::numeric_limits<toml::floating>::max_digits10,
const bool can_be_inlined = false,
std::vector<toml::key> ks = {})
: can_be_inlined_(can_be_inlined), float_prec_(float_prec), width_(w),
keys_(std::move(ks))
{}
~serializer() = default;
std::string operator()(const toml::boolean& b) const
{
return b ? "true" : "false";
}
std::string operator()(const integer i) const
{
return std::to_string(i);
}
std::string operator()(const toml::floating f) const
{
std::string token = [=] {
// every float value needs decimal point (or exponent).
std::ostringstream oss;
oss << std::setprecision(float_prec_) << std::showpoint << f;
return oss.str();
}();
if(token.back() == '.') // 1. => 1.0
{
token += '0';
}
const auto e = std::find_if(token.cbegin(), token.cend(),
[](const char c) -> bool {
return c == 'E' || c == 'e';
});
if(e == token.cend())
{
return token; // there is no exponent part. just return it.
}
// zero-prefix in an exponent is not allowed in TOML.
// remove it if it exists.
bool sign_exists = false;
std::size_t zero_prefix = 0;
for(auto iter = std::next(e), iend = token.cend(); iter != iend; ++iter)
{
if(*iter == '+' || *iter == '-'){sign_exists = true; continue;}
if(*iter == '0'){zero_prefix += 1;}
else {break;}
}
if(zero_prefix != 0)
{
const auto offset = std::distance(token.cbegin(), e) +
(sign_exists ? 2 : 1);
token.erase(offset, zero_prefix);
}
return token;
}
std::string operator()(const string& s) const
{
if(s.kind == string_t::basic)
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend())
{
// if linefeed is contained, make it multiline-string.
const std::string open("\"\"\"\n");
const std::string close("\\\n\"\"\"");
return open + this->escape_ml_basic_string(s.str) + close;
}
// no linefeed. try to make it oneline-string.
std::string oneline = this->escape_basic_string(s.str);
if(oneline.size() + 2 < width_ || width_ < 2)
{
const std::string quote("\"");
return quote + oneline + quote;
}
// the line is too long compared to the specified width.
// split it into multiple lines.
std::string token("\"\"\"\n");
while(!oneline.empty())
{
if(oneline.size() < width_)
{
token += oneline;
oneline.clear();
}
else if(oneline.at(width_-2) == '\\')
{
token += oneline.substr(0, width_-2);
token += "\\\n";
oneline.erase(0, width_-2);
}
else
{
token += oneline.substr(0, width_-1);
token += "\\\n";
oneline.erase(0, width_-1);
}
}
return token + std::string("\\\n\"\"\"");
}
else // the string `s` is literal-string.
{
if(std::find(s.str.cbegin(), s.str.cend(), '\n') != s.str.cend() ||
std::find(s.str.cbegin(), s.str.cend(), '\'') != s.str.cend() )
{
const std::string open("'''\n");
const std::string close("'''");
return open + s.str + close;
}
else
{
const std::string quote("'");
return quote + s.str + quote;
}
}
}
std::string operator()(const local_date& d) const
{
std::ostringstream oss;
oss << d;
return oss.str();
}
std::string operator()(const local_time& t) const
{
std::ostringstream oss;
oss << t;
return oss.str();
}
std::string operator()(const local_datetime& dt) const
{
std::ostringstream oss;
oss << dt;
return oss.str();
}
std::string operator()(const offset_datetime& odt) const
{
std::ostringstream oss;
oss << odt;
return oss.str();
}
std::string operator()(const array& v) const
{
if(!v.empty() && v.front().is(value_t::Table))// v is an array of tables
{
// if it's not inlined, we need to add `[[table.key]]`.
// but if it can be inlined, we need `table.key = [...]`.
if(this->can_be_inlined_)
{
std::string token;
if(!keys_.empty())
{
token += this->serialize_key(keys_.back());
token += " = ";
}
bool width_exceeds = false;
token += "[\n";
for(const auto& item : v)
{
const auto t =
this->make_inline_table(item.cast<value_t::Table>());
if(t.size() + 1 > width_ || // +1 for the last comma {...},
std::find(t.cbegin(), t.cend(), '\n') != t.cend())
{
width_exceeds = true;
break;
}
token += t;
token += ",\n";
}
if(!width_exceeds)
{
token += "]\n";
return token;
}
// if width_exceeds, serialize it as [[array.of.tables]].
}
std::string token;
for(const auto& item : v)
{
token += "[[";
token += this->serialize_dotted_key(keys_);
token += "]]\n";
token += this->make_multiline_table(item.cast<value_t::Table>());
}
return token;
}
if(v.empty())
{
return std::string("[]");
}
// not an array of tables. normal array. first, try to make it inline.
{
const auto inl = this->make_inline_array(v);
if(inl.size() < this->width_ &&
std::find(inl.cbegin(), inl.cend(), '\n') == inl.cend())
{
return inl;
}
}
// if the length exceeds this->width_, print multiline array
std::string token;
std::string current_line;
token += "[\n";
for(const auto& item : v)
{
const auto next_elem = toml::visit(*this, item);
if(current_line.size() + next_elem.size() + 1 < this->width_)
{
current_line += next_elem;
current_line += ',';
}
else if(current_line.empty())
{
// the next elem cannot be within the width.
token += next_elem;
token += ",\n";
}
else
{
token += current_line;
token += ",\n";
current_line = next_elem;
}
}
token += "]\n";
return token;
}
std::string operator()(const table& v) const
{
if(this->can_be_inlined_)
{
std::string token;
if(!this->keys_.empty())
{
token += this->serialize_key(this->keys_.back());
token += " = ";
}
token += this->make_inline_table(v);
if(token.size() < this->width_)
{
return token;
}
}
std::string token;
if(!keys_.empty())
{
token += '[';
token += this->serialize_dotted_key(keys_);
token += "]\n";
}
token += this->make_multiline_table(v);
return token;
}
private:
std::string serialize_key(const toml::key& key) const
{
detail::location<toml::key> loc(key, key);
detail::lex_unquoted_key::invoke(loc);
if(loc.iter() == loc.end())
{
return key; // all the tokens are consumed. the key is unquoted-key.
}
std::string token("\"");
token += this->escape_basic_string(key);
token += "\"";
return token;
}
std::string serialize_dotted_key(const std::vector<toml::key>& keys) const
{
std::string token;
if(keys.empty()){return token;}
for(const auto& k : keys)
{
token += this->serialize_key(k);
token += '.';
}
token.erase(token.size() - 1, 1); // remove trailing `.`
return token;
}
std::string escape_basic_string(const std::string& s) const
{
//XXX assuming `s` is a valid utf-8 sequence.
std::string retval;
for(const char c : s)
{
switch(c)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\\n"; break;}
case '\r': {retval += "\\r"; break;}
default : {retval += c; break;}
}
}
return retval;
}
std::string escape_ml_basic_string(const std::string& s) const
{
std::string retval;
for(auto i=s.cbegin(), e=s.cend(); i!=e; ++i)
{
switch(*i)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\n"; break;}
case '\r':
{
if(std::next(i) != e && *std::next(i) == '\n')
{
retval += "\r\n";
++i;
}
else
{
retval += "\\r";
}
break;
}
default: {retval += *i; break;}
}
}
return retval;
}
std::string make_inline_array(const array& v) const
{
std::string token;
token += '[';
bool is_first = true;
for(const auto& item : v)
{
if(is_first) {is_first = false;} else {token += ',';}
token += visit(serializer(std::numeric_limits<std::size_t>::max(),
this->float_prec_, true), item);
}
token += ']';
return token;
}
std::string make_inline_table(const table& v) const
{
assert(this->can_be_inlined_);
std::string token;
token += '{';
bool is_first = true;
for(const auto& kv : v)
{
// in inline tables, trailing comma is not allowed (toml-lang #569).
if(is_first) {is_first = false;} else {token += ',';}
token += this->serialize_key(kv.first);
token += '=';
token += visit(serializer(std::numeric_limits<std::size_t>::max(),
this->float_prec_, true), kv.second);
}
token += '}';
return token;
}
std::string make_multiline_table(const table& v) const
{
std::string token;
// print non-table stuff first. because after printing [foo.bar], the
// remaining non-table values will be assigned into [foo.bar], not [foo]
for(const auto kv : v)
{
if(kv.second.is(value_t::Table) || is_array_of_tables(kv.second))
{
continue;
}
const auto key_and_sep = this->serialize_key(kv.first) + " = ";
const auto residual_width = (this->width_ > key_and_sep.size()) ?
this->width_ - key_and_sep.size() : 0;
token += key_and_sep;
token += visit(serializer(residual_width, this->float_prec_, true),
kv.second);
token += '\n';
}
// normal tables / array of tables
// after multiline table appeared, the other tables cannot be inline
// because the table would be assigned into the table.
// [foo]
// ...
// bar = {...} # <- bar will be a member of [foo].
bool multiline_table_printed = false;
for(const auto& kv : v)
{
if(!kv.second.is(value_t::Table) && !is_array_of_tables(kv.second))
{
continue; // other stuff are already serialized. skip them.
}
std::vector<toml::key> ks(this->keys_);
ks.push_back(kv.first);
auto tmp = visit(serializer(
this->width_, this->float_prec_, !multiline_table_printed, ks),
kv.second);
if((!multiline_table_printed) &&
std::find(tmp.cbegin(), tmp.cend(), '\n') != tmp.cend())
{
multiline_table_printed = true;
}
else
{
// still inline tables only.
tmp += '\n';
}
token += tmp;
}
return token;
}
bool is_array_of_tables(const value& v) const
{
if(!v.is(value_t::Array)) {return false;}
const auto& a = v.cast<value_t::Array>();
return !a.empty() && a.front().is(value_t::Table);
}
private:
bool can_be_inlined_;
int float_prec_;
std::size_t width_;
std::vector<toml::key> keys_;
};
inline std::string
format(const value& v, std::size_t w = 80,
int fprec = std::numeric_limits<toml::floating>::max_digits10)
{
return visit(serializer(w, fprec, true), v);
}
inline std::string
format(const table& t, std::size_t w = 80,
int fprec = std::numeric_limits<toml::floating>::max_digits10)
{
return serializer(w, fprec, true)(t);
}
template<typename charT, typename traits>
std::basic_ostream<charT, traits>&
operator<<(std::basic_ostream<charT, traits>& os, const value& v)
{
// get status of std::setw(). if the width is narrower than 5 chars, ignore.
const auto w = os.width();
const auto fprec = os.precision();
os << visit(serializer((w > 5 ? w : 80), fprec, false), v);
return os;
}
} // toml
#endif// TOML11_SERIALIZER_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This webpage shows layout of YV12 and other YUV formats
// http://www.fourcc.org/yuv.php
// The actual conversion is best described here
// http://en.wikipedia.org/wiki/YUV
// An article on optimizing YUV conversion using tables instead of multiplies
// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
//
// YV12 is a full plane of Y and a half height, half width chroma planes
// YV16 is a full plane of Y and a full height, half width chroma planes
//
// ARGB pixel format is output, which on little endian is stored as BGRA.
// The alpha is set to 255, allowing the application to use RGBA or RGB32.
#include "media/base/yuv_convert.h"
// Header for low level row functions.
#include "media/base/yuv_row.h"
#if USE_MMX
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <mmintrin.h>
#endif
#endif
#if USE_SSE || USE_MMX
#include <emmintrin.h>
#endif
namespace media {
// 16.16 fixed point arithmetic.
const int kFractionBits = 16;
const int kFractionMax = 1 << kFractionBits;
// Convert a frame of YUV to 32 bit ARGB.
void ConvertYUVToRGB32(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width,
int height,
int y_pitch,
int uv_pitch,
int rgb_pitch,
YUVType yuv_type) {
unsigned int y_shift = yuv_type;
for (int y = 0; y < height; ++y) {
uint8* rgb_row = rgb_buf + y * rgb_pitch;
const uint8* y_ptr = y_buf + y * y_pitch;
const uint8* u_ptr = u_buf + (y >> y_shift) * uv_pitch;
const uint8* v_ptr = v_buf + (y >> y_shift) * uv_pitch;
FastConvertYUVToRGB32Row(y_ptr,
u_ptr,
v_ptr,
rgb_row,
width);
}
// MMX used for FastConvertYUVToRGB32Row requires emms instruction.
EMMS();
}
#if USE_MMX
#if USE_SSE
// FilterRows combines two rows of the image using linear interpolation.
// SSE2 version blends 8 pixels at a time.
static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr,
int width, int scaled_y_fraction) {
__m128i zero = _mm_setzero_si128();
__m128i y1_fraction = _mm_set1_epi16(
static_cast<uint16>(scaled_y_fraction >> 8));
__m128i y0_fraction = _mm_set1_epi16(
static_cast<uint16>((scaled_y_fraction >> 8) ^ 255));
uint8* end = ybuf + width;
if (ybuf < end) {
do {
__m128i y0 = _mm_loadl_epi64(reinterpret_cast<__m128i const*>(y0_ptr));
__m128i y1 = _mm_loadl_epi64(reinterpret_cast<__m128i const*>(y1_ptr));
y0 = _mm_unpacklo_epi8(y0, zero);
y1 = _mm_unpacklo_epi8(y1, zero);
y0 = _mm_mullo_epi16(y0, y0_fraction);
y1 = _mm_mullo_epi16(y1, y1_fraction);
y0 = _mm_add_epi16(y0, y1); // 8.8 fixed point result
y0 = _mm_srli_epi16(y0, 8);
y0 = _mm_packus_epi16(y0, y0);
_mm_storel_epi64(reinterpret_cast<__m128i *>(ybuf), y0);
y0_ptr += 8;
y1_ptr += 8;
ybuf += 8;
} while (ybuf < end);
}
}
#else
// MMX version blends 4 pixels at a time.
static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr,
int width, int scaled_y_fraction) {
__m64 zero = _mm_setzero_si64();
__m64 y1_fraction = _mm_set1_pi16(
static_cast<int16>(scaled_y_fraction >> 8));
__m64 y0_fraction = _mm_set1_pi16(
static_cast<int16>((scaled_y_fraction >> 8) ^ 255));
uint8* end = ybuf + width;
if (ybuf < end) {
do {
__m64 y0 = _mm_cvtsi32_si64(*reinterpret_cast<const int *>(y0_ptr));
__m64 y1 = _mm_cvtsi32_si64(*reinterpret_cast<const int *>(y1_ptr));
y0 = _mm_unpacklo_pi8(y0, zero);
y1 = _mm_unpacklo_pi8(y1, zero);
y0 = _mm_mullo_pi16(y0, y0_fraction);
y1 = _mm_mullo_pi16(y1, y1_fraction);
y0 = _mm_add_pi16(y0, y1); // 8.8 fixed point result
y0 = _mm_srli_pi16(y0, 8);
y0 = _mm_packs_pu16(y0, y0);
*reinterpret_cast<int *>(ybuf) = _mm_cvtsi64_si32(y0);
y0_ptr += 4;
y1_ptr += 4;
ybuf += 4;
} while (ybuf < end);
}
}
#endif // USE_SSE
#else // no MMX or SSE
// C version blends 4 pixels at a time.
static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr,
int width, int scaled_y_fraction) {
int y0_fraction = 65535 - scaled_y_fraction;
int y1_fraction = scaled_y_fraction;
uint8* end = ybuf + width;
if (ybuf < end) {
do {
ybuf[0] = (y0_ptr[0] * (y0_fraction) + y1_ptr[0] * (y1_fraction)) >> 16;
ybuf[1] = (y0_ptr[1] * (y0_fraction) + y1_ptr[1] * (y1_fraction)) >> 16;
ybuf[2] = (y0_ptr[2] * (y0_fraction) + y1_ptr[2] * (y1_fraction)) >> 16;
ybuf[3] = (y0_ptr[3] * (y0_fraction) + y1_ptr[3] * (y1_fraction)) >> 16;
y0_ptr += 4;
y1_ptr += 4;
ybuf += 4;
} while (ybuf < end);
}
}
#endif // USE_MMX
// Scale a frame of YUV to 32 bit ARGB.
void ScaleYUVToRGB32(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width,
int height,
int scaled_width,
int scaled_height,
int y_pitch,
int uv_pitch,
int rgb_pitch,
YUVType yuv_type,
Rotate view_rotate,
ScaleFilter filter) {
const int kFilterBufferSize = 8192;
// Disable filtering if the screen is too big (to avoid buffer overflows).
// This should never happen to regular users: they don't have monitors
// wider than 8192 pixels.
if (width > kFilterBufferSize)
filter = FILTER_NONE;
unsigned int y_shift = yuv_type;
// Diagram showing origin and direction of source sampling.
// ->0 4<-
// 7 3
//
// 6 5
// ->1 2<-
// Rotations that start at right side of image.
if ((view_rotate == ROTATE_180) ||
(view_rotate == ROTATE_270) ||
(view_rotate == MIRROR_ROTATE_0) ||
(view_rotate == MIRROR_ROTATE_90)) {
y_buf += width - 1;
u_buf += width / 2 - 1;
v_buf += width / 2 - 1;
width = -width;
}
// Rotations that start at bottom of image.
if ((view_rotate == ROTATE_90) ||
(view_rotate == ROTATE_180) ||
(view_rotate == MIRROR_ROTATE_90) ||
(view_rotate == MIRROR_ROTATE_180)) {
y_buf += (height - 1) * y_pitch;
u_buf += ((height >> y_shift) - 1) * uv_pitch;
v_buf += ((height >> y_shift) - 1) * uv_pitch;
height = -height;
}
// Handle zero sized destination.
if (scaled_width == 0 || scaled_height == 0)
return;
int scaled_dx = width * kFractionMax / scaled_width;
int scaled_dy = height * kFractionMax / scaled_height;
int scaled_dx_uv = scaled_dx;
if ((view_rotate == ROTATE_90) ||
(view_rotate == ROTATE_270)) {
int tmp = scaled_height;
scaled_height = scaled_width;
scaled_width = tmp;
tmp = height;
height = width;
width = tmp;
int original_dx = scaled_dx;
int original_dy = scaled_dy;
scaled_dx = ((original_dy >> kFractionBits) * y_pitch) << kFractionBits;
scaled_dx_uv = ((original_dy >> kFractionBits) * uv_pitch) << kFractionBits;
scaled_dy = original_dx;
if (view_rotate == ROTATE_90) {
y_pitch = -1;
uv_pitch = -1;
height = -height;
} else {
y_pitch = 1;
uv_pitch = 1;
}
}
// Need padding because FilterRows() may write up to 15 extra pixels
// after the end for SSE2 version.
uint8 ybuf[kFilterBufferSize + 16];
uint8 ubuf[kFilterBufferSize / 2 + 16];
uint8 vbuf[kFilterBufferSize / 2 + 16];
int yscale_fixed = (height << kFractionBits) / scaled_height;
for (int y = 0; y < scaled_height; ++y) {
uint8* dest_pixel = rgb_buf + y * rgb_pitch;
int scaled_y = (y * yscale_fixed);
const uint8* y0_ptr = y_buf + (scaled_y >> kFractionBits) * y_pitch;
const uint8* y1_ptr = y0_ptr + y_pitch;
const uint8* u0_ptr = u_buf +
((scaled_y >> kFractionBits) >> y_shift) * uv_pitch;
const uint8* u1_ptr = u0_ptr + uv_pitch;
const uint8* v0_ptr = v_buf +
((scaled_y >> kFractionBits) >> y_shift) * uv_pitch;
const uint8* v1_ptr = v0_ptr + uv_pitch;
int scaled_y_fraction = scaled_y & (kFractionMax - 1);
int scaled_uv_fraction = (scaled_y >> y_shift) & (kFractionMax - 1);
const uint8* y_ptr = y0_ptr;
const uint8* u_ptr = u0_ptr;
const uint8* v_ptr = v0_ptr;
// Apply vertical filtering if necessary.
if (filter == media::FILTER_BILINEAR && yscale_fixed != kFractionMax) {
if (scaled_y_fraction && ((y + 1) < scaled_height)) {
FilterRows(ybuf, y0_ptr, y1_ptr, width, scaled_y_fraction);
y_ptr = ybuf;
}
if (scaled_uv_fraction &&
(((y >> y_shift) + 1) < (scaled_height >> y_shift))) {
FilterRows(ubuf, u0_ptr, u1_ptr, (width + 1) / 2, scaled_uv_fraction);
u_ptr = ubuf;
FilterRows(vbuf, v0_ptr, v1_ptr, (width + 1) / 2, scaled_uv_fraction);
v_ptr = vbuf;
}
}
if (scaled_dx == kFractionMax) { // Not scaled
FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, scaled_width);
} else {
if (filter == FILTER_BILINEAR)
LinearScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, scaled_width, scaled_dx);
else
ScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, scaled_width, scaled_dx);
}
}
// MMX used for FastConvertYUVToRGB32Row requires emms instruction.
EMMS();
}
} // namespace media
<commit_msg>YUV scale clamp horizontal pixels when filtering BUG=19113 TEST=scale up by 4x and watch right edge for texel wrap.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This webpage shows layout of YV12 and other YUV formats
// http://www.fourcc.org/yuv.php
// The actual conversion is best described here
// http://en.wikipedia.org/wiki/YUV
// An article on optimizing YUV conversion using tables instead of multiplies
// http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
//
// YV12 is a full plane of Y and a half height, half width chroma planes
// YV16 is a full plane of Y and a full height, half width chroma planes
//
// ARGB pixel format is output, which on little endian is stored as BGRA.
// The alpha is set to 255, allowing the application to use RGBA or RGB32.
#include "media/base/yuv_convert.h"
// Header for low level row functions.
#include "media/base/yuv_row.h"
#if USE_MMX
#if defined(_MSC_VER)
#include <intrin.h>
#else
#include <mmintrin.h>
#endif
#endif
#if USE_SSE || USE_MMX
#include <emmintrin.h>
#endif
namespace media {
// 16.16 fixed point arithmetic.
const int kFractionBits = 16;
const int kFractionMax = 1 << kFractionBits;
// Convert a frame of YUV to 32 bit ARGB.
void ConvertYUVToRGB32(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width,
int height,
int y_pitch,
int uv_pitch,
int rgb_pitch,
YUVType yuv_type) {
unsigned int y_shift = yuv_type;
for (int y = 0; y < height; ++y) {
uint8* rgb_row = rgb_buf + y * rgb_pitch;
const uint8* y_ptr = y_buf + y * y_pitch;
const uint8* u_ptr = u_buf + (y >> y_shift) * uv_pitch;
const uint8* v_ptr = v_buf + (y >> y_shift) * uv_pitch;
FastConvertYUVToRGB32Row(y_ptr,
u_ptr,
v_ptr,
rgb_row,
width);
}
// MMX used for FastConvertYUVToRGB32Row requires emms instruction.
EMMS();
}
#if USE_MMX
#if USE_SSE
// FilterRows combines two rows of the image using linear interpolation.
// SSE2 version blends 8 pixels at a time.
static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr,
int width, int scaled_y_fraction) {
__m128i zero = _mm_setzero_si128();
__m128i y1_fraction = _mm_set1_epi16(
static_cast<uint16>(scaled_y_fraction >> 8));
__m128i y0_fraction = _mm_set1_epi16(
static_cast<uint16>((scaled_y_fraction >> 8) ^ 255));
uint8* end = ybuf + width;
if (ybuf < end) {
do {
__m128i y0 = _mm_loadl_epi64(reinterpret_cast<__m128i const*>(y0_ptr));
__m128i y1 = _mm_loadl_epi64(reinterpret_cast<__m128i const*>(y1_ptr));
y0 = _mm_unpacklo_epi8(y0, zero);
y1 = _mm_unpacklo_epi8(y1, zero);
y0 = _mm_mullo_epi16(y0, y0_fraction);
y1 = _mm_mullo_epi16(y1, y1_fraction);
y0 = _mm_add_epi16(y0, y1); // 8.8 fixed point result
y0 = _mm_srli_epi16(y0, 8);
y0 = _mm_packus_epi16(y0, y0);
_mm_storel_epi64(reinterpret_cast<__m128i *>(ybuf), y0);
y0_ptr += 8;
y1_ptr += 8;
ybuf += 8;
} while (ybuf < end);
}
}
#else
// MMX version blends 4 pixels at a time.
static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr,
int width, int scaled_y_fraction) {
__m64 zero = _mm_setzero_si64();
__m64 y1_fraction = _mm_set1_pi16(
static_cast<int16>(scaled_y_fraction >> 8));
__m64 y0_fraction = _mm_set1_pi16(
static_cast<int16>((scaled_y_fraction >> 8) ^ 255));
uint8* end = ybuf + width;
if (ybuf < end) {
do {
__m64 y0 = _mm_cvtsi32_si64(*reinterpret_cast<const int *>(y0_ptr));
__m64 y1 = _mm_cvtsi32_si64(*reinterpret_cast<const int *>(y1_ptr));
y0 = _mm_unpacklo_pi8(y0, zero);
y1 = _mm_unpacklo_pi8(y1, zero);
y0 = _mm_mullo_pi16(y0, y0_fraction);
y1 = _mm_mullo_pi16(y1, y1_fraction);
y0 = _mm_add_pi16(y0, y1); // 8.8 fixed point result
y0 = _mm_srli_pi16(y0, 8);
y0 = _mm_packs_pu16(y0, y0);
*reinterpret_cast<int *>(ybuf) = _mm_cvtsi64_si32(y0);
y0_ptr += 4;
y1_ptr += 4;
ybuf += 4;
} while (ybuf < end);
}
}
#endif // USE_SSE
#else // no MMX or SSE
// C version blends 4 pixels at a time.
static void FilterRows(uint8* ybuf, const uint8* y0_ptr, const uint8* y1_ptr,
int width, int scaled_y_fraction) {
int y0_fraction = 65536 - scaled_y_fraction;
int y1_fraction = scaled_y_fraction;
uint8* end = ybuf + width;
if (ybuf < end) {
do {
ybuf[0] = (y0_ptr[0] * (y0_fraction) + y1_ptr[0] * (y1_fraction)) >> 16;
ybuf[1] = (y0_ptr[1] * (y0_fraction) + y1_ptr[1] * (y1_fraction)) >> 16;
ybuf[2] = (y0_ptr[2] * (y0_fraction) + y1_ptr[2] * (y1_fraction)) >> 16;
ybuf[3] = (y0_ptr[3] * (y0_fraction) + y1_ptr[3] * (y1_fraction)) >> 16;
y0_ptr += 4;
y1_ptr += 4;
ybuf += 4;
} while (ybuf < end);
}
}
#endif // USE_MMX
// Scale a frame of YUV to 32 bit ARGB.
void ScaleYUVToRGB32(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width,
int height,
int scaled_width,
int scaled_height,
int y_pitch,
int uv_pitch,
int rgb_pitch,
YUVType yuv_type,
Rotate view_rotate,
ScaleFilter filter) {
const int kFilterBufferSize = 8192;
// Disable filtering if the screen is too big (to avoid buffer overflows).
// This should never happen to regular users: they don't have monitors
// wider than 8192 pixels.
if (width > kFilterBufferSize)
filter = FILTER_NONE;
unsigned int y_shift = yuv_type;
// Diagram showing origin and direction of source sampling.
// ->0 4<-
// 7 3
//
// 6 5
// ->1 2<-
// Rotations that start at right side of image.
if ((view_rotate == ROTATE_180) ||
(view_rotate == ROTATE_270) ||
(view_rotate == MIRROR_ROTATE_0) ||
(view_rotate == MIRROR_ROTATE_90)) {
y_buf += width - 1;
u_buf += width / 2 - 1;
v_buf += width / 2 - 1;
width = -width;
}
// Rotations that start at bottom of image.
if ((view_rotate == ROTATE_90) ||
(view_rotate == ROTATE_180) ||
(view_rotate == MIRROR_ROTATE_90) ||
(view_rotate == MIRROR_ROTATE_180)) {
y_buf += (height - 1) * y_pitch;
u_buf += ((height >> y_shift) - 1) * uv_pitch;
v_buf += ((height >> y_shift) - 1) * uv_pitch;
height = -height;
}
// Handle zero sized destination.
if (scaled_width == 0 || scaled_height == 0)
return;
int scaled_dx = width * kFractionMax / scaled_width;
int scaled_dy = height * kFractionMax / scaled_height;
int scaled_dx_uv = scaled_dx;
if ((view_rotate == ROTATE_90) ||
(view_rotate == ROTATE_270)) {
int tmp = scaled_height;
scaled_height = scaled_width;
scaled_width = tmp;
tmp = height;
height = width;
width = tmp;
int original_dx = scaled_dx;
int original_dy = scaled_dy;
scaled_dx = ((original_dy >> kFractionBits) * y_pitch) << kFractionBits;
scaled_dx_uv = ((original_dy >> kFractionBits) * uv_pitch) << kFractionBits;
scaled_dy = original_dx;
if (view_rotate == ROTATE_90) {
y_pitch = -1;
uv_pitch = -1;
height = -height;
} else {
y_pitch = 1;
uv_pitch = 1;
}
}
// Need padding because FilterRows() may write up to 15 extra pixels
// after the end for SSE2 version.
uint8 ybuf[kFilterBufferSize + 16];
uint8 ubuf[kFilterBufferSize / 2 + 16];
uint8 vbuf[kFilterBufferSize / 2 + 16];
int yscale_fixed = (height << kFractionBits) / scaled_height;
for (int y = 0; y < scaled_height; ++y) {
uint8* dest_pixel = rgb_buf + y * rgb_pitch;
int scaled_y = (y * yscale_fixed);
const uint8* y0_ptr = y_buf + (scaled_y >> kFractionBits) * y_pitch;
const uint8* y1_ptr = y0_ptr + y_pitch;
const uint8* u0_ptr = u_buf +
((scaled_y >> kFractionBits) >> y_shift) * uv_pitch;
const uint8* u1_ptr = u0_ptr + uv_pitch;
const uint8* v0_ptr = v_buf +
((scaled_y >> kFractionBits) >> y_shift) * uv_pitch;
const uint8* v1_ptr = v0_ptr + uv_pitch;
int scaled_y_fraction = scaled_y & (kFractionMax - 1);
int scaled_uv_fraction = (scaled_y >> y_shift) & (kFractionMax - 1);
const uint8* y_ptr = y0_ptr;
const uint8* u_ptr = u0_ptr;
const uint8* v_ptr = v0_ptr;
// Apply vertical filtering if necessary.
// TODO(fbarchard): Remove memcpy when not necessary.
if (filter == media::FILTER_BILINEAR) {
if (yscale_fixed != kFractionMax &&
scaled_y_fraction && ((y + 1) < scaled_height)) {
FilterRows(ybuf, y0_ptr, y1_ptr, width, scaled_y_fraction);
} else {
memcpy(ybuf, y0_ptr, width);
}
y_ptr = ybuf;
ybuf[width] = ybuf[width-1];
int uv_width = (width + 1) / 2;
if (yscale_fixed != kFractionMax &&
scaled_uv_fraction &&
(((y >> y_shift) + 1) < (scaled_height >> y_shift))) {
FilterRows(ubuf, u0_ptr, u1_ptr, uv_width, scaled_uv_fraction);
FilterRows(vbuf, v0_ptr, v1_ptr, uv_width, scaled_uv_fraction);
} else {
memcpy(ubuf, u0_ptr, uv_width);
memcpy(vbuf, v0_ptr, uv_width);
}
u_ptr = ubuf;
v_ptr = vbuf;
ubuf[(width + 1) / 2] = ybuf[(width + 1) / 2 -1];
vbuf[(width + 1) / 2] = vbuf[(width + 1) / 2 -1];
}
if (scaled_dx == kFractionMax) { // Not scaled
FastConvertYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, scaled_width);
} else {
if (filter == FILTER_BILINEAR)
LinearScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, scaled_width, scaled_dx);
else
ScaleYUVToRGB32Row(y_ptr, u_ptr, v_ptr,
dest_pixel, scaled_width, scaled_dx);
}
}
// MMX used for FastConvertYUVToRGB32Row requires emms instruction.
EMMS();
}
} // namespace media
<|endoftext|>
|
<commit_before>/*
* Animated GIFs Display Code for SmartMatrix and 32x32 RGB LED Panels
*
* This file contains code to decompress the LZW encoded animated GIF data
*
* Written by: Craig A. Lindley, Fabrice Bellard and Steven A. Bennett
* See my book, "Practical Image Processing in C", John Wiley & Sons, Inc.
*
* Copyright (c) 2014 Craig A. Lindley
* Minor modifications by Louis Beaudoin (pixelmatix)
*
* 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 DEBUG 0
#include <Arduino.h>
#include "GIFDecoder.h"
// LZW constants
// NOTE: LZW_MAXBITS set to 11 (initially 10) to support more GIFs with 6k RAM increase
#define LZW_MAXBITS 12
#define LZW_SIZTABLE (1 << LZW_MAXBITS)
// Masks for 0 .. 16 bits
unsigned int mask[17] = {
0x0000, 0x0001, 0x0003, 0x0007,
0x000F, 0x001F, 0x003F, 0x007F,
0x00FF, 0x01FF, 0x03FF, 0x07FF,
0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF,
0xFFFF
};
// LZW variables
int bbits;
int bbuf;
int cursize; // The current code size
int curmask;
int codesize;
int clear_code;
int end_code;
int newcodes; // First available code
int top_slot; // Highest code for current size
int extra_slot;
int slot; // Last read code
int fc, oc;
int bs; // Current buffer size for GIF
byte *sp;
get_byte_callback getByteCallback;
#if USE_EXTERNAL_BUFFERS == 0
byte stack [LZW_SIZTABLE];
byte suffix [LZW_SIZTABLE];
uint16_t prefix [LZW_SIZTABLE];
#else
// buffers need to be size LZW_SIZTABLE
byte * stack;
byte * suffix;
uint16_t * prefix;
get_buffer_callback getStackCallback;
get_buffer_callback getSuffixCallback;
get_buffer_callback getPrefixCallback;
void setGetStackCallback(get_buffer_callback f) {
getStackCallback = f;
}
void setGetSuffixCallback(get_buffer_callback f) {
getSuffixCallback = f;
}
void setGetPrefixCallback(get_buffer_callback f) {
getPrefixCallback = f;
}
#endif
// Initialize LZW decoder
// csize initial code size in bits
// buf input data
void lzw_decode_init (int csize, get_byte_callback f) {
getByteCallback = f;
#if USE_EXTERNAL_BUFFERS == 1
stack = (byte *)(*getStackCallback)();
suffix = (byte *)(*getSuffixCallback)();
prefix = (uint16_t *)(*getPrefixCallback)();
#endif
// Initialize read buffer variables
bbuf = 0;
bbits = 0;
bs = 0;
// Initialize decoder variables
codesize = csize;
cursize = codesize + 1;
curmask = mask[cursize];
top_slot = 1 << cursize;
clear_code = 1 << codesize;
end_code = clear_code + 1;
slot = newcodes = clear_code + 2;
oc = fc = -1;
sp = stack;
}
// Get one code of given number of bits from stream
int lzw_get_code() {
while (bbits < cursize) {
if (!bs) {
bs = (*getByteCallback)();
}
bbuf |= (*getByteCallback)() << bbits;
bbits += 8;
bs--;
}
int c = bbuf;
bbuf >>= cursize;
bbits -= cursize;
return c & curmask;
}
// Decode given number of bytes
// buf 8 bit output buffer
// len number of pixels to decode
// returns the number of bytes decoded
int lzw_decode(byte *buf, int len) {
int l, c, code;
unsigned char debugMessagePrinted = 0;
if (end_code < 0) {
return 0;
}
l = len;
for (;;) {
while (sp > stack) {
*buf++ = *(--sp);
if ((--l) == 0) {
return len;
}
}
c = lzw_get_code();
if (c == end_code) {
break;
}
else if (c == clear_code) {
cursize = codesize + 1;
curmask = mask[cursize];
slot = newcodes;
top_slot = 1 << cursize;
fc= oc= -1;
}
else {
code = c;
if ((code == slot) && (fc >= 0)) {
*sp++ = fc;
code = oc;
}
else if (code >= slot) {
break;
}
while (code >= newcodes) {
*sp++ = suffix[code];
code = prefix[code];
}
*sp++ = code;
if ((slot < top_slot) && (oc >= 0)) {
suffix[slot] = code;
prefix[slot++] = oc;
}
fc = code;
oc = c;
if (slot >= top_slot) {
if (cursize < LZW_MAXBITS) {
top_slot <<= 1;
curmask = mask[++cursize];
} else {
#if DEBUG == 1
if(!debugMessagePrinted) {
debugMessagePrinted = 1;
Serial.println("****** cursize >= MAXBITS *******");
}
#endif
}
}
}
}
end_code = -1;
return len - l;
}
<commit_msg>Add note on LZW_MAXBITS settings<commit_after>/*
* Animated GIFs Display Code for SmartMatrix and 32x32 RGB LED Panels
*
* This file contains code to decompress the LZW encoded animated GIF data
*
* Written by: Craig A. Lindley, Fabrice Bellard and Steven A. Bennett
* See my book, "Practical Image Processing in C", John Wiley & Sons, Inc.
*
* Copyright (c) 2014 Craig A. Lindley
* Minor modifications by Louis Beaudoin (pixelmatix)
*
* 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 DEBUG 0
#include <Arduino.h>
#include "GIFDecoder.h"
// LZW constants
// NOTE: LZW_MAXBITS should be set to 10 or 11 for small displays, 12 for large displays
// all 32x32-pixel GIFs tested work with 11, most work with 10
// LZW_MAXBITS = 12 will support all GIFs, but takes 16kB RAM
#define LZW_MAXBITS 12
#define LZW_SIZTABLE (1 << LZW_MAXBITS)
// Masks for 0 .. 16 bits
unsigned int mask[17] = {
0x0000, 0x0001, 0x0003, 0x0007,
0x000F, 0x001F, 0x003F, 0x007F,
0x00FF, 0x01FF, 0x03FF, 0x07FF,
0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF,
0xFFFF
};
// LZW variables
int bbits;
int bbuf;
int cursize; // The current code size
int curmask;
int codesize;
int clear_code;
int end_code;
int newcodes; // First available code
int top_slot; // Highest code for current size
int extra_slot;
int slot; // Last read code
int fc, oc;
int bs; // Current buffer size for GIF
byte *sp;
get_byte_callback getByteCallback;
#if USE_EXTERNAL_BUFFERS == 0
byte stack [LZW_SIZTABLE];
byte suffix [LZW_SIZTABLE];
uint16_t prefix [LZW_SIZTABLE];
#else
// buffers need to be size LZW_SIZTABLE
byte * stack;
byte * suffix;
uint16_t * prefix;
get_buffer_callback getStackCallback;
get_buffer_callback getSuffixCallback;
get_buffer_callback getPrefixCallback;
void setGetStackCallback(get_buffer_callback f) {
getStackCallback = f;
}
void setGetSuffixCallback(get_buffer_callback f) {
getSuffixCallback = f;
}
void setGetPrefixCallback(get_buffer_callback f) {
getPrefixCallback = f;
}
#endif
// Initialize LZW decoder
// csize initial code size in bits
// buf input data
void lzw_decode_init (int csize, get_byte_callback f) {
getByteCallback = f;
#if USE_EXTERNAL_BUFFERS == 1
stack = (byte *)(*getStackCallback)();
suffix = (byte *)(*getSuffixCallback)();
prefix = (uint16_t *)(*getPrefixCallback)();
#endif
// Initialize read buffer variables
bbuf = 0;
bbits = 0;
bs = 0;
// Initialize decoder variables
codesize = csize;
cursize = codesize + 1;
curmask = mask[cursize];
top_slot = 1 << cursize;
clear_code = 1 << codesize;
end_code = clear_code + 1;
slot = newcodes = clear_code + 2;
oc = fc = -1;
sp = stack;
}
// Get one code of given number of bits from stream
int lzw_get_code() {
while (bbits < cursize) {
if (!bs) {
bs = (*getByteCallback)();
}
bbuf |= (*getByteCallback)() << bbits;
bbits += 8;
bs--;
}
int c = bbuf;
bbuf >>= cursize;
bbits -= cursize;
return c & curmask;
}
// Decode given number of bytes
// buf 8 bit output buffer
// len number of pixels to decode
// returns the number of bytes decoded
int lzw_decode(byte *buf, int len) {
int l, c, code;
unsigned char debugMessagePrinted = 0;
if (end_code < 0) {
return 0;
}
l = len;
for (;;) {
while (sp > stack) {
*buf++ = *(--sp);
if ((--l) == 0) {
return len;
}
}
c = lzw_get_code();
if (c == end_code) {
break;
}
else if (c == clear_code) {
cursize = codesize + 1;
curmask = mask[cursize];
slot = newcodes;
top_slot = 1 << cursize;
fc= oc= -1;
}
else {
code = c;
if ((code == slot) && (fc >= 0)) {
*sp++ = fc;
code = oc;
}
else if (code >= slot) {
break;
}
while (code >= newcodes) {
*sp++ = suffix[code];
code = prefix[code];
}
*sp++ = code;
if ((slot < top_slot) && (oc >= 0)) {
suffix[slot] = code;
prefix[slot++] = oc;
}
fc = code;
oc = c;
if (slot >= top_slot) {
if (cursize < LZW_MAXBITS) {
top_slot <<= 1;
curmask = mask[++cursize];
} else {
#if DEBUG == 1
if(!debugMessagePrinted) {
debugMessagePrinted = 1;
Serial.println("****** cursize >= MAXBITS *******");
}
#endif
}
}
}
}
end_code = -1;
return len - l;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Copyright (C) 2011-2013 Michael Krufky
*
* Author: Michael Krufky <mkrufky@linuxtv.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "feed.h"
#include "linuxtv_tuner.h"
#include "serve.h"
#include "atsctext.h"
typedef std::map<uint8_t, tune> map_tuners;
struct dvbtee_context
{
linuxtv_tuner tuner;
serve *server;
};
typedef std::map<pid_t, struct dvbtee_context*> map_pid_to_context;
map_pid_to_context context_map;
void stop_server(struct dvbtee_context* context);
void cleanup(struct dvbtee_context* context, bool quick = false)
{
if (context->server)
stop_server(context);
if (quick) {
context->tuner.feeder.stop_without_wait();
context->tuner.feeder.close_file();
} else {
context->tuner.stop_feed();
}
context->tuner.close_fe();
#if 1 /* FIXME */
ATSCMultipleStringsDeInit();
#endif
}
void signal_callback_handler(int signum)
{
struct dvbtee_context* context = context_map[getpid()];
bool signal_dbg = true;
const char *signal_desc;
switch (signum) {
case SIGINT: /* Program interrupt. (ctrl-c) */
signal_desc = "SIGINT";
signal_dbg = false;
break;
case SIGABRT: /* Process detects error and reports by calling abort */
signal_desc = "SIGABRT";
break;
case SIGFPE: /* Floating-Point arithmetic Exception */
signal_desc = "SIGFPE";
break;
case SIGILL: /* Illegal Instruction */
signal_desc = "SIGILL";
break;
case SIGSEGV: /* Segmentation Violation */
signal_desc = "SIGSEGV";
break;
case SIGTERM: /* Termination */
signal_desc = "SIGTERM";
break;
case SIGHUP: /* Hangup */
signal_desc = "SIGHUP";
break;
default:
signal_desc = "UNKNOWN";
break;
}
if (signal_dbg)
fprintf(stderr, "%s: caught signal %d: %s\n", __func__, signum, signal_desc);
cleanup(context, true);
context->tuner.feeder.parser.cleanup();
exit(signum);
}
void stop_server(struct dvbtee_context* context)
{
if (!context->server)
return;
context->server->stop();
delete context->server;
context->server = NULL;
return;
}
int start_server(struct dvbtee_context* context, unsigned int flags, int port, int eavesdropping_port = 0)
{
context->server = new serve;
context->server->add_tuner(&context->tuner);
if (eavesdropping_port)
context->tuner.feeder.parser.out.add_http_server(eavesdropping_port);
context->server->set_scan_flags(0, flags);
return context->server->start(port);
}
//FIXME: we return const char * for no reason - this will be converted to bool, int or void
const char * chandump(void *context, parsed_channel_info_t *c)
{
char channelno[7]; /* XXX.XXX */
if (c->major + c->minor > 1)
sprintf(channelno, "%d.%d", c->major, c->minor);
else if (c->lcn)
sprintf(channelno, "%d", c->lcn);
else
sprintf(channelno, "%d", c->physical_channel);
/* xine format */
fprintf(stdout, "%s-%s:%d:%s:%d:%d:%d\n",
channelno,
c->service_name,
c->freq,//iter_vct->second.carrier_freq,
c->modulation,
c->vpid, c->apid, c->program_number);
/* link to http stream */
fprintf(stdout, "<a href='/tune=%d+%d&stream/here'>%s: %s</a>",
c->physical_channel, c->program_number, channelno, c->service_name);
return NULL;
}
bool list_channels(serve *server)
{
if (!server)
return false;
return server->get_channels(chandump, NULL);
}
bool start_async_channel_scan(serve *server, unsigned int flags = 0)
{
server->scan(flags);
}
bool channel_scan_and_dump(serve *server, unsigned int flags = 0)
{
server->scan(flags, chandump, NULL);
}
void epg_header_footer(void *context, bool header, bool channel)
{
const char *noun = (channel) ? "channel" : "epg table";
const char *adj = (header) ? "start" : "end";
fprintf(stdout, "receiving %s of %s\n", adj, noun);
}
void epg_event(void *context, decoded_event_t *e)
{
fprintf(stdout, "received event id: %d on channel name: %s, major: %d, minor: %d, physical: %d, service id: %d, title: %s, desc: %s, start time (time_t) %ld, duration (sec) %d\n",
e->event_id, e->channel_name, e->chan_major, e->chan_minor, e->chan_physical, e->chan_svc_id, e->name, e->text, e->start_time, e->length_sec);
}
bool request_epg(serve *server)
{
if (!server)
return false;
return server->get_epg(epg_header_footer, epg_event, NULL);
}
int main(int argc, char **argv)
{
int opt;
dvbtee_context context;
context.server = NULL;
/* LinuxDVB context: */
int dvb_adap = 0; /* ID X, /dev/dvb/adapterX/ */
int demux_id = 0; /* ID Y, /dev/dvb/adapterX/demuxY */
int dvr_id = 0; /* ID Y, /dev/dvb/adapterX/dvrY */
int fe_id = 0; /* ID Y, /dev/dvb/adapterX/frontendY */
unsigned int serv_flags = 0;
unsigned int scan_flags = 0;
while ((opt = getopt(argc, argv, "a:A:f:d::")) != -1) {
switch (opt) {
case 'a': /* adapter */
dvb_adap = strtoul(optarg, NULL, 0);
break;
case 'A': /* ATSC / QAM */
scan_flags = strtoul(optarg, NULL, 0);
break;
case 'f': /* frontend */
fe_id = strtoul(optarg, NULL, 0);
break;
case 'd':
if (optarg)
libdvbtee_set_debug_level(strtoul(optarg, NULL, 0));
else
libdvbtee_set_debug_level(255);
break;
default: /* bad cmd line option */
return -1;
}
}
context_map[getpid()] = &context;
signal(SIGINT, signal_callback_handler); /* Program interrupt. (ctrl-c) */
signal(SIGABRT, signal_callback_handler); /* Process detects error and reports by calling abort */
signal(SIGFPE, signal_callback_handler); /* Floating-Point arithmetic Exception */
signal(SIGILL, signal_callback_handler); /* Illegal Instruction */
signal(SIGSEGV, signal_callback_handler); /* Segmentation Violation */
signal(SIGTERM, signal_callback_handler); /* Termination */
signal(SIGHUP, signal_callback_handler); /* Hangup */
#if 1 /* FIXME */
ATSCMultipleStringsInit();
#endif
context.tuner.set_device_ids(dvb_adap, fe_id, demux_id, dvr_id, false);
context.tuner.feeder.parser.limit_eit(-1);
start_server(&context, scan_flags, 62080, 62081);
if (context.server) {
while (context.server->is_running()) sleep(1);
stop_server(&context);
}
// cleanup(&context);
#if 1 /* FIXME */
ATSCMultipleStringsDeInit();
#endif
return 0;
}
<commit_msg>server_example: fix warning: no return statement in function returning non-void [-Wreturn-type]<commit_after>/*****************************************************************************
* Copyright (C) 2011-2013 Michael Krufky
*
* Author: Michael Krufky <mkrufky@linuxtv.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <errno.h>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "feed.h"
#include "linuxtv_tuner.h"
#include "serve.h"
#include "atsctext.h"
typedef std::map<uint8_t, tune> map_tuners;
struct dvbtee_context
{
linuxtv_tuner tuner;
serve *server;
};
typedef std::map<pid_t, struct dvbtee_context*> map_pid_to_context;
map_pid_to_context context_map;
void stop_server(struct dvbtee_context* context);
void cleanup(struct dvbtee_context* context, bool quick = false)
{
if (context->server)
stop_server(context);
if (quick) {
context->tuner.feeder.stop_without_wait();
context->tuner.feeder.close_file();
} else {
context->tuner.stop_feed();
}
context->tuner.close_fe();
#if 1 /* FIXME */
ATSCMultipleStringsDeInit();
#endif
}
void signal_callback_handler(int signum)
{
struct dvbtee_context* context = context_map[getpid()];
bool signal_dbg = true;
const char *signal_desc;
switch (signum) {
case SIGINT: /* Program interrupt. (ctrl-c) */
signal_desc = "SIGINT";
signal_dbg = false;
break;
case SIGABRT: /* Process detects error and reports by calling abort */
signal_desc = "SIGABRT";
break;
case SIGFPE: /* Floating-Point arithmetic Exception */
signal_desc = "SIGFPE";
break;
case SIGILL: /* Illegal Instruction */
signal_desc = "SIGILL";
break;
case SIGSEGV: /* Segmentation Violation */
signal_desc = "SIGSEGV";
break;
case SIGTERM: /* Termination */
signal_desc = "SIGTERM";
break;
case SIGHUP: /* Hangup */
signal_desc = "SIGHUP";
break;
default:
signal_desc = "UNKNOWN";
break;
}
if (signal_dbg)
fprintf(stderr, "%s: caught signal %d: %s\n", __func__, signum, signal_desc);
cleanup(context, true);
context->tuner.feeder.parser.cleanup();
exit(signum);
}
void stop_server(struct dvbtee_context* context)
{
if (!context->server)
return;
context->server->stop();
delete context->server;
context->server = NULL;
return;
}
int start_server(struct dvbtee_context* context, unsigned int flags, int port, int eavesdropping_port = 0)
{
context->server = new serve;
context->server->add_tuner(&context->tuner);
if (eavesdropping_port)
context->tuner.feeder.parser.out.add_http_server(eavesdropping_port);
context->server->set_scan_flags(0, flags);
return context->server->start(port);
}
//FIXME: we return const char * for no reason - this will be converted to bool, int or void
const char * chandump(void *context, parsed_channel_info_t *c)
{
char channelno[7]; /* XXX.XXX */
if (c->major + c->minor > 1)
sprintf(channelno, "%d.%d", c->major, c->minor);
else if (c->lcn)
sprintf(channelno, "%d", c->lcn);
else
sprintf(channelno, "%d", c->physical_channel);
/* xine format */
fprintf(stdout, "%s-%s:%d:%s:%d:%d:%d\n",
channelno,
c->service_name,
c->freq,//iter_vct->second.carrier_freq,
c->modulation,
c->vpid, c->apid, c->program_number);
/* link to http stream */
fprintf(stdout, "<a href='/tune=%d+%d&stream/here'>%s: %s</a>",
c->physical_channel, c->program_number, channelno, c->service_name);
return NULL;
}
bool list_channels(serve *server)
{
if (!server)
return false;
return server->get_channels(chandump, NULL);
}
bool start_async_channel_scan(serve *server, unsigned int flags = 0)
{
return server->scan(flags);
}
bool channel_scan_and_dump(serve *server, unsigned int flags = 0)
{
return server->scan(flags, chandump, NULL);
}
void epg_header_footer(void *context, bool header, bool channel)
{
const char *noun = (channel) ? "channel" : "epg table";
const char *adj = (header) ? "start" : "end";
fprintf(stdout, "receiving %s of %s\n", adj, noun);
}
void epg_event(void *context, decoded_event_t *e)
{
fprintf(stdout, "received event id: %d on channel name: %s, major: %d, minor: %d, physical: %d, service id: %d, title: %s, desc: %s, start time (time_t) %ld, duration (sec) %d\n",
e->event_id, e->channel_name, e->chan_major, e->chan_minor, e->chan_physical, e->chan_svc_id, e->name, e->text, e->start_time, e->length_sec);
}
bool request_epg(serve *server)
{
if (!server)
return false;
return server->get_epg(epg_header_footer, epg_event, NULL);
}
int main(int argc, char **argv)
{
int opt;
dvbtee_context context;
context.server = NULL;
/* LinuxDVB context: */
int dvb_adap = 0; /* ID X, /dev/dvb/adapterX/ */
int demux_id = 0; /* ID Y, /dev/dvb/adapterX/demuxY */
int dvr_id = 0; /* ID Y, /dev/dvb/adapterX/dvrY */
int fe_id = 0; /* ID Y, /dev/dvb/adapterX/frontendY */
unsigned int serv_flags = 0;
unsigned int scan_flags = 0;
while ((opt = getopt(argc, argv, "a:A:f:d::")) != -1) {
switch (opt) {
case 'a': /* adapter */
dvb_adap = strtoul(optarg, NULL, 0);
break;
case 'A': /* ATSC / QAM */
scan_flags = strtoul(optarg, NULL, 0);
break;
case 'f': /* frontend */
fe_id = strtoul(optarg, NULL, 0);
break;
case 'd':
if (optarg)
libdvbtee_set_debug_level(strtoul(optarg, NULL, 0));
else
libdvbtee_set_debug_level(255);
break;
default: /* bad cmd line option */
return -1;
}
}
context_map[getpid()] = &context;
signal(SIGINT, signal_callback_handler); /* Program interrupt. (ctrl-c) */
signal(SIGABRT, signal_callback_handler); /* Process detects error and reports by calling abort */
signal(SIGFPE, signal_callback_handler); /* Floating-Point arithmetic Exception */
signal(SIGILL, signal_callback_handler); /* Illegal Instruction */
signal(SIGSEGV, signal_callback_handler); /* Segmentation Violation */
signal(SIGTERM, signal_callback_handler); /* Termination */
signal(SIGHUP, signal_callback_handler); /* Hangup */
#if 1 /* FIXME */
ATSCMultipleStringsInit();
#endif
context.tuner.set_device_ids(dvb_adap, fe_id, demux_id, dvr_id, false);
context.tuner.feeder.parser.limit_eit(-1);
start_server(&context, scan_flags, 62080, 62081);
if (context.server) {
while (context.server->is_running()) sleep(1);
stop_server(&context);
}
// cleanup(&context);
#if 1 /* FIXME */
ATSCMultipleStringsDeInit();
#endif
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: statementcomposer.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2007-07-31 13:38:39 $
*
* 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_connectivity.hxx"
#ifndef CONNECTIVITY_STATEMENTCOMPOSER_HXX
#include <connectivity/statementcomposer.hxx>
#endif
#include <connectivity/dbtools.hxx>
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_NULLPOINTEREXCEPTION_HPP_
#include <com/sun/star/lang/NullPointerException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XQUERIESSUPPLIER_HPP_
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
/** === end UNO includes === **/
#include <unotools/sharedunocomponent.hxx>
#include <tools/diagnose_ex.h>
#include <comphelper/property.hxx>
//........................................................................
namespace dbtools
{
//........................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Reference;
using ::com::sun::star::sdbc::XConnection;
using ::com::sun::star::sdb::XSingleSelectQueryComposer;
using ::com::sun::star::lang::NullPointerException;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::lang::XComponent;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::sdb::XQueriesSupplier;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::sdbc::SQLException;
/** === end UNO using === **/
namespace CommandType = ::com::sun::star::sdb::CommandType;
//====================================================================
//= StatementComposer_Data
//====================================================================
struct StatementComposer_Data
{
const Reference< XConnection > xConnection;
Reference< XSingleSelectQueryComposer > xComposer;
::rtl::OUString sCommand;
::rtl::OUString sFilter;
::rtl::OUString sOrder;
sal_Int32 nCommandType;
sal_Bool bEscapeProcessing;
bool bComposerDirty;
bool bDisposeComposer;
StatementComposer_Data( const Reference< XConnection >& _rxConnection )
:xConnection( _rxConnection )
,sCommand()
,sFilter()
,sOrder()
,nCommandType( CommandType::COMMAND )
,bEscapeProcessing( sal_True )
,bComposerDirty( true )
{
if ( !_rxConnection.is() )
throw NullPointerException();
}
};
//--------------------------------------------------------------------
namespace
{
//----------------------------------------------------------------
void lcl_resetComposer( StatementComposer_Data& _rData )
{
if ( _rData.bDisposeComposer && _rData.xComposer.is() )
{
try
{
Reference< XComponent > xComposerComponent( _rData.xComposer, UNO_QUERY_THROW );
xComposerComponent->dispose();
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
_rData.xComposer.clear();
}
//----------------------------------------------------------------
bool lcl_ensureUpToDateComposer_nothrow( StatementComposer_Data& _rData )
{
if ( !_rData.bComposerDirty )
return _rData.xComposer.is();
lcl_resetComposer( _rData );
try
{
::rtl::OUString sStatement;
switch ( _rData.nCommandType )
{
case CommandType::COMMAND:
if ( _rData.bEscapeProcessing )
sStatement = _rData.sCommand;
// (in case of no escape processing we assume a not parseable statement)
break;
case CommandType::TABLE:
{
if ( !_rData.sCommand.getLength() )
break;
sStatement = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "SELECT * FROM " ) );
::rtl::OUString sCatalog, sSchema, sTable;
qualifiedNameComponents( _rData.xConnection->getMetaData(), _rData.sCommand, sCatalog, sSchema, sTable, eInDataManipulation );
sStatement += composeTableNameForSelect( _rData.xConnection, sCatalog, sSchema, sTable );
}
break;
case CommandType::QUERY:
{
// ask the connection for the query
Reference< XQueriesSupplier > xSupplyQueries( _rData.xConnection, UNO_QUERY_THROW );
Reference< XNameAccess > xQueries( xSupplyQueries->getQueries(), UNO_QUERY_THROW );
if ( !xQueries->hasByName( _rData.sCommand ) )
break;
Reference< XPropertySet > xQuery( xQueries->getByName( _rData.sCommand ), UNO_QUERY_THROW );
// a native query ?
sal_Bool bQueryEscapeProcessing = sal_False;
xQuery->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "EscapeProcessing" ) ) ) >>= bQueryEscapeProcessing;
if ( !bQueryEscapeProcessing )
break;
// the command used by the query
xQuery->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Command" ) ) ) >>= sStatement;
if ( !sStatement.getLength() )
break;
// use a composer to build a statement from the query filter/order props
Reference< XMultiServiceFactory > xFactory( _rData.xConnection, UNO_QUERY_THROW );
::utl::SharedUNOComponent< XSingleSelectQueryComposer > xComposer;
xComposer.set(
xFactory->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdb.SingleSelectQueryComposer" ) ) ),
UNO_QUERY_THROW
);
// the "basic" statement
xComposer->setQuery( sStatement );
// the sort order
const ::rtl::OUString sPropOrder( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Order" ) ) );
if ( ::comphelper::hasProperty( sPropOrder, xQuery ) )
{
::rtl::OUString sOrder;
OSL_VERIFY( xQuery->getPropertyValue( sPropOrder ) >>= sOrder );
xComposer->setOrder( sOrder );
}
// the filter
sal_Bool bApplyFilter = sal_True;
const ::rtl::OUString sPropApply = ::rtl::OUString::createFromAscii( "ApplyFilter" );
if ( ::comphelper::hasProperty( sPropApply, xQuery ) )
{
OSL_VERIFY( xQuery->getPropertyValue( sPropApply ) >>= bApplyFilter );
}
if ( bApplyFilter )
{
::rtl::OUString sFilter;
OSL_VERIFY( xQuery->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Filter" ) ) ) >>= sFilter );
xComposer->setFilter( sFilter );
}
// the composed statement
sStatement = xComposer->getQuery();
}
break;
default:
OSL_ENSURE(sal_False, "lcl_ensureUpToDateComposer_nothrow: no table, no query, no statement - what else ?!");
break;
}
if ( sStatement.getLength() )
{
// create an composer
Reference< XMultiServiceFactory > xFactory( _rData.xConnection, UNO_QUERY_THROW );
Reference< XSingleSelectQueryComposer > xComposer( xFactory->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdb.SingleSelectQueryComposer" ) ) ),
UNO_QUERY_THROW );
xComposer->setElementaryQuery( sStatement );
// append sort/filter
xComposer->setOrder( _rData.sOrder );
xComposer->setFilter( _rData.sFilter );
sStatement = xComposer->getQuery();
_rData.xComposer = xComposer;
_rData.bComposerDirty = false;
}
}
catch( const SQLException& )
{
// allowed to leave here
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
return _rData.xComposer.is();
}
}
//====================================================================
//= StatementComposer
//====================================================================
//--------------------------------------------------------------------
StatementComposer::StatementComposer( const Reference< XConnection >& _rxConnection,
const ::rtl::OUString& _rCommand, const sal_Int32 _nCommandType, const sal_Bool _bEscapeProcessing )
:m_pData( new StatementComposer_Data( _rxConnection ) )
{
OSL_PRECOND( _rxConnection.is(), "StatementComposer::StatementComposer: illegal connection!" );
m_pData->sCommand = _rCommand;
m_pData->nCommandType = _nCommandType;
m_pData->bEscapeProcessing = _bEscapeProcessing;
}
//--------------------------------------------------------------------
StatementComposer::~StatementComposer()
{
lcl_resetComposer( *m_pData );
}
//--------------------------------------------------------------------
void StatementComposer::setDisposeComposer( bool _bDoDispose )
{
m_pData->bDisposeComposer = _bDoDispose;
}
//--------------------------------------------------------------------
bool StatementComposer::getDisposeComposer() const
{
return m_pData->bDisposeComposer;
}
//--------------------------------------------------------------------
void StatementComposer::setFilter( const ::rtl::OUString& _rFilter )
{
m_pData->sFilter = _rFilter;
m_pData->bComposerDirty = true;
}
//--------------------------------------------------------------------
void StatementComposer::setOrder( const ::rtl::OUString& _rOrder )
{
m_pData->sOrder = _rOrder;
m_pData->bComposerDirty = true;
}
//--------------------------------------------------------------------
Reference< XSingleSelectQueryComposer > StatementComposer::getComposer()
{
lcl_ensureUpToDateComposer_nothrow( *m_pData );
return m_pData->xComposer;
}
//--------------------------------------------------------------------
::rtl::OUString StatementComposer::getQuery()
{
if ( lcl_ensureUpToDateComposer_nothrow( *m_pData ) )
{
return m_pData->xComposer->getQuery();
}
return ::rtl::OUString();
}
//........................................................................
} // namespace dbtools
//........................................................................
<commit_msg>INTEGRATION: CWS reportdesign01 (1.4.30); FILE MERGED 2007/10/09 09:22:52 lla 1.4.30.1: #i79214# change setQuery to setElementaryQuery<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: statementcomposer.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: ihi $ $Date: 2007-11-20 19:15:09 $
*
* 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_connectivity.hxx"
#ifndef CONNECTIVITY_STATEMENTCOMPOSER_HXX
#include <connectivity/statementcomposer.hxx>
#endif
#include <connectivity/dbtools.hxx>
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_SDB_COMMANDTYPE_HPP_
#include <com/sun/star/sdb/CommandType.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_NULLPOINTEREXCEPTION_HPP_
#include <com/sun/star/lang/NullPointerException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XQUERIESSUPPLIER_HPP_
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
/** === end UNO includes === **/
#include <unotools/sharedunocomponent.hxx>
#include <tools/diagnose_ex.h>
#include <comphelper/property.hxx>
//........................................................................
namespace dbtools
{
//........................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Reference;
using ::com::sun::star::sdbc::XConnection;
using ::com::sun::star::sdb::XSingleSelectQueryComposer;
using ::com::sun::star::lang::NullPointerException;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::lang::XComponent;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::sdb::XQueriesSupplier;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::beans::XPropertySet;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::sdbc::SQLException;
/** === end UNO using === **/
namespace CommandType = ::com::sun::star::sdb::CommandType;
//====================================================================
//= StatementComposer_Data
//====================================================================
struct StatementComposer_Data
{
const Reference< XConnection > xConnection;
Reference< XSingleSelectQueryComposer > xComposer;
::rtl::OUString sCommand;
::rtl::OUString sFilter;
::rtl::OUString sOrder;
sal_Int32 nCommandType;
sal_Bool bEscapeProcessing;
bool bComposerDirty;
bool bDisposeComposer;
StatementComposer_Data( const Reference< XConnection >& _rxConnection )
:xConnection( _rxConnection )
,sCommand()
,sFilter()
,sOrder()
,nCommandType( CommandType::COMMAND )
,bEscapeProcessing( sal_True )
,bComposerDirty( true )
{
if ( !_rxConnection.is() )
throw NullPointerException();
}
};
//--------------------------------------------------------------------
namespace
{
//----------------------------------------------------------------
void lcl_resetComposer( StatementComposer_Data& _rData )
{
if ( _rData.bDisposeComposer && _rData.xComposer.is() )
{
try
{
Reference< XComponent > xComposerComponent( _rData.xComposer, UNO_QUERY_THROW );
xComposerComponent->dispose();
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
_rData.xComposer.clear();
}
//----------------------------------------------------------------
bool lcl_ensureUpToDateComposer_nothrow( StatementComposer_Data& _rData )
{
if ( !_rData.bComposerDirty )
return _rData.xComposer.is();
lcl_resetComposer( _rData );
try
{
::rtl::OUString sStatement;
switch ( _rData.nCommandType )
{
case CommandType::COMMAND:
if ( _rData.bEscapeProcessing )
sStatement = _rData.sCommand;
// (in case of no escape processing we assume a not parseable statement)
break;
case CommandType::TABLE:
{
if ( !_rData.sCommand.getLength() )
break;
sStatement = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "SELECT * FROM " ) );
::rtl::OUString sCatalog, sSchema, sTable;
qualifiedNameComponents( _rData.xConnection->getMetaData(), _rData.sCommand, sCatalog, sSchema, sTable, eInDataManipulation );
sStatement += composeTableNameForSelect( _rData.xConnection, sCatalog, sSchema, sTable );
}
break;
case CommandType::QUERY:
{
// ask the connection for the query
Reference< XQueriesSupplier > xSupplyQueries( _rData.xConnection, UNO_QUERY_THROW );
Reference< XNameAccess > xQueries( xSupplyQueries->getQueries(), UNO_QUERY_THROW );
if ( !xQueries->hasByName( _rData.sCommand ) )
break;
Reference< XPropertySet > xQuery( xQueries->getByName( _rData.sCommand ), UNO_QUERY_THROW );
// a native query ?
sal_Bool bQueryEscapeProcessing = sal_False;
xQuery->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "EscapeProcessing" ) ) ) >>= bQueryEscapeProcessing;
if ( !bQueryEscapeProcessing )
break;
// the command used by the query
xQuery->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Command" ) ) ) >>= sStatement;
if ( !sStatement.getLength() )
break;
// use a composer to build a statement from the query filter/order props
Reference< XMultiServiceFactory > xFactory( _rData.xConnection, UNO_QUERY_THROW );
::utl::SharedUNOComponent< XSingleSelectQueryComposer > xComposer;
xComposer.set(
xFactory->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdb.SingleSelectQueryComposer" ) ) ),
UNO_QUERY_THROW
);
// the "basic" statement
xComposer->setElementaryQuery( sStatement );
// the sort order
const ::rtl::OUString sPropOrder( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Order" ) ) );
if ( ::comphelper::hasProperty( sPropOrder, xQuery ) )
{
::rtl::OUString sOrder;
OSL_VERIFY( xQuery->getPropertyValue( sPropOrder ) >>= sOrder );
xComposer->setOrder( sOrder );
}
// the filter
sal_Bool bApplyFilter = sal_True;
const ::rtl::OUString sPropApply = ::rtl::OUString::createFromAscii( "ApplyFilter" );
if ( ::comphelper::hasProperty( sPropApply, xQuery ) )
{
OSL_VERIFY( xQuery->getPropertyValue( sPropApply ) >>= bApplyFilter );
}
if ( bApplyFilter )
{
::rtl::OUString sFilter;
OSL_VERIFY( xQuery->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Filter" ) ) ) >>= sFilter );
xComposer->setFilter( sFilter );
}
// the composed statement
sStatement = xComposer->getQuery();
}
break;
default:
OSL_ENSURE(sal_False, "lcl_ensureUpToDateComposer_nothrow: no table, no query, no statement - what else ?!");
break;
}
if ( sStatement.getLength() )
{
// create an composer
Reference< XMultiServiceFactory > xFactory( _rData.xConnection, UNO_QUERY_THROW );
Reference< XSingleSelectQueryComposer > xComposer( xFactory->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdb.SingleSelectQueryComposer" ) ) ),
UNO_QUERY_THROW );
xComposer->setElementaryQuery( sStatement );
// append sort/filter
xComposer->setOrder( _rData.sOrder );
xComposer->setFilter( _rData.sFilter );
sStatement = xComposer->getQuery();
_rData.xComposer = xComposer;
_rData.bComposerDirty = false;
}
}
catch( const SQLException& )
{
// allowed to leave here
}
catch( const Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
return _rData.xComposer.is();
}
}
//====================================================================
//= StatementComposer
//====================================================================
//--------------------------------------------------------------------
StatementComposer::StatementComposer( const Reference< XConnection >& _rxConnection,
const ::rtl::OUString& _rCommand, const sal_Int32 _nCommandType, const sal_Bool _bEscapeProcessing )
:m_pData( new StatementComposer_Data( _rxConnection ) )
{
OSL_PRECOND( _rxConnection.is(), "StatementComposer::StatementComposer: illegal connection!" );
m_pData->sCommand = _rCommand;
m_pData->nCommandType = _nCommandType;
m_pData->bEscapeProcessing = _bEscapeProcessing;
}
//--------------------------------------------------------------------
StatementComposer::~StatementComposer()
{
lcl_resetComposer( *m_pData );
}
//--------------------------------------------------------------------
void StatementComposer::setDisposeComposer( bool _bDoDispose )
{
m_pData->bDisposeComposer = _bDoDispose;
}
//--------------------------------------------------------------------
bool StatementComposer::getDisposeComposer() const
{
return m_pData->bDisposeComposer;
}
//--------------------------------------------------------------------
void StatementComposer::setFilter( const ::rtl::OUString& _rFilter )
{
m_pData->sFilter = _rFilter;
m_pData->bComposerDirty = true;
}
//--------------------------------------------------------------------
void StatementComposer::setOrder( const ::rtl::OUString& _rOrder )
{
m_pData->sOrder = _rOrder;
m_pData->bComposerDirty = true;
}
//--------------------------------------------------------------------
Reference< XSingleSelectQueryComposer > StatementComposer::getComposer()
{
lcl_ensureUpToDateComposer_nothrow( *m_pData );
return m_pData->xComposer;
}
//--------------------------------------------------------------------
::rtl::OUString StatementComposer::getQuery()
{
if ( lcl_ensureUpToDateComposer_nothrow( *m_pData ) )
{
return m_pData->xComposer->getQuery();
}
return ::rtl::OUString();
}
//........................................................................
} // namespace dbtools
//........................................................................
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 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.
*
*//*!
* \file
* \brief Android JNI interface for instrumentations log parsing.
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "xeTestResultParser.hpp"
#include "xeTestCaseResult.hpp"
#include "xeContainerFormatParser.hpp"
#include "xeTestLogWriter.hpp"
#include "xeXMLWriter.hpp"
#include <jni.h>
#include <stdlib.h>
#include <android/log.h>
#include <sstream>
namespace
{
static const char* TESTCASE_STYLESHEET = "testlog.xsl";
static const char* LOG_TAG = "dEQP-TestLog";
class TestLogListener
{
public:
TestLogListener (JNIEnv* env, jobject object);
~TestLogListener (void);
void beginSession (void);
void endSession (void);
void sessionInfo (const char* name, const char* value);
void beginTestCase (const char* testCasePath);
void endTestCase (void);
void terminateTestCase (const char* reason);
void testCaseResult (const char* statusCode, const char* details);
void testLogData (const char* data);
private:
JNIEnv* m_env;
jobject m_object;
jclass m_class;
jmethodID m_sessionInfoID;
jmethodID m_beginSessionID;
jmethodID m_endSessionID;
jmethodID m_beginTestCaseID;
jmethodID m_endTestCaseID;
jmethodID m_terminateTestCaseID;
jmethodID m_testCaseResultID;
jmethodID m_testLogData;
TestLogListener (const TestLogListener&);
TestLogListener& operator= (const TestLogListener&);
};
TestLogListener::TestLogListener (JNIEnv* env, jobject object)
: m_env (env)
, m_object (object)
{
m_class = m_env->GetObjectClass(m_object);
m_sessionInfoID = m_env->GetMethodID(m_class, "sessionInfo", "(Ljava/lang/String;Ljava/lang/String;)V");
m_beginSessionID = m_env->GetMethodID(m_class, "beginSession", "()V");
m_endSessionID = m_env->GetMethodID(m_class, "endSession", "()V");
m_beginTestCaseID = m_env->GetMethodID(m_class, "beginTestCase", "(Ljava/lang/String;)V");
m_endTestCaseID = m_env->GetMethodID(m_class, "endTestCase", "()V");
m_terminateTestCaseID = m_env->GetMethodID(m_class, "terminateTestCase", "(Ljava/lang/String;)V");
m_testCaseResultID = m_env->GetMethodID(m_class, "testCaseResult", "(Ljava/lang/String;Ljava/lang/String;)V");
m_testLogData = m_env->GetMethodID(m_class, "testLogData", "(Ljava/lang/String;)V");
TCU_CHECK_INTERNAL(m_beginSessionID);
TCU_CHECK_INTERNAL(m_endSessionID);
TCU_CHECK_INTERNAL(m_sessionInfoID);
TCU_CHECK_INTERNAL(m_beginTestCaseID);
TCU_CHECK_INTERNAL(m_endTestCaseID);
TCU_CHECK_INTERNAL(m_terminateTestCaseID);
TCU_CHECK_INTERNAL(m_testCaseResultID);
TCU_CHECK_INTERNAL(m_testLogData);
}
TestLogListener::~TestLogListener (void)
{
}
void TestLogListener::beginSession (void)
{
m_env->CallObjectMethod(m_object, m_beginSessionID);
}
void TestLogListener::endSession (void)
{
m_env->CallObjectMethod(m_object, m_endSessionID);
}
void TestLogListener::sessionInfo (const char* name, const char* value)
{
jstring jName = m_env->NewStringUTF(name);
jstring jValue = m_env->NewStringUTF(value);
m_env->CallObjectMethod(m_object, m_sessionInfoID, jName, jValue);
}
void TestLogListener::beginTestCase (const char* testCasePath)
{
jstring jTestCasePath = m_env->NewStringUTF(testCasePath);
m_env->CallObjectMethod(m_object, m_beginTestCaseID, jTestCasePath);
}
void TestLogListener::endTestCase (void)
{
m_env->CallObjectMethod(m_object, m_endTestCaseID);
}
void TestLogListener::terminateTestCase (const char* reason)
{
jstring jReason = m_env->NewStringUTF(reason);
m_env->CallObjectMethod(m_object, m_terminateTestCaseID, jReason);
}
void TestLogListener::testCaseResult (const char* statusCode, const char* details)
{
jstring jStatusCode = m_env->NewStringUTF(statusCode);
jstring jDetails = m_env->NewStringUTF(details);
m_env->CallObjectMethod(m_object, m_testCaseResultID, jStatusCode, jDetails);
}
void TestLogListener::testLogData (const char* data)
{
jstring logData = m_env->NewStringUTF(data);
m_env->CallObjectMethod(m_object, m_testLogData, logData);
}
class TestLogParser
{
public:
TestLogParser (bool logData);
~TestLogParser (void);
void parse (TestLogListener& listener, const char* buffer, size_t size);
private:
const bool m_logData;
bool m_inTestCase;
bool m_loggedResult;
xe::ContainerFormatParser m_containerParser;
xe::TestCaseResult m_testCaseResult;
xe::TestResultParser m_testResultParser;
TestLogParser (const TestLogParser&);
TestLogParser& operator= (const TestLogParser&);
};
TestLogParser::TestLogParser (bool logData)
: m_logData (logData)
, m_inTestCase (DE_FALSE)
, m_loggedResult (DE_FALSE)
{
}
TestLogParser::~TestLogParser (void)
{
}
void TestLogParser::parse (TestLogListener& listener, const char* buffer, size_t size)
{
m_containerParser.feed((const deUint8*)buffer, size);
while (m_containerParser.getElement() != xe::CONTAINERELEMENT_INCOMPLETE)
{
switch (m_containerParser.getElement())
{
case xe::CONTAINERELEMENT_END_OF_STRING:
// Do nothing
break;
case xe::CONTAINERELEMENT_BEGIN_SESSION:
listener.beginSession();
break;
case xe::CONTAINERELEMENT_END_SESSION:
listener.endSession();
break;
case xe::CONTAINERELEMENT_SESSION_INFO:
listener.sessionInfo(m_containerParser.getSessionInfoAttribute(), m_containerParser.getSessionInfoValue());
break;
case xe::CONTAINERELEMENT_BEGIN_TEST_CASE_RESULT:
listener.beginTestCase(m_containerParser.getTestCasePath());
m_inTestCase = DE_TRUE;
m_loggedResult = DE_FALSE;
m_testCaseResult = xe::TestCaseResult();
m_testResultParser.init(&m_testCaseResult);
break;
case xe::CONTAINERELEMENT_END_TEST_CASE_RESULT:
if (m_testCaseResult.statusCode != xe::TESTSTATUSCODE_LAST && !m_loggedResult)
{
listener.testCaseResult(xe::getTestStatusCodeName(m_testCaseResult.statusCode), m_testCaseResult.statusDetails.c_str());
m_loggedResult = DE_TRUE;
}
if (m_logData)
{
std::ostringstream testLog;
xe::xml::Writer xmlWriter(testLog);
testLog << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
<< "<?xml-stylesheet href=\"" << TESTCASE_STYLESHEET << "\" type=\"text/xsl\"?>\n";
xe::writeTestResult(m_testCaseResult, xmlWriter);
listener.testLogData(testLog.str().c_str());
}
listener.endTestCase();
m_inTestCase = DE_FALSE;
break;
case xe::CONTAINERELEMENT_TERMINATE_TEST_CASE_RESULT:
if (m_logData)
{
std::ostringstream testLog;
xe::xml::Writer xmlWriter(testLog);
testLog << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
<< "<?xml-stylesheet href=\"" << TESTCASE_STYLESHEET << "\" type=\"text/xsl\"?>\n";
xe::writeTestResult(m_testCaseResult, xmlWriter);
listener.testLogData(testLog.str().c_str());
}
if (m_testCaseResult.statusCode != xe::TESTSTATUSCODE_LAST && !m_loggedResult)
{
listener.testCaseResult(xe::getTestStatusCodeName(m_testCaseResult.statusCode), m_testCaseResult.statusDetails.c_str());
m_loggedResult = DE_TRUE;
}
listener.terminateTestCase(m_containerParser.getTerminateReason());
m_inTestCase = DE_FALSE;
break;
case xe::CONTAINERELEMENT_TEST_LOG_DATA:
{
if (m_inTestCase)
{
std::vector<deUint8> data(m_containerParser.getDataSize());
m_containerParser.getData(&(data[0]), (int)data.size(), 0);
//tcu::print("%d %s :%s %s", __LINE__, std::string((const char*)&data[0], data.size()).c_str(), __func__, __FILE__);
if (m_testResultParser.parse(&(data[0]), (int)data.size()) == xe::TestResultParser::PARSERESULT_CHANGED)
{
if (m_testCaseResult.statusCode != xe::TESTSTATUSCODE_LAST && !m_loggedResult)
{
listener.testCaseResult(xe::getTestStatusCodeName(m_testCaseResult.statusCode), m_testCaseResult.statusDetails.c_str());
m_loggedResult = DE_TRUE;
}
}
}
break;
}
default:
DE_ASSERT(DE_FALSE);
};
m_containerParser.advance();
}
}
void throwJNIException (JNIEnv* env, const std::exception& e)
{
jclass exClass;
exClass = env->FindClass("java/lang/Exception");
TCU_CHECK_INTERNAL(exClass != DE_NULL);
TCU_CHECK_INTERNAL(env->ThrowNew(exClass, e.what()) == 0);
}
} // anonymous
DE_BEGIN_EXTERN_C
JNIEXPORT jlong JNICALL Java_com_drawelements_deqp_testercore_TestLogParser_nativeCreate (JNIEnv* env, jclass, jboolean logData)
{
DE_UNREF(env);
try
{
return (jlong)new TestLogParser(logData);
}
catch (const std::exception& e)
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "%s", e.what());
throwJNIException(env, e);
return 0;
}
}
JNIEXPORT void JNICALL Java_com_drawelements_deqp_testercore_TestLogParser_nativeDestroy (JNIEnv* env, jclass, jlong nativePointer)
{
DE_UNREF(env);
try
{
delete ((TestLogParser*)nativePointer);
}
catch (const std::exception& e)
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "%s", e.what());
throwJNIException(env, e);
}
}
JNIEXPORT void JNICALL Java_com_drawelements_deqp_testercore_TestLogParser_nativeParse (JNIEnv* env, jclass, jlong nativePointer, jobject instrumentation, jbyteArray buffer, jint size)
{
jbyte* logData = DE_NULL;
try
{
TestLogParser* parser = (TestLogParser*)nativePointer;
TestLogListener listener (env, instrumentation);
logData = env->GetByteArrayElements(buffer, NULL);
parser->parse(listener, (const char*)logData, (size_t)size);
env->ReleaseByteArrayElements(buffer, logData, JNI_ABORT);
logData = DE_NULL;
}
catch (const std::exception& e)
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "%s", e.what());
if (logData)
env->ReleaseByteArrayElements(buffer, logData, JNI_ABORT);
throwJNIException(env, e);
}
}
DE_END_EXTERN_C
<commit_msg>am 4adc1515: Fix JNI usage issues in Android TestLogParser<commit_after>/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 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.
*
*//*!
* \file
* \brief Android JNI interface for instrumentations log parsing.
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "xeTestResultParser.hpp"
#include "xeTestCaseResult.hpp"
#include "xeContainerFormatParser.hpp"
#include "xeTestLogWriter.hpp"
#include "xeXMLWriter.hpp"
#include <jni.h>
#include <stdlib.h>
#include <android/log.h>
#include <sstream>
namespace
{
static const char* TESTCASE_STYLESHEET = "testlog.xsl";
static const char* LOG_TAG = "dEQP-TestLog";
class TestLogListener
{
public:
TestLogListener (JNIEnv* env, jobject object);
~TestLogListener (void);
void beginSession (void);
void endSession (void);
void sessionInfo (const char* name, const char* value);
void beginTestCase (const char* testCasePath);
void endTestCase (void);
void terminateTestCase (const char* reason);
void testCaseResult (const char* statusCode, const char* details);
void testLogData (const char* data);
private:
JNIEnv* m_env;
jobject m_object;
jclass m_class;
jmethodID m_sessionInfoID;
jmethodID m_beginSessionID;
jmethodID m_endSessionID;
jmethodID m_beginTestCaseID;
jmethodID m_endTestCaseID;
jmethodID m_terminateTestCaseID;
jmethodID m_testCaseResultID;
jmethodID m_testLogData;
TestLogListener (const TestLogListener&);
TestLogListener& operator= (const TestLogListener&);
};
TestLogListener::TestLogListener (JNIEnv* env, jobject object)
: m_env (env)
, m_object (object)
{
m_class = m_env->GetObjectClass(m_object);
m_sessionInfoID = m_env->GetMethodID(m_class, "sessionInfo", "(Ljava/lang/String;Ljava/lang/String;)V");
m_beginSessionID = m_env->GetMethodID(m_class, "beginSession", "()V");
m_endSessionID = m_env->GetMethodID(m_class, "endSession", "()V");
m_beginTestCaseID = m_env->GetMethodID(m_class, "beginTestCase", "(Ljava/lang/String;)V");
m_endTestCaseID = m_env->GetMethodID(m_class, "endTestCase", "()V");
m_terminateTestCaseID = m_env->GetMethodID(m_class, "terminateTestCase", "(Ljava/lang/String;)V");
m_testCaseResultID = m_env->GetMethodID(m_class, "testCaseResult", "(Ljava/lang/String;Ljava/lang/String;)V");
m_testLogData = m_env->GetMethodID(m_class, "testLogData", "(Ljava/lang/String;)V");
TCU_CHECK_INTERNAL(m_beginSessionID);
TCU_CHECK_INTERNAL(m_endSessionID);
TCU_CHECK_INTERNAL(m_sessionInfoID);
TCU_CHECK_INTERNAL(m_beginTestCaseID);
TCU_CHECK_INTERNAL(m_endTestCaseID);
TCU_CHECK_INTERNAL(m_terminateTestCaseID);
TCU_CHECK_INTERNAL(m_testCaseResultID);
TCU_CHECK_INTERNAL(m_testLogData);
}
TestLogListener::~TestLogListener (void)
{
}
void TestLogListener::beginSession (void)
{
m_env->CallVoidMethod(m_object, m_beginSessionID);
}
void TestLogListener::endSession (void)
{
m_env->CallVoidMethod(m_object, m_endSessionID);
}
void TestLogListener::sessionInfo (const char* name, const char* value)
{
jstring jName = m_env->NewStringUTF(name);
jstring jValue = m_env->NewStringUTF(value);
m_env->CallVoidMethod(m_object, m_sessionInfoID, jName, jValue);
m_env->DeleteLocalRef(jName);
m_env->DeleteLocalRef(jValue);
}
void TestLogListener::beginTestCase (const char* testCasePath)
{
jstring jTestCasePath = m_env->NewStringUTF(testCasePath);
m_env->CallVoidMethod(m_object, m_beginTestCaseID, jTestCasePath);
m_env->DeleteLocalRef(jTestCasePath);
}
void TestLogListener::endTestCase (void)
{
m_env->CallVoidMethod(m_object, m_endTestCaseID);
}
void TestLogListener::terminateTestCase (const char* reason)
{
jstring jReason = m_env->NewStringUTF(reason);
m_env->CallVoidMethod(m_object, m_terminateTestCaseID, jReason);
m_env->DeleteLocalRef(jReason);
}
void TestLogListener::testCaseResult (const char* statusCode, const char* details)
{
jstring jStatusCode = m_env->NewStringUTF(statusCode);
jstring jDetails = m_env->NewStringUTF(details);
m_env->CallVoidMethod(m_object, m_testCaseResultID, jStatusCode, jDetails);
m_env->DeleteLocalRef(jStatusCode);
m_env->DeleteLocalRef(jDetails);
}
void TestLogListener::testLogData (const char* data)
{
jstring logData = m_env->NewStringUTF(data);
m_env->CallVoidMethod(m_object, m_testLogData, logData);
m_env->DeleteLocalRef(logData);
}
class TestLogParser
{
public:
TestLogParser (bool logData);
~TestLogParser (void);
void parse (TestLogListener& listener, const char* buffer, size_t size);
private:
const bool m_logData;
bool m_inTestCase;
bool m_loggedResult;
xe::ContainerFormatParser m_containerParser;
xe::TestCaseResult m_testCaseResult;
xe::TestResultParser m_testResultParser;
TestLogParser (const TestLogParser&);
TestLogParser& operator= (const TestLogParser&);
};
TestLogParser::TestLogParser (bool logData)
: m_logData (logData)
, m_inTestCase (DE_FALSE)
, m_loggedResult (DE_FALSE)
{
}
TestLogParser::~TestLogParser (void)
{
}
void TestLogParser::parse (TestLogListener& listener, const char* buffer, size_t size)
{
m_containerParser.feed((const deUint8*)buffer, size);
while (m_containerParser.getElement() != xe::CONTAINERELEMENT_INCOMPLETE)
{
switch (m_containerParser.getElement())
{
case xe::CONTAINERELEMENT_END_OF_STRING:
// Do nothing
break;
case xe::CONTAINERELEMENT_BEGIN_SESSION:
listener.beginSession();
break;
case xe::CONTAINERELEMENT_END_SESSION:
listener.endSession();
break;
case xe::CONTAINERELEMENT_SESSION_INFO:
listener.sessionInfo(m_containerParser.getSessionInfoAttribute(), m_containerParser.getSessionInfoValue());
break;
case xe::CONTAINERELEMENT_BEGIN_TEST_CASE_RESULT:
listener.beginTestCase(m_containerParser.getTestCasePath());
m_inTestCase = DE_TRUE;
m_loggedResult = DE_FALSE;
m_testCaseResult = xe::TestCaseResult();
m_testResultParser.init(&m_testCaseResult);
break;
case xe::CONTAINERELEMENT_END_TEST_CASE_RESULT:
if (m_testCaseResult.statusCode != xe::TESTSTATUSCODE_LAST && !m_loggedResult)
{
listener.testCaseResult(xe::getTestStatusCodeName(m_testCaseResult.statusCode), m_testCaseResult.statusDetails.c_str());
m_loggedResult = DE_TRUE;
}
if (m_logData)
{
std::ostringstream testLog;
xe::xml::Writer xmlWriter(testLog);
testLog << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
<< "<?xml-stylesheet href=\"" << TESTCASE_STYLESHEET << "\" type=\"text/xsl\"?>\n";
xe::writeTestResult(m_testCaseResult, xmlWriter);
listener.testLogData(testLog.str().c_str());
}
listener.endTestCase();
m_inTestCase = DE_FALSE;
break;
case xe::CONTAINERELEMENT_TERMINATE_TEST_CASE_RESULT:
if (m_logData)
{
std::ostringstream testLog;
xe::xml::Writer xmlWriter(testLog);
testLog << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
<< "<?xml-stylesheet href=\"" << TESTCASE_STYLESHEET << "\" type=\"text/xsl\"?>\n";
xe::writeTestResult(m_testCaseResult, xmlWriter);
listener.testLogData(testLog.str().c_str());
}
if (m_testCaseResult.statusCode != xe::TESTSTATUSCODE_LAST && !m_loggedResult)
{
listener.testCaseResult(xe::getTestStatusCodeName(m_testCaseResult.statusCode), m_testCaseResult.statusDetails.c_str());
m_loggedResult = DE_TRUE;
}
listener.terminateTestCase(m_containerParser.getTerminateReason());
m_inTestCase = DE_FALSE;
break;
case xe::CONTAINERELEMENT_TEST_LOG_DATA:
{
if (m_inTestCase)
{
std::vector<deUint8> data(m_containerParser.getDataSize());
m_containerParser.getData(&(data[0]), (int)data.size(), 0);
//tcu::print("%d %s :%s %s", __LINE__, std::string((const char*)&data[0], data.size()).c_str(), __func__, __FILE__);
if (m_testResultParser.parse(&(data[0]), (int)data.size()) == xe::TestResultParser::PARSERESULT_CHANGED)
{
if (m_testCaseResult.statusCode != xe::TESTSTATUSCODE_LAST && !m_loggedResult)
{
listener.testCaseResult(xe::getTestStatusCodeName(m_testCaseResult.statusCode), m_testCaseResult.statusDetails.c_str());
m_loggedResult = DE_TRUE;
}
}
}
break;
}
default:
DE_ASSERT(DE_FALSE);
};
m_containerParser.advance();
}
}
void throwJNIException (JNIEnv* env, const std::exception& e)
{
jclass exClass;
exClass = env->FindClass("java/lang/Exception");
TCU_CHECK_INTERNAL(exClass != DE_NULL);
TCU_CHECK_INTERNAL(env->ThrowNew(exClass, e.what()) == 0);
}
} // anonymous
DE_BEGIN_EXTERN_C
JNIEXPORT jlong JNICALL Java_com_drawelements_deqp_testercore_TestLogParser_nativeCreate (JNIEnv* env, jclass, jboolean logData)
{
DE_UNREF(env);
try
{
return (jlong)new TestLogParser(logData);
}
catch (const std::exception& e)
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "%s", e.what());
throwJNIException(env, e);
return 0;
}
}
JNIEXPORT void JNICALL Java_com_drawelements_deqp_testercore_TestLogParser_nativeDestroy (JNIEnv* env, jclass, jlong nativePointer)
{
DE_UNREF(env);
try
{
delete ((TestLogParser*)nativePointer);
}
catch (const std::exception& e)
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "%s", e.what());
throwJNIException(env, e);
}
}
JNIEXPORT void JNICALL Java_com_drawelements_deqp_testercore_TestLogParser_nativeParse (JNIEnv* env, jclass, jlong nativePointer, jobject instrumentation, jbyteArray buffer, jint size)
{
jbyte* logData = DE_NULL;
try
{
TestLogParser* parser = (TestLogParser*)nativePointer;
TestLogListener listener (env, instrumentation);
logData = env->GetByteArrayElements(buffer, NULL);
parser->parse(listener, (const char*)logData, (size_t)size);
env->ReleaseByteArrayElements(buffer, logData, JNI_ABORT);
logData = DE_NULL;
}
catch (const std::exception& e)
{
__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "%s", e.what());
if (logData)
env->ReleaseByteArrayElements(buffer, logData, JNI_ABORT);
throwJNIException(env, e);
}
}
DE_END_EXTERN_C
<|endoftext|>
|
<commit_before>/*
* Copyright 2008-2010 Google 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 "esnpapi.h"
#include "proxyImpl.h"
#include <any.h>
#include <reflect.h>
#include <org/w3c/dom.h>
using namespace org::w3c::dom;
void initializeHtmlMetaData()
{
registerMetaData(html::ApplicationCache::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ApplicationCache_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::BarProp::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::BarProp_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::BeforeUnloadEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::BeforeUnloadEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::CanvasGradient::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasGradient_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::CanvasPattern::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasPattern_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::CanvasPixelArray::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasPixelArray_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::CanvasRenderingContext2D::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasRenderingContext2D_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DataTransfer::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DataTransfer_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DOMSettableTokenList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMSettableTokenList_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DOMStringMap::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMStringMap_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DOMTokenList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMTokenList_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DragEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DragEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Function::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Function_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::History::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::History_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::ImageData::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ImageData_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Location::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Location_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::MediaError::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MediaError_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::MessageChannel::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessageChannel_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::MessageEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessageEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::MessagePort::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessagePort_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Navigator::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Navigator_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::PopStateEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::PopStateEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::PropertyNodeList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::PropertyNodeList_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::RadioNodeList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::RadioNodeList_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Screen::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Screen_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Selection::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Selection_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::StyleMedia::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::StyleMedia_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::TextMetrics::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::TextMetrics_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::TimeRanges::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::TimeRanges_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::UndoManagerEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::UndoManagerEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::UndoManager::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::UndoManager_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::ValidityState::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ValidityState_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Window::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Window_Bridge<Any, invoke> >::createInstance));
initializeHtmlMetaDataA_G();
initializeHtmlMetaDataH_N();
initializeHtmlMetaDataO_U();
initializeHtmlMetaDataV_Z();
// In HTML5, HTMLDocument is a mixin of Document, but historically it was a separate interface extended from Document.
// Existing browsers uses HTMLDocument as a class name, and we need to register 'HTMLDocument' as a valid interface name for Document.
registerMetaData(Document::getMetaData(),
reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, Document_Bridge<Any, invoke> >::createInstance),
"HTMLDocument");
}
<commit_msg>(initializeHtmlMetaData) : Regiseter DOMWindow for WebKit.<commit_after>/*
* Copyright 2008-2010 Google 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 "esnpapi.h"
#include "proxyImpl.h"
#include <any.h>
#include <reflect.h>
#include <org/w3c/dom.h>
using namespace org::w3c::dom;
void initializeHtmlMetaData()
{
registerMetaData(html::ApplicationCache::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ApplicationCache_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::BarProp::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::BarProp_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::BeforeUnloadEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::BeforeUnloadEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::CanvasGradient::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasGradient_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::CanvasPattern::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasPattern_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::CanvasPixelArray::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasPixelArray_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::CanvasRenderingContext2D::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasRenderingContext2D_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DataTransfer::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DataTransfer_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DOMSettableTokenList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMSettableTokenList_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DOMStringMap::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMStringMap_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DOMTokenList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMTokenList_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::DragEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DragEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Function::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Function_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::History::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::History_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::ImageData::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ImageData_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Location::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Location_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::MediaError::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MediaError_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::MessageChannel::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessageChannel_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::MessageEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessageEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::MessagePort::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessagePort_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Navigator::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Navigator_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::PopStateEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::PopStateEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::PropertyNodeList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::PropertyNodeList_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::RadioNodeList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::RadioNodeList_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Screen::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Screen_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Selection::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Selection_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::StyleMedia::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::StyleMedia_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::TextMetrics::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::TextMetrics_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::TimeRanges::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::TimeRanges_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::UndoManagerEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::UndoManagerEvent_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::UndoManager::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::UndoManager_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::ValidityState::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ValidityState_Bridge<Any, invoke> >::createInstance));
registerMetaData(html::Window::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Window_Bridge<Any, invoke> >::createInstance));
initializeHtmlMetaDataA_G();
initializeHtmlMetaDataH_N();
initializeHtmlMetaDataO_U();
initializeHtmlMetaDataV_Z();
// In HTML5, HTMLDocument is a mixin of Document, but historically it was a separate interface extended from Document.
// Existing browsers uses HTMLDocument as a class name, and we need to register 'HTMLDocument' as a valid interface name for Document.
registerMetaData(Document::getMetaData(),
reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, Document_Bridge<Any, invoke> >::createInstance),
"HTMLDocument");
// WebKit uses "DOMWindow" instead of "Window"
registerMetaData(html::Window::getMetaData(),
reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Window_Bridge<Any, invoke> >::createInstance),
"DOMWindow");
}
<|endoftext|>
|
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2018 Intel Corporation
#ifndef OPENCV_GAPI_UTIL_OPTIONAL_HPP
#define OPENCV_GAPI_UTIL_OPTIONAL_HPP
#include <opencv2/gapi/util/variant.hpp>
// A poor man's `optional` implementation, incompletely modeled against C++17 spec.
namespace cv
{
namespace util
{
class bad_optional_access: public std::exception
{
public:
virtual const char *what() const noexcept override
{
return "Bad optional access";
}
};
// TODO: nullopt_t
// Interface ///////////////////////////////////////////////////////////////
template<typename T> class optional
{
public:
// Constructors
// NB.: there were issues with Clang 3.8 when =default() was used
// instead {}
optional() {};
optional(const optional&) = default;
explicit optional(T&&) noexcept;
explicit optional(const T&) noexcept;
optional(optional&&) noexcept;
// TODO: optional(nullopt_t) noexcept;
// TODO: optional(const optional<U> &)
// TODO: optional(optional<U> &&)
// TODO: optional(Args&&...)
// TODO: optional(initializer_list<U>)
// TODO: optional(U&& value);
// Assignment
optional& operator=(const optional&) = default;
optional& operator=(optional&&);
// Observers
T* operator-> ();
const T* operator-> () const;
T& operator* ();
const T& operator* () const;
// TODO: && versions
operator bool() const noexcept;
bool has_value() const noexcept;
T& value();
const T& value() const;
// TODO: && versions
template<class U>
T value_or(U &&default_value) const;
void swap(optional &other) noexcept;
void reset() noexcept;
// TODO: emplace
// TODO: operator==, !=, <, <=, >, >=
private:
struct nothing {};
util::variant<nothing, T> m_holder;
};
template<class T>
optional<typename std::decay<T>::type> make_optional(T&& value);
// TODO: Args... and initializer_list versions
// Implementation //////////////////////////////////////////////////////////
template<class T> optional<T>::optional(T &&v) noexcept
: m_holder(v)
{
}
template<class T> optional<T>::optional(const T &v) noexcept
: m_holder(v)
{
}
template<class T> optional<T>::optional(optional&& rhs) noexcept
: m_holder(std::move(rhs.m_holder))
{
rhs.reset();
}
template<class T> optional<T>& optional<T>::operator=(optional&& rhs)
{
m_holder = std::move(rhs.m_holder);
rhs.reset();
return *this;
}
template<class T> T* optional<T>::operator-> ()
{
return & *(*this);
}
template<class T> const T* optional<T>::operator-> () const
{
return & *(*this);
}
template<class T> T& optional<T>::operator* ()
{
return this->value();
}
template<class T> const T& optional<T>::operator* () const
{
return this->value();
}
template<class T> optional<T>::operator bool() const noexcept
{
return this->has_value();
}
template<class T> bool optional<T>::has_value() const noexcept
{
return util::holds_alternative<T>(m_holder);
}
template<class T> T& optional<T>::value()
{
if (!this->has_value())
throw_error(bad_optional_access());
return util::get<T>(m_holder);
}
template<class T> const T& optional<T>::value() const
{
if (!this->has_value())
throw_error(bad_optional_access());
return util::get<T>(m_holder);
}
template<class T>
template<class U> T optional<T>::value_or(U &&default_value) const
{
return (this->has_value() ? this->value() : T(default_value));
}
template<class T> void optional<T>::swap(optional<T> &other) noexcept
{
m_holder.swap(other.m_holder);
}
template<class T> void optional<T>::reset() noexcept
{
if (this->has_value())
m_holder = nothing{};
}
template<class T>
optional<typename std::decay<T>::type> make_optional(T&& value)
{
return optional<typename std::decay<T>::type>(std::forward<T>(value));
}
} // namespace util
} // namespace cv
#endif // OPENCV_GAPI_UTIL_OPTIONAL_HPP
<commit_msg>Fix optional move constructor<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Copyright (C) 2018 Intel Corporation
#ifndef OPENCV_GAPI_UTIL_OPTIONAL_HPP
#define OPENCV_GAPI_UTIL_OPTIONAL_HPP
#include <opencv2/gapi/util/variant.hpp>
// A poor man's `optional` implementation, incompletely modeled against C++17 spec.
namespace cv
{
namespace util
{
class bad_optional_access: public std::exception
{
public:
virtual const char *what() const noexcept override
{
return "Bad optional access";
}
};
// TODO: nullopt_t
// Interface ///////////////////////////////////////////////////////////////
template<typename T> class optional
{
public:
// Constructors
// NB.: there were issues with Clang 3.8 when =default() was used
// instead {}
optional() {};
optional(const optional&) = default;
explicit optional(T&&) noexcept;
explicit optional(const T&) noexcept;
optional(optional&&) noexcept;
// TODO: optional(nullopt_t) noexcept;
// TODO: optional(const optional<U> &)
// TODO: optional(optional<U> &&)
// TODO: optional(Args&&...)
// TODO: optional(initializer_list<U>)
// TODO: optional(U&& value);
// Assignment
optional& operator=(const optional&) = default;
optional& operator=(optional&&);
// Observers
T* operator-> ();
const T* operator-> () const;
T& operator* ();
const T& operator* () const;
// TODO: && versions
operator bool() const noexcept;
bool has_value() const noexcept;
T& value();
const T& value() const;
// TODO: && versions
template<class U>
T value_or(U &&default_value) const;
void swap(optional &other) noexcept;
void reset() noexcept;
// TODO: emplace
// TODO: operator==, !=, <, <=, >, >=
private:
struct nothing {};
util::variant<nothing, T> m_holder;
};
template<class T>
optional<typename std::decay<T>::type> make_optional(T&& value);
// TODO: Args... and initializer_list versions
// Implementation //////////////////////////////////////////////////////////
template<class T> optional<T>::optional(T &&v) noexcept
: m_holder(std::move(v))
{
}
template<class T> optional<T>::optional(const T &v) noexcept
: m_holder(v)
{
}
template<class T> optional<T>::optional(optional&& rhs) noexcept
: m_holder(std::move(rhs.m_holder))
{
rhs.reset();
}
template<class T> optional<T>& optional<T>::operator=(optional&& rhs)
{
m_holder = std::move(rhs.m_holder);
rhs.reset();
return *this;
}
template<class T> T* optional<T>::operator-> ()
{
return & *(*this);
}
template<class T> const T* optional<T>::operator-> () const
{
return & *(*this);
}
template<class T> T& optional<T>::operator* ()
{
return this->value();
}
template<class T> const T& optional<T>::operator* () const
{
return this->value();
}
template<class T> optional<T>::operator bool() const noexcept
{
return this->has_value();
}
template<class T> bool optional<T>::has_value() const noexcept
{
return util::holds_alternative<T>(m_holder);
}
template<class T> T& optional<T>::value()
{
if (!this->has_value())
throw_error(bad_optional_access());
return util::get<T>(m_holder);
}
template<class T> const T& optional<T>::value() const
{
if (!this->has_value())
throw_error(bad_optional_access());
return util::get<T>(m_holder);
}
template<class T>
template<class U> T optional<T>::value_or(U &&default_value) const
{
return (this->has_value() ? this->value() : T(default_value));
}
template<class T> void optional<T>::swap(optional<T> &other) noexcept
{
m_holder.swap(other.m_holder);
}
template<class T> void optional<T>::reset() noexcept
{
if (this->has_value())
m_holder = nothing{};
}
template<class T>
optional<typename std::decay<T>::type> make_optional(T&& value)
{
return optional<typename std::decay<T>::type>(std::forward<T>(value));
}
} // namespace util
} // namespace cv
#endif // OPENCV_GAPI_UTIL_OPTIONAL_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: mainthreadexecutor.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: mav $ $Date: 2003-12-17 11:26:52 $
*
* 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 __MAINTHREADEXECUTOR_HXX_
#define __MAINTHREADEXECUTOR_HXX_
#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_
#include <com/sun/star/task/XJob.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#include <tools/link.hxx>
class MainThreadExecutorRequest
{
::com::sun::star::uno::Reference< ::com::sun::star::task::XJob > m_xJob;
::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > m_aValues;
public:
MainThreadExecutorRequest(
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XJob >& xJob,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& aValues );
void doIt();
};
class MainThreadExecutor : public ::cppu::WeakImplHelper2<
::com::sun::star::task::XJob,
::com::sun::star::lang::XServiceInfo >
{
public:
MainThreadExecutor(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory )
{}
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL impl_staticGetSupportedServiceNames();
static ::rtl::OUString SAL_CALL impl_staticGetImplementationName();
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_staticCreateSelfInstance(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
DECL_STATIC_LINK( MainThreadExecutor, worker, MainThreadExecutorRequest* );
// XJob
virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.114); FILE MERGED 2005/09/05 17:18:19 rt 1.1.114.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: mainthreadexecutor.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:49:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __MAINTHREADEXECUTOR_HXX_
#define __MAINTHREADEXECUTOR_HXX_
#ifndef _COM_SUN_STAR_TASK_XJOB_HPP_
#include <com/sun/star/task/XJob.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#include <tools/link.hxx>
class MainThreadExecutorRequest
{
::com::sun::star::uno::Reference< ::com::sun::star::task::XJob > m_xJob;
::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > m_aValues;
public:
MainThreadExecutorRequest(
const ::com::sun::star::uno::Reference< ::com::sun::star::task::XJob >& xJob,
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& aValues );
void doIt();
};
class MainThreadExecutor : public ::cppu::WeakImplHelper2<
::com::sun::star::task::XJob,
::com::sun::star::lang::XServiceInfo >
{
public:
MainThreadExecutor(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory )
{}
static ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL impl_staticGetSupportedServiceNames();
static ::rtl::OUString SAL_CALL impl_staticGetImplementationName();
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_staticCreateSelfInstance(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
DECL_STATIC_LINK( MainThreadExecutor, worker, MainThreadExecutorRequest* );
// XJob
virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>
|
<commit_before>/* libs/graphics/ports/SkTime_Unix.cpp
**
** Copyright 2006, 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 "SkTime.h"
#include <sys/time.h>
#include <time.h>
void SkTime::GetDateTime(DateTime* dt)
{
if (dt)
{
time_t m_time;
time(&m_time);
struct tm* tstruct;
tstruct = localtime(&m_time);
dt->fYear = tstruct->tm_year;
dt->fMonth = SkToU8(tstruct->tm_mon + 1);
dt->fDayOfWeek = SkToU8(tstruct->tm_wday);
dt->fDay = SkToU8(tstruct->tm_mday);
dt->fHour = SkToU8(tstruct->tm_hour);
dt->fMinute = SkToU8(tstruct->tm_min);
dt->fSecond = SkToU8(tstruct->tm_sec);
}
}
SkMSec SkTime::GetMSecs()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (SkMSec) (tv.tv_sec * 1000 + tv.tv_usec / 1000 ); // microseconds to milliseconds
}
#endif
<commit_msg>Deleted the #endif that's caused the compiler erro<commit_after>/* libs/graphics/ports/SkTime_Unix.cpp
**
** Copyright 2006, 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 "SkTime.h"
#include <sys/time.h>
#include <time.h>
void SkTime::GetDateTime(DateTime* dt)
{
if (dt)
{
time_t m_time;
time(&m_time);
struct tm* tstruct;
tstruct = localtime(&m_time);
dt->fYear = tstruct->tm_year;
dt->fMonth = SkToU8(tstruct->tm_mon + 1);
dt->fDayOfWeek = SkToU8(tstruct->tm_wday);
dt->fDay = SkToU8(tstruct->tm_mday);
dt->fHour = SkToU8(tstruct->tm_hour);
dt->fMinute = SkToU8(tstruct->tm_min);
dt->fSecond = SkToU8(tstruct->tm_sec);
}
}
SkMSec SkTime::GetMSecs()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (SkMSec) (tv.tv_sec * 1000 + tv.tv_usec / 1000 ); // microseconds to milliseconds
}<|endoftext|>
|
<commit_before>#include "Test.h"
TEST_CASE("Finding top level", "[binding:decls]") {
auto file1 = SyntaxTree::fromText("module A; endmodule\nmodule B; A a(); endmodule\nmodule C; endmodule");
auto file2 = SyntaxTree::fromText("module D; B b(); E e(); endmodule\nmodule E; module C; endmodule C c(); endmodule");
Compilation compilation;
compilation.addSyntaxTree(file1);
compilation.addSyntaxTree(file2);
const RootSymbol& root = compilation.getRoot();
REQUIRE(root.topInstances.size() == 2);
CHECK(root.topInstances[0]->name == "C");
CHECK(root.topInstances[1]->name == "D");
NO_COMPILATION_ERRORS;
}
TEST_CASE("Module parameterization errors", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
Leaf l1();
Leaf #(1, 2, 3, 4) l2();
Leaf #(1, 2, 3, 4, 5) l3();
Leaf #(.foo(3), .baz(9)) l4();
Leaf #(.unset(10), .bla(7)) l5();
Leaf #(.unset(10), .localp(7)) l6();
Leaf #(.unset(10), .unset(7)) l7();
Leaf #(.unset(10), 5) l8();
Leaf #(.unset(10)) l9(); // no errors on this one
endmodule
module Leaf #(
int foo = 4,
int bar = 9,
localparam int baz,
parameter bizz = baz,
parameter int unset
)();
parameter int localp;
endmodule
)");
Compilation compilation;
auto it = evalModule(tree, compilation).membersOfType<ModuleInstanceSymbol>().begin();
CHECK(it->name == "l1"); it++;
CHECK(it->name == "l2"); it++;
CHECK(it->name == "l3"); it++;
CHECK(it->name == "l4"); it++;
CHECK(it->name == "l5"); it++;
CHECK(it->name == "l6"); it++;
CHECK(it->name == "l7"); it++;
CHECK(it->name == "l8"); it++;
CHECK(it->name == "l9"); it++;
Diagnostics diags = compilation.getSemanticDiagnostics();
REQUIRE(diags.size() == 10);
CHECK(diags[0].code == DiagCode::ParamHasNoValue);
CHECK(diags[1].code == DiagCode::TooManyParamAssignments);
CHECK(diags[2].code == DiagCode::ParamHasNoValue);
CHECK(diags[3].code == DiagCode::AssignedToLocalPortParam);
CHECK(diags[4].code == DiagCode::ParameterDoesNotExist);
CHECK(diags[5].code == DiagCode::AssignedToLocalBodyParam);
CHECK(diags[6].code == DiagCode::DuplicateParamAssignment);
CHECK(diags[7].code == DiagCode::MixingOrderedAndNamedParams);
CHECK(diags[8].code == DiagCode::LocalParamNoInitializer);
CHECK(diags[9].code == DiagCode::BodyParamNoInitializer);
REQUIRE(diags[3].notes.size() == 1);
REQUIRE(diags[5].notes.size() == 1);
REQUIRE(diags[6].notes.size() == 1);
CHECK(diags[3].notes[0].code == DiagCode::NoteDeclarationHere);
CHECK(diags[5].notes[0].code == DiagCode::NoteDeclarationHere);
CHECK(diags[6].notes[0].code == DiagCode::NotePreviousUsage);
}
TEST_CASE("Module children (simple)", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
Child child();
endmodule
module Child;
Leaf leaf();
endmodule
module Leaf #(parameter int foo = 4)();
parameter localp = foo;
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation);
const auto& leaf = instance.memberAt<ModuleInstanceSymbol>(0).memberAt<ModuleInstanceSymbol>(0);
const auto& foo = leaf.find<ParameterSymbol>("foo");
CHECK(foo.getValue().integer() == 4);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Module children (conditional generate)", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
Child child();
endmodule
module Child #(parameter foo = 4)();
if (foo == 4) begin
Leaf #(1) leaf();
end
else begin
Leaf #(2) leaf();
end
endmodule
module Leaf #(parameter int foo = 4)();
parameter localp = foo;
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation);
const auto& leaf = instance
.memberAt<ModuleInstanceSymbol>(0)
.memberAt<GenerateBlockSymbol>(1)
.memberAt<ModuleInstanceSymbol>(0);
const auto& foo = leaf.find<ParameterSymbol>("foo");
CHECK(foo.getValue().integer() == 1);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Module children (loop generate)", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
for (genvar i = 0; i < 10; i += 1) begin
Leaf #(i) leaf();
end
endmodule
module Leaf #(parameter int foo)();
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation).memberAt<GenerateBlockArraySymbol>(0);
REQUIRE(instance.members().size() == 10);
for (uint32_t i = 0; i < 10; i++) {
const auto& leaf = instance.memberAt<GenerateBlockSymbol>(i).memberAt<ModuleInstanceSymbol>(1);
const auto& foo = leaf.find<ParameterSymbol>("foo");
CHECK(foo.getValue().integer() == i);
}
NO_COMPILATION_ERRORS;
}
TEST_CASE("Interface instantiation", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
interface I2CBus(
input wire clk,
input wire rst);
logic scl_i;
logic sda_i;
logic scl_o;
logic sda_o;
modport master (input clk, rst, scl_i, sda_i,
output scl_o, sda_o);
endinterface
module Top;
logic clk;
logic rst;
I2CBus bus(.*);
endmodule
)");
// TODO:
Compilation compilation;
evalModule(tree, compilation);
NO_COMPILATION_ERRORS;
}
TEST_CASE("always_comb", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module module1
#(
parameter int P1 = 4,
parameter int P2 = 5
)
(
input logic [P1-1:0] in1,
input logic [P2-1:0] in2,
input logic [3:0] in3,
output logic [P1-1:0] out1,
output logic [P1-1:0] out2,
output logic [P1-1:0] out3
);
always_comb out1 = in1;
always_comb begin
out2 = in2;
out3 = in3;
end
logic [7:0] arr1;
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation);
const auto& alwaysComb = instance.memberAt<ProceduralBlockSymbol>(14);
CHECK(alwaysComb.procedureKind == ProceduralBlockKind::AlwaysComb);
const auto& variable = instance.memberAt<VariableSymbol>(16);
CHECK(variable.getType().isIntegral());
CHECK(variable.name == "arr1");
NO_COMPILATION_ERRORS;
}
TEST_CASE("Function declaration", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
function static logic [15:0] foo(a, int b, output logic [15:0] u, v, inout w);
return a + b;
endfunction
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation);
const auto& foo = instance.memberAt<SubroutineSymbol>(0);
CHECK(!foo.isTask);
CHECK(foo.defaultLifetime == VariableLifetime::Static);
CHECK(foo.getReturnType().getBitWidth() == 16);
CHECK(foo.name == "foo");
auto args = foo.arguments;
REQUIRE(args.size() == 5);
CHECK(args[0]->getType().getBitWidth() == 1);
CHECK(args[0]->direction == FormalArgumentDirection::In);
CHECK(args[1]->getType().getBitWidth() == 32);
CHECK(args[1]->direction == FormalArgumentDirection::In);
CHECK(args[2]->getType().getBitWidth() == 16);
CHECK(args[2]->direction == FormalArgumentDirection::Out);
CHECK(args[3]->getType().getBitWidth() == 16);
CHECK(args[3]->direction == FormalArgumentDirection::Out);
CHECK(args[4]->getType().getBitWidth() == 1);
CHECK(args[4]->direction == FormalArgumentDirection::InOut);
const auto& returnStmt = foo.getBody()->as<StatementList>().list[0]->as<ReturnStatement>();
REQUIRE(returnStmt.kind == StatementKind::Return);
CHECK(!returnStmt.expr->bad());
CHECK(returnStmt.expr->type->getBitWidth() == 16);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Package declaration", "[symbols]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
parameter int blah = Foo::x;
endmodule
package Foo;
parameter int x = 4;
endpackage
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
auto& cv = compilation.getRoot().topInstances[0]->memberAt<ParameterSymbol>(0).getValue();
CHECK(cv.integer() == 4);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Recursive parameter / function") {
auto tree = SyntaxTree::fromText(R"(
module M;
localparam logic [bar()-1:0] foo = 1;
function logic[$bits(foo)-1:0] bar;
return 1;
endfunction
localparam int baz = fun();
localparam int bax = baz;
function logic[bax-1:0] fun;
return 1;
endfunction
localparam int a = stuff();
localparam int b = a;
function int stuff;
return b;
endfunction
localparam int z = stuff2();
logic [3:0] y;
function int stuff2;
return $bits(y);
endfunction
endmodule
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
Diagnostics diags = compilation.getAllDiagnostics();
// TODO: $bits() function should check argument even though it's not evaluated
//REQUIRE(diags.size() == 5);
REQUIRE(diags.size() == 4);
CHECK(diags[0].code == DiagCode::RecursiveDefinition);
CHECK(diags[1].code == DiagCode::RecursiveDefinition);
CHECK(diags[2].code == DiagCode::ExpressionNotConstant);
CHECK(diags[3].code == DiagCode::RecursiveDefinition);
//CHECK(diags[4].code == DiagCode::ExpressionNotConstant);
}<commit_msg>Add a bunch of tests for port declarations<commit_after>#include "Test.h"
TEST_CASE("Finding top level", "[binding:decls]") {
auto file1 = SyntaxTree::fromText("module A; endmodule\nmodule B; A a(); endmodule\nmodule C; endmodule");
auto file2 = SyntaxTree::fromText("module D; B b(); E e(); endmodule\nmodule E; module C; endmodule C c(); endmodule");
Compilation compilation;
compilation.addSyntaxTree(file1);
compilation.addSyntaxTree(file2);
const RootSymbol& root = compilation.getRoot();
REQUIRE(root.topInstances.size() == 2);
CHECK(root.topInstances[0]->name == "C");
CHECK(root.topInstances[1]->name == "D");
NO_COMPILATION_ERRORS;
}
TEST_CASE("Module parameterization errors", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
Leaf l1();
Leaf #(1, 2, 3, 4) l2();
Leaf #(1, 2, 3, 4, 5) l3();
Leaf #(.foo(3), .baz(9)) l4();
Leaf #(.unset(10), .bla(7)) l5();
Leaf #(.unset(10), .localp(7)) l6();
Leaf #(.unset(10), .unset(7)) l7();
Leaf #(.unset(10), 5) l8();
Leaf #(.unset(10)) l9(); // no errors on this one
endmodule
module Leaf #(
int foo = 4,
int bar = 9,
localparam int baz,
parameter bizz = baz,
parameter int unset
)();
parameter int localp;
endmodule
)");
Compilation compilation;
auto it = evalModule(tree, compilation).membersOfType<ModuleInstanceSymbol>().begin();
CHECK(it->name == "l1"); it++;
CHECK(it->name == "l2"); it++;
CHECK(it->name == "l3"); it++;
CHECK(it->name == "l4"); it++;
CHECK(it->name == "l5"); it++;
CHECK(it->name == "l6"); it++;
CHECK(it->name == "l7"); it++;
CHECK(it->name == "l8"); it++;
CHECK(it->name == "l9"); it++;
Diagnostics diags = compilation.getSemanticDiagnostics();
REQUIRE(diags.size() == 10);
CHECK(diags[0].code == DiagCode::ParamHasNoValue);
CHECK(diags[1].code == DiagCode::TooManyParamAssignments);
CHECK(diags[2].code == DiagCode::ParamHasNoValue);
CHECK(diags[3].code == DiagCode::AssignedToLocalPortParam);
CHECK(diags[4].code == DiagCode::ParameterDoesNotExist);
CHECK(diags[5].code == DiagCode::AssignedToLocalBodyParam);
CHECK(diags[6].code == DiagCode::DuplicateParamAssignment);
CHECK(diags[7].code == DiagCode::MixingOrderedAndNamedParams);
CHECK(diags[8].code == DiagCode::LocalParamNoInitializer);
CHECK(diags[9].code == DiagCode::BodyParamNoInitializer);
REQUIRE(diags[3].notes.size() == 1);
REQUIRE(diags[5].notes.size() == 1);
REQUIRE(diags[6].notes.size() == 1);
CHECK(diags[3].notes[0].code == DiagCode::NoteDeclarationHere);
CHECK(diags[5].notes[0].code == DiagCode::NoteDeclarationHere);
CHECK(diags[6].notes[0].code == DiagCode::NotePreviousUsage);
}
TEST_CASE("Module children (simple)", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
Child child();
endmodule
module Child;
Leaf leaf();
endmodule
module Leaf #(parameter int foo = 4)();
parameter localp = foo;
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation);
const auto& leaf = instance.memberAt<ModuleInstanceSymbol>(0).memberAt<ModuleInstanceSymbol>(0);
const auto& foo = leaf.find<ParameterSymbol>("foo");
CHECK(foo.getValue().integer() == 4);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Module children (conditional generate)", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
Child child();
endmodule
module Child #(parameter foo = 4)();
if (foo == 4) begin
Leaf #(1) leaf();
end
else begin
Leaf #(2) leaf();
end
endmodule
module Leaf #(parameter int foo = 4)();
parameter localp = foo;
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation);
const auto& leaf = instance
.memberAt<ModuleInstanceSymbol>(0)
.memberAt<GenerateBlockSymbol>(1)
.memberAt<ModuleInstanceSymbol>(0);
const auto& foo = leaf.find<ParameterSymbol>("foo");
CHECK(foo.getValue().integer() == 1);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Module children (loop generate)", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
for (genvar i = 0; i < 10; i += 1) begin
Leaf #(i) leaf();
end
endmodule
module Leaf #(parameter int foo)();
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation).memberAt<GenerateBlockArraySymbol>(0);
REQUIRE(instance.members().size() == 10);
for (uint32_t i = 0; i < 10; i++) {
const auto& leaf = instance.memberAt<GenerateBlockSymbol>(i).memberAt<ModuleInstanceSymbol>(1);
const auto& foo = leaf.find<ParameterSymbol>("foo");
CHECK(foo.getValue().integer() == i);
}
NO_COMPILATION_ERRORS;
}
TEST_CASE("Interface instantiation", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
interface I2CBus(
input wire clk,
input wire rst);
logic scl_i;
logic sda_i;
logic scl_o;
logic sda_o;
modport master (input clk, rst, scl_i, sda_i,
output scl_o, sda_o);
endinterface
module Top;
logic clk;
logic rst;
I2CBus bus(.*);
endmodule
)");
// TODO:
Compilation compilation;
evalModule(tree, compilation);
NO_COMPILATION_ERRORS;
}
TEST_CASE("always_comb", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module module1
#(
parameter int P1 = 4,
parameter int P2 = 5
)
(
input logic [P1-1:0] in1,
input logic [P2-1:0] in2,
input logic [3:0] in3,
output logic [P1-1:0] out1,
output logic [P1-1:0] out2,
output logic [P1-1:0] out3
);
always_comb out1 = in1;
always_comb begin
out2 = in2;
out3 = in3;
end
logic [7:0] arr1;
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation);
const auto& alwaysComb = instance.memberAt<ProceduralBlockSymbol>(14);
CHECK(alwaysComb.procedureKind == ProceduralBlockKind::AlwaysComb);
const auto& variable = instance.memberAt<VariableSymbol>(16);
CHECK(variable.getType().isIntegral());
CHECK(variable.name == "arr1");
NO_COMPILATION_ERRORS;
}
TEST_CASE("Function declaration", "[binding:modules]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
function static logic [15:0] foo(a, int b, output logic [15:0] u, v, inout w);
return a + b;
endfunction
endmodule
)");
Compilation compilation;
const auto& instance = evalModule(tree, compilation);
const auto& foo = instance.memberAt<SubroutineSymbol>(0);
CHECK(!foo.isTask);
CHECK(foo.defaultLifetime == VariableLifetime::Static);
CHECK(foo.getReturnType().getBitWidth() == 16);
CHECK(foo.name == "foo");
auto args = foo.arguments;
REQUIRE(args.size() == 5);
CHECK(args[0]->getType().getBitWidth() == 1);
CHECK(args[0]->direction == FormalArgumentDirection::In);
CHECK(args[1]->getType().getBitWidth() == 32);
CHECK(args[1]->direction == FormalArgumentDirection::In);
CHECK(args[2]->getType().getBitWidth() == 16);
CHECK(args[2]->direction == FormalArgumentDirection::Out);
CHECK(args[3]->getType().getBitWidth() == 16);
CHECK(args[3]->direction == FormalArgumentDirection::Out);
CHECK(args[4]->getType().getBitWidth() == 1);
CHECK(args[4]->direction == FormalArgumentDirection::InOut);
const auto& returnStmt = foo.getBody()->as<StatementList>().list[0]->as<ReturnStatement>();
REQUIRE(returnStmt.kind == StatementKind::Return);
CHECK(!returnStmt.expr->bad());
CHECK(returnStmt.expr->type->getBitWidth() == 16);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Package declaration", "[symbols]") {
auto tree = SyntaxTree::fromText(R"(
module Top;
parameter int blah = Foo::x;
endmodule
package Foo;
parameter int x = 4;
endpackage
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
auto& cv = compilation.getRoot().topInstances[0]->memberAt<ParameterSymbol>(0).getValue();
CHECK(cv.integer() == 4);
NO_COMPILATION_ERRORS;
}
TEST_CASE("Recursive parameter / function") {
auto tree = SyntaxTree::fromText(R"(
module M;
localparam logic [bar()-1:0] foo = 1;
function logic[$bits(foo)-1:0] bar;
return 1;
endfunction
localparam int baz = fun();
localparam int bax = baz;
function logic[bax-1:0] fun;
return 1;
endfunction
localparam int a = stuff();
localparam int b = a;
function int stuff;
return b;
endfunction
localparam int z = stuff2();
logic [3:0] y;
function int stuff2;
return $bits(y);
endfunction
endmodule
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
Diagnostics diags = compilation.getAllDiagnostics();
// TODO: $bits() function should check argument even though it's not evaluated
//REQUIRE(diags.size() == 5);
REQUIRE(diags.size() == 4);
CHECK(diags[0].code == DiagCode::RecursiveDefinition);
CHECK(diags[1].code == DiagCode::RecursiveDefinition);
CHECK(diags[2].code == DiagCode::ExpressionNotConstant);
CHECK(diags[3].code == DiagCode::RecursiveDefinition);
//CHECK(diags[4].code == DiagCode::ExpressionNotConstant);
}
TEST_CASE("Module ANSI ports") {
auto tree = SyntaxTree::fromText(R"(
module mh0 (wire x); endmodule
module mh1 (integer x); endmodule
module mh2 (inout integer x); endmodule
module mh3 ([5:0] x); endmodule
module mh4 (var x); endmodule // TODO: ERROR: direction defaults to inout which cannot be var
module mh5 (input x); endmodule
module mh6 (input var x); endmodule
module mh7 (input var integer x); endmodule
module mh8 (output x); endmodule
module mh9 (output var x); endmodule
module mh10(output signed [5:0] x); endmodule
module mh11(output integer x); endmodule
module mh12(ref [5:0] x); endmodule
module mh13(ref x [5:0]); endmodule
module mh14(wire x, y[7:0]); endmodule
module mh15(integer x, signed [5:0] y); endmodule
module mh16([5:0] x, wire y); endmodule
module mh17(input var integer x, wire y); endmodule
module mh18(output var x, input y); endmodule
module mh19(output signed [5:0] x, integer y); endmodule
module mh20(ref [5:0] x, y); endmodule
module mh21(ref x [5:0], y); endmodule
)");
Compilation compilation;
compilation.addSyntaxTree(tree);
Diagnostics diags = compilation.getAllDiagnostics();
#define checkPort(moduleName, index, dir, kind, type) {\
auto def = compilation.getDefinition(moduleName);\
REQUIRE(def);\
REQUIRE(def->ports.size() > index);\
auto& port = *def->ports[index]; \
CHECK(port.direction == dir); \
CHECK(port.portKind == kind); \
CHECK(port.getType().toString() == type); \
};
checkPort("mh0", 0, PortDirection::InOut, PortKind::Net, "logic");
checkPort("mh1", 0, PortDirection::InOut, PortKind::Net, "integer");
checkPort("mh2", 0, PortDirection::InOut, PortKind::Net, "integer");
checkPort("mh3", 0, PortDirection::InOut, PortKind::Net, "logic[5:0]");
checkPort("mh4", 0, PortDirection::InOut, PortKind::Variable, "logic");
checkPort("mh5", 0, PortDirection::In, PortKind::Net, "logic");
checkPort("mh6", 0, PortDirection::In, PortKind::Variable, "logic");
checkPort("mh7", 0, PortDirection::In, PortKind::Variable, "integer");
checkPort("mh8", 0, PortDirection::Out, PortKind::Net, "logic");
checkPort("mh9", 0, PortDirection::Out, PortKind::Variable, "logic");
checkPort("mh10", 0, PortDirection::Out, PortKind::Net, "logic signed[5:0]");
checkPort("mh11", 0, PortDirection::Out, PortKind::Variable, "integer");
checkPort("mh12", 0, PortDirection::Ref, PortKind::Variable, "logic[5:0]");
checkPort("mh13", 0, PortDirection::Ref, PortKind::Variable, "logic$[5:0]");
checkPort("mh14", 0, PortDirection::InOut, PortKind::Net, "logic");
checkPort("mh14", 1, PortDirection::InOut, PortKind::Net, "logic$[7:0]");
checkPort("mh15", 0, PortDirection::InOut, PortKind::Net, "integer");
checkPort("mh15", 1, PortDirection::InOut, PortKind::Net, "logic signed[5:0]");
checkPort("mh16", 0, PortDirection::InOut, PortKind::Net, "logic[5:0]");
checkPort("mh16", 1, PortDirection::InOut, PortKind::Net, "logic");
checkPort("mh17", 0, PortDirection::In, PortKind::Variable, "integer");
checkPort("mh17", 1, PortDirection::In, PortKind::Net, "logic");
checkPort("mh18", 0, PortDirection::Out, PortKind::Variable, "logic");
checkPort("mh18", 1, PortDirection::In, PortKind::Net, "logic");
checkPort("mh19", 0, PortDirection::Out, PortKind::Net, "logic signed[5:0]");
checkPort("mh19", 1, PortDirection::Out, PortKind::Variable, "integer");
checkPort("mh20", 0, PortDirection::Ref, PortKind::Variable, "logic[5:0]");
checkPort("mh20", 1, PortDirection::Ref, PortKind::Variable, "logic[5:0]");
checkPort("mh21", 0, PortDirection::Ref, PortKind::Variable, "logic$[5:0]");
checkPort("mh21", 1, PortDirection::Ref, PortKind::Variable, "logic");
}<|endoftext|>
|
<commit_before>/**
* EasyButton.cpp
* @author Evert Arias
* @version 1.0.0
* @license MIT
*/
#include "EasyButton.h"
void EasyButton::begin() {
pinMode(_pin, _pu_enabled ? INPUT_PULLUP : INPUT);
_current_state = digitalRead(_pin);
if (_invert) _current_state = !_current_state;
_time = millis();
_last_state = _current_state;
_changed = false;
_last_change = _time;
}
void EasyButton::onPressed(EasyButton::callback_t callback) {
mPressedCallback = callback;
}
void EasyButton::onPressedFor(uint32_t duration, EasyButton::callback_t callback) {
_held_threshold = duration;
mPressedForCallback = callback;
}
void EasyButton::onSequence(uint8_t sequences, uint32_t duration, EasyButton::callback_t callback)
{
_press_sequences = sequences;
_press_sequence_duration = duration;
mPressedSequenceCallback = callback;
}
bool EasyButton::isPressed()
{
return _current_state;
}
bool EasyButton::isReleased()
{
return !_current_state;
}
bool EasyButton::wasPressed()
{
return _current_state && _changed;
}
bool EasyButton::wasReleased()
{
return !_current_state && _changed;
}
bool EasyButton::pressedFor(uint32_t duration)
{
return _current_state && _time - _last_change >= duration;
}
bool EasyButton::releasedFor(uint32_t duration)
{
return !_current_state && _time - _last_change >= duration;
}
bool EasyButton::read() {
// get current millis.
uint32_t read_started_ms = millis();
// read pin value.
bool pinVal = digitalRead(_pin);
// if invert = true, invert Button's pin value.
if (_invert) {
pinVal = !pinVal;
};
// detect change on button's state.
if (read_started_ms - _last_change < _db_time)
{
// button's state has not changed.
_changed = false;
}
else
{
// button's state has changed.
_last_state = _current_state; // save last state.
_current_state = pinVal; // assign new state as current state from pin's value.
_changed = (_current_state != _last_state); // report state change if current state vary from last state.
// if state has changed since last read.
if (_changed) {
// save current millis as last change time.
_last_change = read_started_ms;
}
}
// call the callback functions when conditions met.
if (!_current_state && _changed) {
// button was released.
if (!_was_btn_held) {
if (_short_press_count == 0) {
_first_press_time = read_started_ms;
}
// increment presses counter.
_short_press_count++;
// button is not being held.
// call the callback function for a short press event if it exist.
if (mPressedCallback) {
mPressedCallback();
}
if (_short_press_count == _press_sequences && _press_sequence_duration >= (read_started_ms - _first_press_time)) {
if (mPressedSequenceCallback) {
mPressedSequenceCallback();
}
_short_press_count = 0;
_first_press_time = 0;
}
// if secuence timeout, reset short presses counters.
else if (_press_sequence_duration <= (read_started_ms - _first_press_time)) {
_short_press_count = 0;
_first_press_time = 0;
}
}
// button was not held.
else {
_was_btn_held = false;
}
// since button released, reset mPressedForCallbackCalled value.
_held_callback_called = false;
}
// button is not released.
else if (_current_state && _time - _last_change >= _held_threshold && mPressedForCallback) {
// button has been pressed for at least the given time
_was_btn_held = true;
// reset short presses counters.
_short_press_count = 0;
_first_press_time = 0;
// call the callback function for a long press event if it exist and if it has not been called yet.
if (mPressedForCallback && !_held_callback_called) {
_held_callback_called = true; // set as called.
mPressedForCallback();
}
}
_time = read_started_ms;
return _current_state;
}
<commit_msg>docs: fix simple typo, secuence -> sequence<commit_after>/**
* EasyButton.cpp
* @author Evert Arias
* @version 1.0.0
* @license MIT
*/
#include "EasyButton.h"
void EasyButton::begin() {
pinMode(_pin, _pu_enabled ? INPUT_PULLUP : INPUT);
_current_state = digitalRead(_pin);
if (_invert) _current_state = !_current_state;
_time = millis();
_last_state = _current_state;
_changed = false;
_last_change = _time;
}
void EasyButton::onPressed(EasyButton::callback_t callback) {
mPressedCallback = callback;
}
void EasyButton::onPressedFor(uint32_t duration, EasyButton::callback_t callback) {
_held_threshold = duration;
mPressedForCallback = callback;
}
void EasyButton::onSequence(uint8_t sequences, uint32_t duration, EasyButton::callback_t callback)
{
_press_sequences = sequences;
_press_sequence_duration = duration;
mPressedSequenceCallback = callback;
}
bool EasyButton::isPressed()
{
return _current_state;
}
bool EasyButton::isReleased()
{
return !_current_state;
}
bool EasyButton::wasPressed()
{
return _current_state && _changed;
}
bool EasyButton::wasReleased()
{
return !_current_state && _changed;
}
bool EasyButton::pressedFor(uint32_t duration)
{
return _current_state && _time - _last_change >= duration;
}
bool EasyButton::releasedFor(uint32_t duration)
{
return !_current_state && _time - _last_change >= duration;
}
bool EasyButton::read() {
// get current millis.
uint32_t read_started_ms = millis();
// read pin value.
bool pinVal = digitalRead(_pin);
// if invert = true, invert Button's pin value.
if (_invert) {
pinVal = !pinVal;
};
// detect change on button's state.
if (read_started_ms - _last_change < _db_time)
{
// button's state has not changed.
_changed = false;
}
else
{
// button's state has changed.
_last_state = _current_state; // save last state.
_current_state = pinVal; // assign new state as current state from pin's value.
_changed = (_current_state != _last_state); // report state change if current state vary from last state.
// if state has changed since last read.
if (_changed) {
// save current millis as last change time.
_last_change = read_started_ms;
}
}
// call the callback functions when conditions met.
if (!_current_state && _changed) {
// button was released.
if (!_was_btn_held) {
if (_short_press_count == 0) {
_first_press_time = read_started_ms;
}
// increment presses counter.
_short_press_count++;
// button is not being held.
// call the callback function for a short press event if it exist.
if (mPressedCallback) {
mPressedCallback();
}
if (_short_press_count == _press_sequences && _press_sequence_duration >= (read_started_ms - _first_press_time)) {
if (mPressedSequenceCallback) {
mPressedSequenceCallback();
}
_short_press_count = 0;
_first_press_time = 0;
}
// if sequence timeout, reset short presses counters.
else if (_press_sequence_duration <= (read_started_ms - _first_press_time)) {
_short_press_count = 0;
_first_press_time = 0;
}
}
// button was not held.
else {
_was_btn_held = false;
}
// since button released, reset mPressedForCallbackCalled value.
_held_callback_called = false;
}
// button is not released.
else if (_current_state && _time - _last_change >= _held_threshold && mPressedForCallback) {
// button has been pressed for at least the given time
_was_btn_held = true;
// reset short presses counters.
_short_press_count = 0;
_first_press_time = 0;
// call the callback function for a long press event if it exist and if it has not been called yet.
if (mPressedForCallback && !_held_callback_called) {
_held_callback_called = true; // set as called.
mPressedForCallback();
}
}
_time = read_started_ms;
return _current_state;
}
<|endoftext|>
|
<commit_before>/*
icqeditaccountwidget.cpp - ICQ Account Widget
Copyright (c) 2003 by Chris TenHarmsel <tenharmsel@staticmethod.net>
Kopete (c) 2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "icqeditaccountwidget.h"
#include "ui_icqeditaccountui.h"
#include <qlayout.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qpushbutton.h>
#include <qvalidator.h>
#include <QLatin1String>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kurllabel.h>
#include <kdatewidget.h>
#include <ktoolinvocation.h>
#include <kpassworddialog.h>
#include <kmessagebox.h>
#include "kopetepassword.h"
#include "kopetepasswordwidget.h"
#include "icqprotocol.h"
#include "icqaccount.h"
#include "icqcontact.h"
#include "oscarprivacyengine.h"
#include "oscarsettings.h"
#include "icqchangepassworddialog.h"
ICQEditAccountWidget::ICQEditAccountWidget(ICQProtocol *protocol,
Kopete::Account *account, QWidget *parent)
: QWidget(parent), KopeteEditAccountWidget(account)
{
kDebug(14153) << k_funcinfo << "Called.";
mAccount=dynamic_cast<ICQAccount*>(account);
mProtocol=protocol;
m_visibleEngine = 0;
m_invisibleEngine = 0;
m_ignoreEngine = 0;
mAccountSettings = new Ui::ICQEditAccountUI();
mAccountSettings->setupUi( this );
mProtocol->fillComboFromTable( mAccountSettings->encodingCombo, mProtocol->encodings() );
//Setup the edtAccountId
QRegExp rx("[0-9]{9}");
QValidator* validator = new QRegExpValidator( rx, this );
mAccountSettings->edtAccountId->setValidator(validator);
// Read in the settings from the account if it exists
if(mAccount)
{
mAccountSettings->edtAccountId->setText(mAccount->accountId());
// TODO: Remove me after we can change Account IDs (Matt)
mAccountSettings->edtAccountId->setDisabled(true);
mAccountSettings->mPasswordWidget->load(&mAccount->password());
mAccountSettings->chkAutoLogin->setChecked(mAccount->excludeConnect());
QString serverEntry = mAccount->configGroup()->readEntry("Server", "login.oscar.aol.com");
int portEntry = mAccount->configGroup()->readEntry("Port", 5190);
if ( serverEntry != "login.oscar.aol.com" || ( portEntry != 5190) )
mAccountSettings->optionOverrideServer->setChecked( true );
mAccountSettings->edtServerAddress->setText( serverEntry );
mAccountSettings->edtServerPort->setValue( portEntry );
bool configChecked = mAccount->configGroup()->readEntry( "RequireAuth", false );
mAccountSettings->chkRequireAuth->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "RespectRequireAuth", true );
mAccountSettings->chkRespectRequireAuth->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "HideIP", true );
mAccountSettings->chkHideIP->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "WebAware", false );
mAccountSettings->chkWebAware->setChecked( configChecked );
int configValue = mAccount->configGroup()->readEntry( "DefaultEncoding", 4 );
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
configValue );
//set filetransfer stuff
configChecked = mAccount->configGroup()->readEntry( "FileProxy", false );
mAccountSettings->chkFileProxy->setChecked( configChecked );
configValue = mAccount->configGroup()->readEntry( "FirstPort", 5190 );
mAccountSettings->sbxFirstPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "LastPort", 5199 );
mAccountSettings->sbxLastPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "Timeout", 10 );
mAccountSettings->sbxTimeout->setValue( configValue );
// Global Identity
mAccountSettings->chkGlobalIdentity->setChecked( mAccount->configGroup()->readEntry("ExcludeGlobalIdentity", false) );
if ( mAccount->engine()->isActive() )
{
m_visibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Visible );
m_visibleEngine->setAllContactsView( mAccountSettings->visibleAllContacts );
m_visibleEngine->setContactsView( mAccountSettings->visibleContacts );
QObject::connect( mAccountSettings->visibleAdd, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->visibleRemove, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotRemove() ) );
m_invisibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Invisible );
m_invisibleEngine->setAllContactsView( mAccountSettings->invisibleAllContacts );
m_invisibleEngine->setContactsView( mAccountSettings->invisibleContacts );
QObject::connect( mAccountSettings->invisibleAdd, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->invisibleRemove, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotRemove() ) );
m_ignoreEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Ignore );
m_ignoreEngine->setAllContactsView( mAccountSettings->ignoreAllContacts );
m_ignoreEngine->setContactsView( mAccountSettings->ignoreContacts );
QObject::connect( mAccountSettings->ignoreAdd, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->ignoreRemove, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotRemove() ) );
}
}
else
{
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
4 );
}
if ( !mAccount || !mAccount->engine()->isActive() )
{
mAccountSettings->tabVisible->setEnabled( false );
mAccountSettings->tabInvisible->setEnabled( false );
mAccountSettings->tabIgnore->setEnabled( false );
mAccountSettings->buttonChangePassword->setEnabled( false );
}
QObject::connect(mAccountSettings->buttonRegister, SIGNAL(clicked()), this, SLOT(slotOpenRegister()));
QObject::connect(mAccountSettings->buttonChangePassword, SIGNAL(clicked()), this, SLOT(slotChangePassword()));
/* Set tab order to password custom widget correctly */
QWidget::setTabOrder( mAccountSettings->edtAccountId, mAccountSettings->mPasswordWidget->mRemembered );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mRemembered, mAccountSettings->mPasswordWidget->mPassword );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mPassword, mAccountSettings->chkAutoLogin );
}
ICQEditAccountWidget::~ICQEditAccountWidget()
{
if ( m_visibleEngine )
delete m_visibleEngine;
if ( m_invisibleEngine )
delete m_invisibleEngine;
if ( m_ignoreEngine )
delete m_ignoreEngine;
}
Kopete::Account *ICQEditAccountWidget::apply()
{
kDebug(14153) << k_funcinfo << "Called.";
// If this is a new account, create it
if (!mAccount)
{
kDebug(14153) << k_funcinfo << "Creating a new account";
mAccount = new ICQAccount(mProtocol, mAccountSettings->edtAccountId->text());
if(!mAccount)
return NULL;
}
mAccountSettings->mPasswordWidget->save(&mAccount->password());
mAccount->setExcludeConnect(mAccountSettings->chkAutoLogin->isChecked());
Oscar::Settings* oscarSettings = mAccount->engine()->clientSettings();
bool configChecked = mAccountSettings->chkRequireAuth->isChecked();
mAccount->configGroup()->writeEntry( "RequireAuth", configChecked );
oscarSettings->setRequireAuth( configChecked );
configChecked = mAccountSettings->chkRespectRequireAuth->isChecked();
mAccount->configGroup()->writeEntry( "RespectRequireAuth", configChecked );
oscarSettings->setRespectRequireAuth( configChecked );
configChecked = mAccountSettings->chkHideIP->isChecked();
mAccount->configGroup()->writeEntry( "HideIP", configChecked );
oscarSettings->setHideIP( configChecked );
configChecked = mAccountSettings->chkWebAware->isChecked();
mAccount->configGroup()->writeEntry( "WebAware", configChecked );
oscarSettings->setWebAware( configChecked );
int configValue = mProtocol->getCodeForCombo( mAccountSettings->encodingCombo,
mProtocol->encodings() );
mAccount->configGroup()->writeEntry( "DefaultEncoding", configValue );
if ( mAccountSettings->optionOverrideServer->isChecked() )
{
mAccount->setServerAddress(mAccountSettings->edtServerAddress->text());
mAccount->setServerPort(mAccountSettings->edtServerPort->value());
}
else
{
mAccount->setServerAddress("login.oscar.aol.com");
mAccount->setServerPort(5190);
}
//set filetransfer stuff
configChecked = mAccountSettings->chkFileProxy->isChecked();
mAccount->configGroup()->writeEntry( "FileProxy", configChecked );
oscarSettings->setFileProxy( configChecked );
configValue = mAccountSettings->sbxFirstPort->value();
mAccount->configGroup()->writeEntry( "FirstPort", configValue );
oscarSettings->setFirstPort( configValue );
configValue = mAccountSettings->sbxLastPort->value();
mAccount->configGroup()->writeEntry( "LastPort", configValue );
oscarSettings->setLastPort( configValue );
configValue = mAccountSettings->sbxTimeout->value();
mAccount->configGroup()->writeEntry( "Timeout", configValue );
oscarSettings->setTimeout( configValue );
// Global Identity
mAccount->configGroup()->writeEntry( "ExcludeGlobalIdentity", mAccountSettings->chkGlobalIdentity->isChecked() );
if ( mAccount->engine()->isActive() )
{
if ( m_visibleEngine )
m_visibleEngine->storeChanges();
if ( m_invisibleEngine )
m_invisibleEngine->storeChanges();
if ( m_ignoreEngine )
m_ignoreEngine->storeChanges();
//Update Oscar settings
static_cast<ICQMyselfContact*>( mAccount->myself() )->fetchShortInfo();
}
return mAccount;
}
bool ICQEditAccountWidget::validateData()
{
kDebug(14153) << k_funcinfo << "Called.";
bool bOk;
QString userId = mAccountSettings->edtAccountId->text();
qulonglong uid = userId.toULongLong( &bOk );
if( !bOk || uid == 0 || userId.isEmpty() )
{ KMessageBox::queuedMessageBox(this, KMessageBox::Sorry,
i18n("<qt>You must enter a valid ICQ Nr.</qt>"), i18n("ICQ"));
return false;
}
// No need to check port, min and max values are properly defined in .ui
if (mAccountSettings->edtServerAddress->text().isEmpty())
return false;
// Seems good to me
kDebug(14153) << k_funcinfo <<
"Account data validated successfully." << endl;
return true;
}
void ICQEditAccountWidget::slotOpenRegister()
{
KToolInvocation::invokeBrowser( QLatin1String("http://go.icq.com/register/") );
}
void ICQEditAccountWidget::slotChangePassword()
{
ICQChangePasswordDialog *passwordDlg = new ICQChangePasswordDialog( mAccount, this );
passwordDlg->exec();
delete passwordDlg;
}
#include "icqeditaccountwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
// kate: indent-mode csands; space-indent off; replace-tabs off;
<commit_msg>default to windows-1251 for russian systems<commit_after>/*
icqeditaccountwidget.cpp - ICQ Account Widget
Copyright (c) 2003 by Chris TenHarmsel <tenharmsel@staticmethod.net>
Kopete (c) 2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "icqeditaccountwidget.h"
#include "ui_icqeditaccountui.h"
#include <qlayout.h>
#include <qcheckbox.h>
#include <qlineedit.h>
#include <qspinbox.h>
#include <qpushbutton.h>
#include <qvalidator.h>
#include <QLatin1String>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kurllabel.h>
#include <kdatewidget.h>
#include <ktoolinvocation.h>
#include <kpassworddialog.h>
#include <kmessagebox.h>
#include "kopetepassword.h"
#include "kopetepasswordwidget.h"
#include "icqprotocol.h"
#include "icqaccount.h"
#include "icqcontact.h"
#include "oscarprivacyengine.h"
#include "oscarsettings.h"
#include "icqchangepassworddialog.h"
ICQEditAccountWidget::ICQEditAccountWidget(ICQProtocol *protocol,
Kopete::Account *account, QWidget *parent)
: QWidget(parent), KopeteEditAccountWidget(account)
{
kDebug(14153) << k_funcinfo << "Called.";
mAccount=dynamic_cast<ICQAccount*>(account);
mProtocol=protocol;
m_visibleEngine = 0;
m_invisibleEngine = 0;
m_ignoreEngine = 0;
mAccountSettings = new Ui::ICQEditAccountUI();
mAccountSettings->setupUi( this );
mProtocol->fillComboFromTable( mAccountSettings->encodingCombo, mProtocol->encodings() );
//Setup the edtAccountId
QRegExp rx("[0-9]{9}");
QValidator* validator = new QRegExpValidator( rx, this );
mAccountSettings->edtAccountId->setValidator(validator);
// Read in the settings from the account if it exists
if(mAccount)
{
mAccountSettings->edtAccountId->setText(mAccount->accountId());
// TODO: Remove me after we can change Account IDs (Matt)
mAccountSettings->edtAccountId->setDisabled(true);
mAccountSettings->mPasswordWidget->load(&mAccount->password());
mAccountSettings->chkAutoLogin->setChecked(mAccount->excludeConnect());
QString serverEntry = mAccount->configGroup()->readEntry("Server", "login.oscar.aol.com");
int portEntry = mAccount->configGroup()->readEntry("Port", 5190);
if ( serverEntry != "login.oscar.aol.com" || ( portEntry != 5190) )
mAccountSettings->optionOverrideServer->setChecked( true );
mAccountSettings->edtServerAddress->setText( serverEntry );
mAccountSettings->edtServerPort->setValue( portEntry );
bool configChecked = mAccount->configGroup()->readEntry( "RequireAuth", false );
mAccountSettings->chkRequireAuth->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "RespectRequireAuth", true );
mAccountSettings->chkRespectRequireAuth->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "HideIP", true );
mAccountSettings->chkHideIP->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "WebAware", false );
mAccountSettings->chkWebAware->setChecked( configChecked );
int configValue = mAccount->configGroup()->readEntry( "DefaultEncoding", 4 );
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
configValue );
//set filetransfer stuff
configChecked = mAccount->configGroup()->readEntry( "FileProxy", false );
mAccountSettings->chkFileProxy->setChecked( configChecked );
configValue = mAccount->configGroup()->readEntry( "FirstPort", 5190 );
mAccountSettings->sbxFirstPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "LastPort", 5199 );
mAccountSettings->sbxLastPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "Timeout", 10 );
mAccountSettings->sbxTimeout->setValue( configValue );
// Global Identity
mAccountSettings->chkGlobalIdentity->setChecked( mAccount->configGroup()->readEntry("ExcludeGlobalIdentity", false) );
if ( mAccount->engine()->isActive() )
{
m_visibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Visible );
m_visibleEngine->setAllContactsView( mAccountSettings->visibleAllContacts );
m_visibleEngine->setContactsView( mAccountSettings->visibleContacts );
QObject::connect( mAccountSettings->visibleAdd, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->visibleRemove, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotRemove() ) );
m_invisibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Invisible );
m_invisibleEngine->setAllContactsView( mAccountSettings->invisibleAllContacts );
m_invisibleEngine->setContactsView( mAccountSettings->invisibleContacts );
QObject::connect( mAccountSettings->invisibleAdd, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->invisibleRemove, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotRemove() ) );
m_ignoreEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Ignore );
m_ignoreEngine->setAllContactsView( mAccountSettings->ignoreAllContacts );
m_ignoreEngine->setContactsView( mAccountSettings->ignoreContacts );
QObject::connect( mAccountSettings->ignoreAdd, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->ignoreRemove, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotRemove() ) );
}
}
else
{
int encodingId=4; //see icqprotocol.cpp for mappings
if (KGlobal::locale()->language().startsWith("ru"))
encodingId=2251;
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
encodingId );
}
if ( !mAccount || !mAccount->engine()->isActive() )
{
mAccountSettings->tabVisible->setEnabled( false );
mAccountSettings->tabInvisible->setEnabled( false );
mAccountSettings->tabIgnore->setEnabled( false );
mAccountSettings->buttonChangePassword->setEnabled( false );
}
QObject::connect(mAccountSettings->buttonRegister, SIGNAL(clicked()), this, SLOT(slotOpenRegister()));
QObject::connect(mAccountSettings->buttonChangePassword, SIGNAL(clicked()), this, SLOT(slotChangePassword()));
/* Set tab order to password custom widget correctly */
QWidget::setTabOrder( mAccountSettings->edtAccountId, mAccountSettings->mPasswordWidget->mRemembered );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mRemembered, mAccountSettings->mPasswordWidget->mPassword );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mPassword, mAccountSettings->chkAutoLogin );
}
ICQEditAccountWidget::~ICQEditAccountWidget()
{
if ( m_visibleEngine )
delete m_visibleEngine;
if ( m_invisibleEngine )
delete m_invisibleEngine;
if ( m_ignoreEngine )
delete m_ignoreEngine;
}
Kopete::Account *ICQEditAccountWidget::apply()
{
kDebug(14153) << k_funcinfo << "Called.";
// If this is a new account, create it
if (!mAccount)
{
kDebug(14153) << k_funcinfo << "Creating a new account";
mAccount = new ICQAccount(mProtocol, mAccountSettings->edtAccountId->text());
if(!mAccount)
return NULL;
}
mAccountSettings->mPasswordWidget->save(&mAccount->password());
mAccount->setExcludeConnect(mAccountSettings->chkAutoLogin->isChecked());
Oscar::Settings* oscarSettings = mAccount->engine()->clientSettings();
bool configChecked = mAccountSettings->chkRequireAuth->isChecked();
mAccount->configGroup()->writeEntry( "RequireAuth", configChecked );
oscarSettings->setRequireAuth( configChecked );
configChecked = mAccountSettings->chkRespectRequireAuth->isChecked();
mAccount->configGroup()->writeEntry( "RespectRequireAuth", configChecked );
oscarSettings->setRespectRequireAuth( configChecked );
configChecked = mAccountSettings->chkHideIP->isChecked();
mAccount->configGroup()->writeEntry( "HideIP", configChecked );
oscarSettings->setHideIP( configChecked );
configChecked = mAccountSettings->chkWebAware->isChecked();
mAccount->configGroup()->writeEntry( "WebAware", configChecked );
oscarSettings->setWebAware( configChecked );
int configValue = mProtocol->getCodeForCombo( mAccountSettings->encodingCombo,
mProtocol->encodings() );
mAccount->configGroup()->writeEntry( "DefaultEncoding", configValue );
if ( mAccountSettings->optionOverrideServer->isChecked() )
{
mAccount->setServerAddress(mAccountSettings->edtServerAddress->text());
mAccount->setServerPort(mAccountSettings->edtServerPort->value());
}
else
{
mAccount->setServerAddress("login.oscar.aol.com");
mAccount->setServerPort(5190);
}
//set filetransfer stuff
configChecked = mAccountSettings->chkFileProxy->isChecked();
mAccount->configGroup()->writeEntry( "FileProxy", configChecked );
oscarSettings->setFileProxy( configChecked );
configValue = mAccountSettings->sbxFirstPort->value();
mAccount->configGroup()->writeEntry( "FirstPort", configValue );
oscarSettings->setFirstPort( configValue );
configValue = mAccountSettings->sbxLastPort->value();
mAccount->configGroup()->writeEntry( "LastPort", configValue );
oscarSettings->setLastPort( configValue );
configValue = mAccountSettings->sbxTimeout->value();
mAccount->configGroup()->writeEntry( "Timeout", configValue );
oscarSettings->setTimeout( configValue );
// Global Identity
mAccount->configGroup()->writeEntry( "ExcludeGlobalIdentity", mAccountSettings->chkGlobalIdentity->isChecked() );
if ( mAccount->engine()->isActive() )
{
if ( m_visibleEngine )
m_visibleEngine->storeChanges();
if ( m_invisibleEngine )
m_invisibleEngine->storeChanges();
if ( m_ignoreEngine )
m_ignoreEngine->storeChanges();
//Update Oscar settings
static_cast<ICQMyselfContact*>( mAccount->myself() )->fetchShortInfo();
}
return mAccount;
}
bool ICQEditAccountWidget::validateData()
{
kDebug(14153) << k_funcinfo << "Called.";
bool bOk;
QString userId = mAccountSettings->edtAccountId->text();
qulonglong uid = userId.toULongLong( &bOk );
if( !bOk || uid == 0 || userId.isEmpty() )
{ KMessageBox::queuedMessageBox(this, KMessageBox::Sorry,
i18n("<qt>You must enter a valid ICQ Nr.</qt>"), i18n("ICQ"));
return false;
}
// No need to check port, min and max values are properly defined in .ui
if (mAccountSettings->edtServerAddress->text().isEmpty())
return false;
// Seems good to me
kDebug(14153) << k_funcinfo <<
"Account data validated successfully." << endl;
return true;
}
void ICQEditAccountWidget::slotOpenRegister()
{
KToolInvocation::invokeBrowser( QLatin1String("http://go.icq.com/register/") );
}
void ICQEditAccountWidget::slotChangePassword()
{
ICQChangePasswordDialog *passwordDlg = new ICQChangePasswordDialog( mAccount, this );
passwordDlg->exec();
delete passwordDlg;
}
#include "icqeditaccountwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
// kate: indent-mode csands; space-indent off; replace-tabs off;
<|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 <winmeta.h>
#include "WindowsEventLog.h"
#include "UnicodeConversion.h"
#include "utils/Deleters.h"
#include "utils/ScopeGuard.h"
#include <algorithm>
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace wel {
void WindowsEventLogMetadataImpl::renderMetadata() {
DWORD status = ERROR_SUCCESS;
DWORD dwBufferSize = 0;
DWORD dwBufferUsed = 0;
DWORD dwPropertyCount = 0;
std::unique_ptr< EVT_VARIANT, utils::FreeDeleter> rendered_values;
auto context = EvtCreateRenderContext(0, NULL, EvtRenderContextSystem);
if (context == NULL) {
return;
}
utils::ScopeGuard contextGuard([&context](){
EvtClose(context);
});
if (!EvtRender(context, event_ptr_, EvtRenderEventValues, dwBufferSize, nullptr, &dwBufferUsed, &dwPropertyCount))
{
if (ERROR_INSUFFICIENT_BUFFER == (status = GetLastError()))
{
dwBufferSize = dwBufferUsed;
rendered_values = std::unique_ptr<EVT_VARIANT, utils::FreeDeleter>((PEVT_VARIANT)(malloc(dwBufferSize)));
if (rendered_values)
{
EvtRender(context, event_ptr_, EvtRenderEventValues, dwBufferSize, rendered_values.get(), &dwBufferUsed, &dwPropertyCount);
}
}
else {
return;
}
if (ERROR_SUCCESS != (status = GetLastError()))
{
return;
}
}
event_timestamp_ = static_cast<PEVT_VARIANT>( rendered_values.get())[EvtSystemTimeCreated].FileTimeVal;
SYSTEMTIME st;
FILETIME ft;
ft.dwHighDateTime = (DWORD)((event_timestamp_ >> 32) & 0xFFFFFFFF);
ft.dwLowDateTime = (DWORD)(event_timestamp_ & 0xFFFFFFFF);
FileTimeToSystemTime(&ft, &st);
std::stringstream datestr;
std::string period = "AM";
auto hour = st.wHour;
if (hour >= 12 && hour < 24)
period = "PM";
if (hour >= 12)
hour -= 12;
datestr << st.wMonth << "/" << st.wDay << "/" << st.wYear << " " << std::setfill('0') << std::setw(2) << hour << ":" << std::setfill('0') << std::setw(2) << st.wMinute << ":" << std::setfill('0') << std::setw(2) << st.wSecond << " " << period;
event_timestamp_str_ = datestr.str();
auto level = static_cast<PEVT_VARIANT>(rendered_values.get())[EvtSystemLevel];
auto keyword = static_cast<PEVT_VARIANT>(rendered_values.get())[EvtSystemKeywords];
if (level.Type == EvtVarTypeByte) {
switch (level.ByteVal)
{
case WINEVENT_LEVEL_CRITICAL:
case WINEVENT_LEVEL_ERROR:
event_type_ = "Error";
event_type_index_ = 1;
break;
case WINEVENT_LEVEL_WARNING:
event_type_ = "Warning";
event_type_index_ = 2;
break;
case WINEVENT_LEVEL_INFO:
case WINEVENT_LEVEL_VERBOSE:
event_type_ = "Information";
event_type_index_ = 4;
break;
default:
event_type_index_ = 0;
};
}
else {
event_type_ = "N/A";
}
if (keyword.UInt64Val & WINEVENT_KEYWORD_AUDIT_SUCCESS) {
event_type_ = "Success Audit";
event_type_index_ = 8;
} else if (keyword.UInt64Val & EVENTLOG_AUDIT_FAILURE) {
event_type_ = "Failure Audit";
event_type_index_ = 16;
}
}
std::string WindowsEventLogMetadataImpl::getEventData(EVT_FORMAT_MESSAGE_FLAGS flags) const {
LPWSTR string_buffer = NULL;
DWORD string_buffer_size = 0;
DWORD string_buffer_used = 0;
DWORD result = 0;
std::string event_data;
if (metadata_ptr_ == NULL | event_ptr_ == NULL) {
return event_data;
}
if (!EvtFormatMessage(metadata_ptr_, event_ptr_, 0, 0, NULL, flags, string_buffer_size, string_buffer, &string_buffer_used)) {
result = GetLastError();
if (ERROR_INSUFFICIENT_BUFFER == result) {
string_buffer_size = string_buffer_used;
string_buffer = (LPWSTR) malloc(string_buffer_size * sizeof(WCHAR));
if (string_buffer) {
if ((EvtFormatMessageKeyword == flags))
string_buffer[string_buffer_size - 1] = L'\0';
EvtFormatMessage(metadata_ptr_, event_ptr_, 0, 0, NULL, flags, string_buffer_size, string_buffer, &string_buffer_used);
if ((EvtFormatMessageKeyword == flags))
string_buffer[string_buffer_used - 1] = L'\0';
std::wstring str(string_buffer);
event_data = std::string(str.begin(), str.end());
free(string_buffer);
}
}
}
return event_data;
}
std::string WindowsEventLogHandler::getEventMessage(EVT_HANDLE eventHandle) const
{
std::string returnValue;
std::unique_ptr<WCHAR, utils::FreeDeleter> pBuffer;
DWORD dwBufferSize = 0;
DWORD dwBufferUsed = 0;
DWORD status = 0;
EvtFormatMessage(metadata_provider_, eventHandle, 0, 0, NULL, EvtFormatMessageEvent, dwBufferSize, pBuffer.get(), &dwBufferUsed);
if (dwBufferUsed == 0) {
return returnValue;
}
// we need to get the size of the buffer
status = GetLastError();
if (ERROR_INSUFFICIENT_BUFFER == status) {
dwBufferSize = dwBufferUsed;
/* All C++ examples use malloc and even HeapAlloc in some cases. To avoid any problems ( with EvtFormatMessage calling
free for example ) we will continue to use malloc and use a custom deleter with unique_ptr.
'*/
pBuffer = std::unique_ptr<WCHAR, utils::FreeDeleter>((LPWSTR)malloc(dwBufferSize * sizeof(WCHAR)));
if (!pBuffer) {
return returnValue;
}
EvtFormatMessage(metadata_provider_, eventHandle, 0, 0, NULL, EvtFormatMessageEvent, dwBufferSize, pBuffer.get(), &dwBufferUsed);
}
if (ERROR_EVT_MESSAGE_NOT_FOUND == status || ERROR_EVT_MESSAGE_ID_NOT_FOUND == status) {
return returnValue;
}
// convert wstring to std::string
return to_string(pBuffer.get());
}
void WindowsEventLogHeader::setDelimiter(const std::string &delim) {
delimiter_ = delim;
}
std::string WindowsEventLogHeader::createDefaultDelimiter(size_t max, size_t length) const {
if (max > length) {
return ":" + std::string(max - length, ' ');
}
else {
return ": ";
}
}
EVT_HANDLE WindowsEventLogHandler::getMetadata() const {
return metadata_provider_;
}
} /* namespace wel */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */
<commit_msg>MINIFICPP-1302 - ConsumeWindowsEventLog sometimes renders event with invalid time format<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 <winmeta.h>
#include "WindowsEventLog.h"
#include "UnicodeConversion.h"
#include "utils/Deleters.h"
#include "utils/ScopeGuard.h"
#include <algorithm>
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace wel {
void WindowsEventLogMetadataImpl::renderMetadata() {
DWORD status = ERROR_SUCCESS;
DWORD dwBufferSize = 0;
DWORD dwBufferUsed = 0;
DWORD dwPropertyCount = 0;
std::unique_ptr< EVT_VARIANT, utils::FreeDeleter> rendered_values;
auto context = EvtCreateRenderContext(0, NULL, EvtRenderContextSystem);
if (context == NULL) {
return;
}
utils::ScopeGuard contextGuard([&context](){
EvtClose(context);
});
if (!EvtRender(context, event_ptr_, EvtRenderEventValues, dwBufferSize, nullptr, &dwBufferUsed, &dwPropertyCount))
{
if (ERROR_INSUFFICIENT_BUFFER == (status = GetLastError()))
{
dwBufferSize = dwBufferUsed;
rendered_values = std::unique_ptr<EVT_VARIANT, utils::FreeDeleter>((PEVT_VARIANT)(malloc(dwBufferSize)));
if (rendered_values)
{
EvtRender(context, event_ptr_, EvtRenderEventValues, dwBufferSize, rendered_values.get(), &dwBufferUsed, &dwPropertyCount);
}
}
else {
return;
}
if (ERROR_SUCCESS != (status = GetLastError()))
{
return;
}
}
event_timestamp_ = static_cast<PEVT_VARIANT>( rendered_values.get())[EvtSystemTimeCreated].FileTimeVal;
SYSTEMTIME st;
FILETIME ft;
ft.dwHighDateTime = (DWORD)((event_timestamp_ >> 32) & 0xFFFFFFFF);
ft.dwLowDateTime = (DWORD)(event_timestamp_ & 0xFFFFFFFF);
FileTimeToSystemTime(&ft, &st);
std::stringstream datestr;
std::string period = "AM";
auto hour = st.wHour;
if (hour >= 12 && hour < 24)
period = "PM";
if (hour > 12)
hour -= 12;
if (hour == 0)
hour = 12;
datestr << st.wMonth << "/" << st.wDay << "/" << st.wYear << " " << std::setfill('0') << std::setw(2) << hour << ":" << std::setfill('0') << std::setw(2) << st.wMinute << ":" << std::setfill('0') << std::setw(2) << st.wSecond << " " << period;
event_timestamp_str_ = datestr.str();
auto level = static_cast<PEVT_VARIANT>(rendered_values.get())[EvtSystemLevel];
auto keyword = static_cast<PEVT_VARIANT>(rendered_values.get())[EvtSystemKeywords];
if (level.Type == EvtVarTypeByte) {
switch (level.ByteVal)
{
case WINEVENT_LEVEL_CRITICAL:
case WINEVENT_LEVEL_ERROR:
event_type_ = "Error";
event_type_index_ = 1;
break;
case WINEVENT_LEVEL_WARNING:
event_type_ = "Warning";
event_type_index_ = 2;
break;
case WINEVENT_LEVEL_INFO:
case WINEVENT_LEVEL_VERBOSE:
event_type_ = "Information";
event_type_index_ = 4;
break;
default:
event_type_index_ = 0;
};
}
else {
event_type_ = "N/A";
}
if (keyword.UInt64Val & WINEVENT_KEYWORD_AUDIT_SUCCESS) {
event_type_ = "Success Audit";
event_type_index_ = 8;
} else if (keyword.UInt64Val & EVENTLOG_AUDIT_FAILURE) {
event_type_ = "Failure Audit";
event_type_index_ = 16;
}
}
std::string WindowsEventLogMetadataImpl::getEventData(EVT_FORMAT_MESSAGE_FLAGS flags) const {
LPWSTR string_buffer = NULL;
DWORD string_buffer_size = 0;
DWORD string_buffer_used = 0;
DWORD result = 0;
std::string event_data;
if (metadata_ptr_ == NULL | event_ptr_ == NULL) {
return event_data;
}
if (!EvtFormatMessage(metadata_ptr_, event_ptr_, 0, 0, NULL, flags, string_buffer_size, string_buffer, &string_buffer_used)) {
result = GetLastError();
if (ERROR_INSUFFICIENT_BUFFER == result) {
string_buffer_size = string_buffer_used;
string_buffer = (LPWSTR) malloc(string_buffer_size * sizeof(WCHAR));
if (string_buffer) {
if ((EvtFormatMessageKeyword == flags))
string_buffer[string_buffer_size - 1] = L'\0';
EvtFormatMessage(metadata_ptr_, event_ptr_, 0, 0, NULL, flags, string_buffer_size, string_buffer, &string_buffer_used);
if ((EvtFormatMessageKeyword == flags))
string_buffer[string_buffer_used - 1] = L'\0';
std::wstring str(string_buffer);
event_data = std::string(str.begin(), str.end());
free(string_buffer);
}
}
}
return event_data;
}
std::string WindowsEventLogHandler::getEventMessage(EVT_HANDLE eventHandle) const
{
std::string returnValue;
std::unique_ptr<WCHAR, utils::FreeDeleter> pBuffer;
DWORD dwBufferSize = 0;
DWORD dwBufferUsed = 0;
DWORD status = 0;
EvtFormatMessage(metadata_provider_, eventHandle, 0, 0, NULL, EvtFormatMessageEvent, dwBufferSize, pBuffer.get(), &dwBufferUsed);
if (dwBufferUsed == 0) {
return returnValue;
}
// we need to get the size of the buffer
status = GetLastError();
if (ERROR_INSUFFICIENT_BUFFER == status) {
dwBufferSize = dwBufferUsed;
/* All C++ examples use malloc and even HeapAlloc in some cases. To avoid any problems ( with EvtFormatMessage calling
free for example ) we will continue to use malloc and use a custom deleter with unique_ptr.
'*/
pBuffer = std::unique_ptr<WCHAR, utils::FreeDeleter>((LPWSTR)malloc(dwBufferSize * sizeof(WCHAR)));
if (!pBuffer) {
return returnValue;
}
EvtFormatMessage(metadata_provider_, eventHandle, 0, 0, NULL, EvtFormatMessageEvent, dwBufferSize, pBuffer.get(), &dwBufferUsed);
}
if (ERROR_EVT_MESSAGE_NOT_FOUND == status || ERROR_EVT_MESSAGE_ID_NOT_FOUND == status) {
return returnValue;
}
// convert wstring to std::string
return to_string(pBuffer.get());
}
void WindowsEventLogHeader::setDelimiter(const std::string &delim) {
delimiter_ = delim;
}
std::string WindowsEventLogHeader::createDefaultDelimiter(size_t max, size_t length) const {
if (max > length) {
return ":" + std::string(max - length, ' ');
}
else {
return ": ";
}
}
EVT_HANDLE WindowsEventLogHandler::getMetadata() const {
return metadata_provider_;
}
} /* namespace wel */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */
<|endoftext|>
|
<commit_before>/*
icqeditaccountwidget.cpp - ICQ Account Widget
Copyright (c) 2003 by Chris TenHarmsel <tenharmsel@staticmethod.net>
Kopete (c) 2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "icqeditaccountwidget.h"
#include "ui_icqeditaccountui.h"
#include <QLayout>
#include <QCheckbox>
#include <QLineedit>
#include <QSpinBox>
#include <QPushButton>
#include <QValidator>
#include <QLatin1String>
#include <QLocale>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kurllabel.h>
#include <kdatewidget.h>
#include <ktoolinvocation.h>
#include <kpassworddialog.h>
#include <kmessagebox.h>
#include "kopetepassword.h"
#include "kopetepasswordwidget.h"
#include "icqprotocol.h"
#include "icqaccount.h"
#include "icqcontact.h"
#include "oscarprivacyengine.h"
#include "oscarsettings.h"
#include "icqchangepassworddialog.h"
ICQEditAccountWidget::ICQEditAccountWidget(ICQProtocol *protocol,
Kopete::Account *account, QWidget *parent)
: QWidget(parent), KopeteEditAccountWidget(account)
{
kDebug(14153) << "Called.";
mAccount=dynamic_cast<ICQAccount*>(account);
mProtocol=protocol;
m_visibleEngine = 0;
m_invisibleEngine = 0;
m_ignoreEngine = 0;
mAccountSettings = new Ui::ICQEditAccountUI();
mAccountSettings->setupUi( this );
mProtocol->fillComboFromTable( mAccountSettings->encodingCombo, mProtocol->encodings() );
//Setup the edtAccountId
QRegExp rx("[0-9]{9}");
QValidator* validator = new QRegExpValidator( rx, this );
mAccountSettings->edtAccountId->setValidator(validator);
// Read in the settings from the account if it exists
if(mAccount)
{
mAccountSettings->edtAccountId->setText(mAccount->accountId());
// TODO: Remove me after we can change Account IDs (Matt)
mAccountSettings->edtAccountId->setReadOnly(true);
mAccountSettings->mPasswordWidget->load(&mAccount->password());
mAccountSettings->chkAutoLogin->setChecked(mAccount->excludeConnect());
QString serverEntry = mAccount->configGroup()->readEntry("Server", "login.oscar.aol.com");
int portEntry = mAccount->configGroup()->readEntry("Port", 5190);
if ( serverEntry != "login.oscar.aol.com" || ( portEntry != 5190) )
mAccountSettings->optionOverrideServer->setChecked( true );
mAccountSettings->edtServerAddress->setText( serverEntry );
mAccountSettings->edtServerPort->setValue( portEntry );
bool configChecked = mAccount->configGroup()->readEntry( "RequireAuth", false );
mAccountSettings->chkRequireAuth->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "HideIP", true );
mAccountSettings->chkHideIP->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "WebAware", false );
mAccountSettings->chkWebAware->setChecked( configChecked );
int configValue = mAccount->configGroup()->readEntry( "DefaultEncoding", 4 );
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
configValue );
//set filetransfer stuff
configChecked = mAccount->configGroup()->readEntry( "FileProxy", false );
mAccountSettings->chkFileProxy->setChecked( configChecked );
configValue = mAccount->configGroup()->readEntry( "FirstPort", 5190 );
mAccountSettings->sbxFirstPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "LastPort", 5199 );
mAccountSettings->sbxLastPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "Timeout", 10 );
mAccountSettings->sbxTimeout->setValue( configValue );
if ( mAccount->engine()->isActive() )
{
m_visibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Visible );
m_visibleEngine->setAllContactsView( mAccountSettings->visibleAllContacts );
m_visibleEngine->setContactsView( mAccountSettings->visibleContacts );
QObject::connect( mAccountSettings->visibleAdd, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->visibleRemove, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotRemove() ) );
m_invisibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Invisible );
m_invisibleEngine->setAllContactsView( mAccountSettings->invisibleAllContacts );
m_invisibleEngine->setContactsView( mAccountSettings->invisibleContacts );
QObject::connect( mAccountSettings->invisibleAdd, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->invisibleRemove, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotRemove() ) );
m_ignoreEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Ignore );
m_ignoreEngine->setAllContactsView( mAccountSettings->ignoreAllContacts );
m_ignoreEngine->setContactsView( mAccountSettings->ignoreContacts );
QObject::connect( mAccountSettings->ignoreAdd, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->ignoreRemove, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotRemove() ) );
}
// Hide the registration UI when editing an existing account
mAccountSettings->registrationGroupBox->hide();
}
else
{
int encodingId=4; //see icqprotocol.cpp for mappings
switch (QLocale::system().language())
{
case QLocale::Russian:
case QLocale::Ukrainian:
case QLocale::Byelorussian:
case QLocale::Bulgarian:
encodingId=2251;
break;
case QLocale::Hebrew:
encodingId=2255;
break;
case QLocale::Turkish:
encodingId=2254;
break;
case QLocale::Greek:
encodingId=2253;
break;
case QLocale::Arabic:
encodingId=2256;
break;
case QLocale::German:
case QLocale::Italian:
case QLocale::Spanish:
case QLocale::Portuguese:
case QLocale::French:
case QLocale::Dutch:
case QLocale::Danish:
case QLocale::Swedish:
case QLocale::Norwegian:
case QLocale::Icelandic:
encodingId=2252;
break;
default:
encodingId=4;
}
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
encodingId );
mAccountSettings->changePasswordGroupBox->hide();
}
if ( !mAccount || !mAccount->engine()->isActive() )
{
mAccountSettings->tabVisible->setEnabled( false );
mAccountSettings->tabInvisible->setEnabled( false );
mAccountSettings->tabIgnore->setEnabled( false );
mAccountSettings->buttonChangePassword->setEnabled( false );
}
QObject::connect(mAccountSettings->buttonRegister, SIGNAL(clicked()), this, SLOT(slotOpenRegister()));
QObject::connect(mAccountSettings->buttonChangePassword, SIGNAL(clicked()), this, SLOT(slotChangePassword()));
/* Set tab order to password custom widget correctly */
QWidget::setTabOrder( mAccountSettings->edtAccountId, mAccountSettings->mPasswordWidget->mRemembered );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mRemembered, mAccountSettings->mPasswordWidget->mPassword );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mPassword, mAccountSettings->chkAutoLogin );
}
ICQEditAccountWidget::~ICQEditAccountWidget()
{
if ( m_visibleEngine )
delete m_visibleEngine;
if ( m_invisibleEngine )
delete m_invisibleEngine;
if ( m_ignoreEngine )
delete m_ignoreEngine;
delete mAccountSettings;
}
Kopete::Account *ICQEditAccountWidget::apply()
{
kDebug(14153) << "Called.";
// If this is a new account, create it
if (!mAccount)
{
kDebug(14153) << "Creating a new account";
mAccount = new ICQAccount(mProtocol, mAccountSettings->edtAccountId->text());
if(!mAccount)
return NULL;
}
mAccountSettings->mPasswordWidget->save(&mAccount->password());
mAccount->setExcludeConnect(mAccountSettings->chkAutoLogin->isChecked());
Oscar::Settings* oscarSettings = mAccount->engine()->clientSettings();
bool configChecked = mAccountSettings->chkRequireAuth->isChecked();
mAccount->configGroup()->writeEntry( "RequireAuth", configChecked );
oscarSettings->setRequireAuth( configChecked );
configChecked = mAccountSettings->chkHideIP->isChecked();
mAccount->configGroup()->writeEntry( "HideIP", configChecked );
oscarSettings->setHideIP( configChecked );
configChecked = mAccountSettings->chkWebAware->isChecked();
mAccount->configGroup()->writeEntry( "WebAware", configChecked );
oscarSettings->setWebAware( configChecked );
int configValue = mProtocol->getCodeForCombo( mAccountSettings->encodingCombo,
mProtocol->encodings() );
mAccount->configGroup()->writeEntry( "DefaultEncoding", configValue );
if ( mAccountSettings->optionOverrideServer->isChecked() )
{
mAccount->setServerAddress(mAccountSettings->edtServerAddress->text().trimmed());
mAccount->setServerPort(mAccountSettings->edtServerPort->value());
}
else
{
mAccount->setServerAddress("login.oscar.aol.com");
mAccount->setServerPort(5190);
}
//set filetransfer stuff
configChecked = mAccountSettings->chkFileProxy->isChecked();
mAccount->configGroup()->writeEntry( "FileProxy", configChecked );
oscarSettings->setFileProxy( configChecked );
configValue = mAccountSettings->sbxFirstPort->value();
mAccount->configGroup()->writeEntry( "FirstPort", configValue );
oscarSettings->setFirstPort( configValue );
configValue = mAccountSettings->sbxLastPort->value();
mAccount->configGroup()->writeEntry( "LastPort", configValue );
oscarSettings->setLastPort( configValue );
configValue = mAccountSettings->sbxTimeout->value();
mAccount->configGroup()->writeEntry( "Timeout", configValue );
oscarSettings->setTimeout( configValue );
if ( mAccount->engine()->isActive() )
{
if ( m_visibleEngine )
m_visibleEngine->storeChanges();
if ( m_invisibleEngine )
m_invisibleEngine->storeChanges();
if ( m_ignoreEngine )
m_ignoreEngine->storeChanges();
//Update Oscar settings
static_cast<ICQMyselfContact*>( mAccount->myself() )->fetchShortInfo();
}
return mAccount;
}
bool ICQEditAccountWidget::validateData()
{
kDebug(14153) << "Called.";
bool bOk;
QString userId = mAccountSettings->edtAccountId->text();
qulonglong uid = userId.toULongLong( &bOk );
if( !bOk || uid == 0 || userId.isEmpty() )
{ KMessageBox::queuedMessageBox(this, KMessageBox::Sorry,
i18n("<qt>You must enter a valid ICQ No.</qt>"), i18n("ICQ"));
return false;
}
// No need to check port, min and max values are properly defined in .ui
if (mAccountSettings->edtServerAddress->text().isEmpty())
return false;
// Seems good to me
kDebug(14153) <<
"Account data validated successfully." << endl;
return true;
}
void ICQEditAccountWidget::slotOpenRegister()
{
KToolInvocation::invokeBrowser( QLatin1String("http://go.icq.com/register/") );
}
void ICQEditAccountWidget::slotChangePassword()
{
ICQChangePasswordDialog *passwordDlg = new ICQChangePasswordDialog( mAccount, this );
passwordDlg->exec();
delete passwordDlg;
}
#include "icqeditaccountwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
// kate: indent-mode csands; space-indent off; replace-tabs off;
<commit_msg>Fix headers<commit_after>/*
icqeditaccountwidget.cpp - ICQ Account Widget
Copyright (c) 2003 by Chris TenHarmsel <tenharmsel@staticmethod.net>
Kopete (c) 2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include "icqeditaccountwidget.h"
#include "ui_icqeditaccountui.h"
#include <QLayout>
#include <QCheckBox>
#include <QLineEdit>
#include <QSpinBox>
#include <QPushButton>
#include <QValidator>
#include <QLatin1String>
#include <QLocale>
#include <kconfig.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kurllabel.h>
#include <kdatewidget.h>
#include <ktoolinvocation.h>
#include <kpassworddialog.h>
#include <kmessagebox.h>
#include "kopetepassword.h"
#include "kopetepasswordwidget.h"
#include "icqprotocol.h"
#include "icqaccount.h"
#include "icqcontact.h"
#include "oscarprivacyengine.h"
#include "oscarsettings.h"
#include "icqchangepassworddialog.h"
ICQEditAccountWidget::ICQEditAccountWidget(ICQProtocol *protocol,
Kopete::Account *account, QWidget *parent)
: QWidget(parent), KopeteEditAccountWidget(account)
{
kDebug(14153) << "Called.";
mAccount=dynamic_cast<ICQAccount*>(account);
mProtocol=protocol;
m_visibleEngine = 0;
m_invisibleEngine = 0;
m_ignoreEngine = 0;
mAccountSettings = new Ui::ICQEditAccountUI();
mAccountSettings->setupUi( this );
mProtocol->fillComboFromTable( mAccountSettings->encodingCombo, mProtocol->encodings() );
//Setup the edtAccountId
QRegExp rx("[0-9]{9}");
QValidator* validator = new QRegExpValidator( rx, this );
mAccountSettings->edtAccountId->setValidator(validator);
// Read in the settings from the account if it exists
if(mAccount)
{
mAccountSettings->edtAccountId->setText(mAccount->accountId());
// TODO: Remove me after we can change Account IDs (Matt)
mAccountSettings->edtAccountId->setReadOnly(true);
mAccountSettings->mPasswordWidget->load(&mAccount->password());
mAccountSettings->chkAutoLogin->setChecked(mAccount->excludeConnect());
QString serverEntry = mAccount->configGroup()->readEntry("Server", "login.oscar.aol.com");
int portEntry = mAccount->configGroup()->readEntry("Port", 5190);
if ( serverEntry != "login.oscar.aol.com" || ( portEntry != 5190) )
mAccountSettings->optionOverrideServer->setChecked( true );
mAccountSettings->edtServerAddress->setText( serverEntry );
mAccountSettings->edtServerPort->setValue( portEntry );
bool configChecked = mAccount->configGroup()->readEntry( "RequireAuth", false );
mAccountSettings->chkRequireAuth->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "HideIP", true );
mAccountSettings->chkHideIP->setChecked( configChecked );
configChecked = mAccount->configGroup()->readEntry( "WebAware", false );
mAccountSettings->chkWebAware->setChecked( configChecked );
int configValue = mAccount->configGroup()->readEntry( "DefaultEncoding", 4 );
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
configValue );
//set filetransfer stuff
configChecked = mAccount->configGroup()->readEntry( "FileProxy", false );
mAccountSettings->chkFileProxy->setChecked( configChecked );
configValue = mAccount->configGroup()->readEntry( "FirstPort", 5190 );
mAccountSettings->sbxFirstPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "LastPort", 5199 );
mAccountSettings->sbxLastPort->setValue( configValue );
configValue = mAccount->configGroup()->readEntry( "Timeout", 10 );
mAccountSettings->sbxTimeout->setValue( configValue );
if ( mAccount->engine()->isActive() )
{
m_visibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Visible );
m_visibleEngine->setAllContactsView( mAccountSettings->visibleAllContacts );
m_visibleEngine->setContactsView( mAccountSettings->visibleContacts );
QObject::connect( mAccountSettings->visibleAdd, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->visibleRemove, SIGNAL( clicked() ), m_visibleEngine, SLOT( slotRemove() ) );
m_invisibleEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Invisible );
m_invisibleEngine->setAllContactsView( mAccountSettings->invisibleAllContacts );
m_invisibleEngine->setContactsView( mAccountSettings->invisibleContacts );
QObject::connect( mAccountSettings->invisibleAdd, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->invisibleRemove, SIGNAL( clicked() ), m_invisibleEngine, SLOT( slotRemove() ) );
m_ignoreEngine = new OscarPrivacyEngine( mAccount, OscarPrivacyEngine::Ignore );
m_ignoreEngine->setAllContactsView( mAccountSettings->ignoreAllContacts );
m_ignoreEngine->setContactsView( mAccountSettings->ignoreContacts );
QObject::connect( mAccountSettings->ignoreAdd, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotAdd() ) );
QObject::connect( mAccountSettings->ignoreRemove, SIGNAL( clicked() ), m_ignoreEngine, SLOT( slotRemove() ) );
}
// Hide the registration UI when editing an existing account
mAccountSettings->registrationGroupBox->hide();
}
else
{
int encodingId=4; //see icqprotocol.cpp for mappings
switch (QLocale::system().language())
{
case QLocale::Russian:
case QLocale::Ukrainian:
case QLocale::Byelorussian:
case QLocale::Bulgarian:
encodingId=2251;
break;
case QLocale::Hebrew:
encodingId=2255;
break;
case QLocale::Turkish:
encodingId=2254;
break;
case QLocale::Greek:
encodingId=2253;
break;
case QLocale::Arabic:
encodingId=2256;
break;
case QLocale::German:
case QLocale::Italian:
case QLocale::Spanish:
case QLocale::Portuguese:
case QLocale::French:
case QLocale::Dutch:
case QLocale::Danish:
case QLocale::Swedish:
case QLocale::Norwegian:
case QLocale::Icelandic:
encodingId=2252;
break;
default:
encodingId=4;
}
mProtocol->setComboFromTable( mAccountSettings->encodingCombo,
mProtocol->encodings(),
encodingId );
mAccountSettings->changePasswordGroupBox->hide();
}
if ( !mAccount || !mAccount->engine()->isActive() )
{
mAccountSettings->tabVisible->setEnabled( false );
mAccountSettings->tabInvisible->setEnabled( false );
mAccountSettings->tabIgnore->setEnabled( false );
mAccountSettings->buttonChangePassword->setEnabled( false );
}
QObject::connect(mAccountSettings->buttonRegister, SIGNAL(clicked()), this, SLOT(slotOpenRegister()));
QObject::connect(mAccountSettings->buttonChangePassword, SIGNAL(clicked()), this, SLOT(slotChangePassword()));
/* Set tab order to password custom widget correctly */
QWidget::setTabOrder( mAccountSettings->edtAccountId, mAccountSettings->mPasswordWidget->mRemembered );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mRemembered, mAccountSettings->mPasswordWidget->mPassword );
QWidget::setTabOrder( mAccountSettings->mPasswordWidget->mPassword, mAccountSettings->chkAutoLogin );
}
ICQEditAccountWidget::~ICQEditAccountWidget()
{
if ( m_visibleEngine )
delete m_visibleEngine;
if ( m_invisibleEngine )
delete m_invisibleEngine;
if ( m_ignoreEngine )
delete m_ignoreEngine;
delete mAccountSettings;
}
Kopete::Account *ICQEditAccountWidget::apply()
{
kDebug(14153) << "Called.";
// If this is a new account, create it
if (!mAccount)
{
kDebug(14153) << "Creating a new account";
mAccount = new ICQAccount(mProtocol, mAccountSettings->edtAccountId->text());
if(!mAccount)
return NULL;
}
mAccountSettings->mPasswordWidget->save(&mAccount->password());
mAccount->setExcludeConnect(mAccountSettings->chkAutoLogin->isChecked());
Oscar::Settings* oscarSettings = mAccount->engine()->clientSettings();
bool configChecked = mAccountSettings->chkRequireAuth->isChecked();
mAccount->configGroup()->writeEntry( "RequireAuth", configChecked );
oscarSettings->setRequireAuth( configChecked );
configChecked = mAccountSettings->chkHideIP->isChecked();
mAccount->configGroup()->writeEntry( "HideIP", configChecked );
oscarSettings->setHideIP( configChecked );
configChecked = mAccountSettings->chkWebAware->isChecked();
mAccount->configGroup()->writeEntry( "WebAware", configChecked );
oscarSettings->setWebAware( configChecked );
int configValue = mProtocol->getCodeForCombo( mAccountSettings->encodingCombo,
mProtocol->encodings() );
mAccount->configGroup()->writeEntry( "DefaultEncoding", configValue );
if ( mAccountSettings->optionOverrideServer->isChecked() )
{
mAccount->setServerAddress(mAccountSettings->edtServerAddress->text().trimmed());
mAccount->setServerPort(mAccountSettings->edtServerPort->value());
}
else
{
mAccount->setServerAddress("login.oscar.aol.com");
mAccount->setServerPort(5190);
}
//set filetransfer stuff
configChecked = mAccountSettings->chkFileProxy->isChecked();
mAccount->configGroup()->writeEntry( "FileProxy", configChecked );
oscarSettings->setFileProxy( configChecked );
configValue = mAccountSettings->sbxFirstPort->value();
mAccount->configGroup()->writeEntry( "FirstPort", configValue );
oscarSettings->setFirstPort( configValue );
configValue = mAccountSettings->sbxLastPort->value();
mAccount->configGroup()->writeEntry( "LastPort", configValue );
oscarSettings->setLastPort( configValue );
configValue = mAccountSettings->sbxTimeout->value();
mAccount->configGroup()->writeEntry( "Timeout", configValue );
oscarSettings->setTimeout( configValue );
if ( mAccount->engine()->isActive() )
{
if ( m_visibleEngine )
m_visibleEngine->storeChanges();
if ( m_invisibleEngine )
m_invisibleEngine->storeChanges();
if ( m_ignoreEngine )
m_ignoreEngine->storeChanges();
//Update Oscar settings
static_cast<ICQMyselfContact*>( mAccount->myself() )->fetchShortInfo();
}
return mAccount;
}
bool ICQEditAccountWidget::validateData()
{
kDebug(14153) << "Called.";
bool bOk;
QString userId = mAccountSettings->edtAccountId->text();
qulonglong uid = userId.toULongLong( &bOk );
if( !bOk || uid == 0 || userId.isEmpty() )
{ KMessageBox::queuedMessageBox(this, KMessageBox::Sorry,
i18n("<qt>You must enter a valid ICQ No.</qt>"), i18n("ICQ"));
return false;
}
// No need to check port, min and max values are properly defined in .ui
if (mAccountSettings->edtServerAddress->text().isEmpty())
return false;
// Seems good to me
kDebug(14153) <<
"Account data validated successfully." << endl;
return true;
}
void ICQEditAccountWidget::slotOpenRegister()
{
KToolInvocation::invokeBrowser( QLatin1String("http://go.icq.com/register/") );
}
void ICQEditAccountWidget::slotChangePassword()
{
ICQChangePasswordDialog *passwordDlg = new ICQChangePasswordDialog( mAccount, this );
passwordDlg->exec();
delete passwordDlg;
}
#include "icqeditaccountwidget.moc"
// vim: set noet ts=4 sts=4 sw=4:
// kate: indent-mode csands; space-indent off; replace-tabs off;
<|endoftext|>
|
<commit_before>#include <string>
#include <list>
#include <iostream>
#include <locale>
using namespace std;
/*
#pragma templet ~message
#pragma templet ~message =
#pragma templet ~message@(submessage1?,submessage2!,submessage3!,-submessage4?)
#pragma templet *actor
#pragma templet *actor +
#pragma templet *actor@(?,port?message,port!message) +
#pragma templet '~' id ['@'] [ '(' ['-'] id ('!'|'?') {',' ['-'] id ('!'|'?')} ')' ] ['=']
#pragma templet '*' id ['@'] [ '(' ('?'| id ('!'|'?') id) {',' id ('!'|'?') id)} ')' ] ['+']
*/
struct submessage{
string name;
bool dummy;
enum {CALL,ANSWER} type;
};
struct message{
string name;
bool duplex;
bool serilizable;
list <submessage> subm;
};
struct port{
string name;
string message_name;
enum {SERVER,CLIENT} type;
};
struct actor{
string name;
bool serilizable;
bool initially_active;
bool response_any;
list<port> ports;
};
bool openparse(string&name,string&pragma);
// открыть файл для разбора по имени,
// pragma – обрабатывать только заданные прагмы, например, #pragma omp
bool getpragma(string&argstring,int&line);
// argstring -- аргументы следующей по порядку разбора команды #pragma,
// line – номер строки файла, с которой начинается прагма
void closeparse();
// закрытие файл
void lexinit(string&s);
// инициализация; s – строка символов для разбора
bool getlex(string&lex);
// извлечение следующей лексемы из строки
// return false – если лексем больше нет
bool ungetlex();
// возврат на одну лексему назад
// return false – если возврат невозможен (например, уже выполнен)
void lexclear();
// очистка
void error(int line)
{
cerr << "error: bag #pragma at line " << line << endl;
exit(EXIT_FAILURE);
}
bool is_id(string&s)
{
locale loc;
return s.length()>1 || (s.length()==1 && isalpha(s[0],loc));
}
bool parse_message(int line, message& m)
{
string lex;
if (getlex(lex) && lex == "~"){
if (getlex(lex) && is_id(lex)){
}
}
else{
ungetlex();
return false;
}
}
bool parse_actor(int line, actor& a)
{
string lex;
if (getlex(lex) && lex == "*"){
if (getlex(lex) && is_id(lex)){
}
}
else{
ungetlex();
return false;
}
}
void print_message(ostream& s, message& m)
{
}
void print_actor(ostream&s,actor&a)
{
}
int main(int argc, char *argv[])
{
return EXIT_SUCCESS;
}
<commit_msg>build/print AST code added<commit_after>#include <string>
#include <list>
#include <iostream>
#include <locale>
using namespace std;
/*
#pragma templet ~message
#pragma templet ~message =
#pragma templet ~message@(submessage1?,submessage2!,submessage3!,-submessage4?)
#pragma templet *actor
#pragma templet *actor +
#pragma templet *actor@(?,port?message,port!message) +
#pragma templet '~' id ['@'] [ '(' ['-'] id ('!'|'?') {',' ['-'] id ('!'|'?')} ')' ] ['=']
#pragma templet '*' id ['@'] [ '(' ('?'| id ('!'|'?') id) {',' id ('!'|'?') id)} ')' ] ['+']
*/
struct submessage{
string name;
bool dummy;
enum {CALL,ANSWER} type;
};
struct message{
string name;
bool duplex;
bool serilizable;
list <submessage> subm;
};
struct port{
string name;
string message_name;
enum {SERVER,CLIENT} type;
};
struct actor{
string name;
bool serilizable;
bool initially_active;
bool response_any;
list<port> ports;
};
bool openparse(string&name,string&pragma);
// открыть файл для разбора по имени,
// pragma – обрабатывать только заданные прагмы, например, #pragma omp
bool getpragma(string&argstring,int&line);
// argstring -- аргументы следующей по порядку разбора команды #pragma,
// line – номер строки файла, с которой начинается прагма
void closeparse();
// закрытие файл
void lexinit(string&s);
// инициализация; s – строка символов для разбора
bool getlex(string&lex);
// извлечение следующей лексемы из строки
// return false – если лексем больше нет
bool ungetlex();
// возврат на одну лексему назад
// return false – если возврат невозможен (например, уже выполнен)
void lexclear();
// очистка
void error(int line)
{
cerr << "error: bad #pragma at line " << line << endl;
exit(EXIT_FAILURE);
}
bool is_id(string&s)
{
locale loc;
return s.length()>1 || (s.length()==1 && isalpha(s[0],loc));
}
bool parse_message(int line, message& m)
{
string lex;
if (!(getlex(lex) && lex == "~")){ ungetlex(); return false; }
if (!(getlex(lex) && is_id(lex))) error(line);
m.name = lex;
if (getlex(lex) && lex == "@"){ m.serilizable = true; }
else{ ungetlex(); m.serilizable = false; }
if (getlex(lex) && lex == "("){
submessage sm;
if (getlex(lex) && lex == "-"){ sm.dummy = true; }
else{ ungetlex(); sm.dummy = false; }
if (!(getlex(lex) && is_id(lex))) error(line);
sm.name = lex;
if (getlex(lex) && lex == "?"){ sm.type = submessage::ANSWER; }
else if (ungetlex() && getlex(lex) && lex == "!"){ sm.type = submessage::CALL; }
else error(line);
m.subm.push_back(sm);
while (getlex(lex) && lex == ","){
if (getlex(lex) && lex == "-"){ sm.dummy = true; }
else{ ungetlex(); sm.dummy = false; }
if (!(getlex(lex) && is_id(lex))) error(line);
sm.name = lex;
if (getlex(lex) && lex == "?"){ sm.type = submessage::ANSWER; }
else if (ungetlex() && getlex(lex) && lex == "!"){ sm.type = submessage::CALL; }
else error(line);
m.subm.push_back(sm);
}
}
ungetlex();
if (!(getlex(lex) && lex == ")")) error(line);
if (getlex(lex) && lex == "="){ m.duplex = true; }
else{ ungetlex(); m.duplex = false; }
if (m.subm.size()) m.duplex = true;
if (getlex(lex)) error(line);
return true;
}
bool parse_actor(int line, actor& a)
{
string lex;
if (!(getlex(lex) && lex == "*")){ ungetlex(); return false; }
if (!(getlex(lex) && is_id(lex))) error(line);
a.name = lex;
if (getlex(lex) && lex == "@"){ a.serilizable = true; }
else{ ungetlex(); a.serilizable = false; }
if (getlex(lex) && lex == "("){
port p;
a.response_any = false;
if (getlex(lex) && lex == "?"){
a.response_any = true;
}
else{
ungetlex();
if (!(getlex(lex) && is_id(lex))) error(line);
p.name = lex;
if (getlex(lex) && lex == "?"){ p.type = port::SERVER; }
else if (ungetlex() && getlex(lex) && lex == "!"){ p.type = port::CLIENT; }
else error(line);
if (!(getlex(lex) && is_id(lex))) error(line);
p.message_name = lex;
a.ports.push_back(p);
}
while (getlex(lex) && lex == ","){
if (!(getlex(lex) && is_id(lex))) error(line);
p.name = lex;
if (getlex(lex) && lex == "?"){ p.type = port::SERVER; }
else if (ungetlex() && getlex(lex) && lex == "!"){ p.type = port::CLIENT; }
else error(line);
if (!(getlex(lex) && is_id(lex))) error(line);
p.message_name = lex;
a.ports.push_back(p);
}
}
ungetlex();
if (!(getlex(lex) && lex == ")")) error(line);
if (getlex(lex) && lex == "+"){ a.initially_active = true; }
else{ ungetlex(); a.initially_active = false; }
if (getlex(lex)) error(line);
return true;
}
void print_message(ostream& s, message& m)
{
bool comma = false;
s << "~" << m.name;
if (m.serilizable) s << "@";
if (m.subm.size()){
s << "(";
for (auto x : m.subm){
if (comma) s << ",";
if (x.dummy) s << "-";
s << x.name;
if (x.type == submessage::ANSWER) s << "!";
else if (x.type == submessage::CALL) s << "?";
comma = true;
}
s << ")";
}
if (m.duplex && m.subm.size() == 0) s << "=";
}
void print_actor(ostream&s,actor&a)
{
bool comma = false;
s << "~" << a.name;
if (a.serilizable) s << "@";
if (a.ports.size()){
s << "(";
if (a.response_any){ s << "?"; comma = true; }
for (auto x : a.ports){
if (comma) s << ",";
s << x.name;
if (x.type == port::CLIENT) s << "!";
else if (x.type == port::SERVER) s << "?";
s << x.message_name;
comma = true;
}
s << ")";
}
if (a.initially_active) s << "+";
}
int main(int argc, char *argv[])
{
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: systemshell.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: tra $ $Date: 2002-07-05 07:20:17 $
*
* 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 _SYSTEMSHELL_HXX_
#define _SYSTEMSHELL_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace SystemShell
{
/** Add a file to the system shells recent document list if there is any.
This function may have no effect under Unix because there is no
standard API among the different desktop managers.
@param aFileUrl
The file url of the document.
*/
void AddToRecentDocumentList(const rtl::OUString& aFileUrl);
};
#endif
<commit_msg>INTEGRATION: CWS geordi2q06 (1.1.82); FILE MERGED 2003/09/24 11:28:40 rt 1.1.82.1: #111934#: join CWS recentdocs<commit_after>/*************************************************************************
*
* $RCSfile: systemshell.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2003-09-29 14:53:16 $
*
* 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 _SYSTEMSHELL_HXX_
#define _SYSTEMSHELL_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
namespace SystemShell
{
/** Add a file to the system shells recent document list if there is any.
This function may have no effect under Unix because there is no
standard API among the different desktop managers.
@param aFileUrl
The file url of the document.
@param aMimeType
The mime content type of the document specified by aFileUrl.
If an empty string will be provided "application/octet-stream"
will be used.
*/
void AddToRecentDocumentList(const rtl::OUString& aFileUrl, const rtl::OUString& aMimeType);
};
#endif
<|endoftext|>
|
<commit_before>// NOLINT(namespace-envoy)
#include <string>
#include <string_view>
#include <unordered_map>
#include "proxy_wasm_intrinsics.h"
class ExampleRootContext : public RootContext {
public:
explicit ExampleRootContext(uint32_t id, std::string_view root_id) : RootContext(id, root_id) {}
bool onStart(size_t) override;
bool onConfigure(size_t) override;
void onTick() override;
};
class ExampleContext : public Context {
public:
explicit ExampleContext(uint32_t id, RootContext* root) : Context(id, root) {}
void onCreate() override;
FilterHeadersStatus onRequestHeaders(uint32_t headers, bool end_of_stream) override;
FilterDataStatus onRequestBody(size_t body_buffer_length, bool end_of_stream) override;
FilterHeadersStatus onResponseHeaders(uint32_t headers, bool end_of_stream) override;
FilterDataStatus onResponseBody(size_t body_buffer_length, bool end_of_stream) override;
void onDone() override;
void onLog() override;
void onDelete() override;
};
static RegisterContextFactory register_ExampleContext(CONTEXT_FACTORY(ExampleContext),
ROOT_FACTORY(ExampleRootContext),
"my_root_id");
bool ExampleRootContext::onStart(size_t) {
LOG_TRACE("onStart");
return true;
}
bool ExampleRootContext::onConfigure(size_t) {
LOG_TRACE("onConfigure");
proxy_set_tick_period_milliseconds(1000); // 1 sec
return true;
}
void ExampleRootContext::onTick() { LOG_TRACE("onTick"); }
void ExampleContext::onCreate() { LOG_WARN(std::string("onCreate " + std::to_string(id()))); }
FilterHeadersStatus ExampleContext::onRequestHeaders(uint32_t, bool) {
LOG_DEBUG(std::string("onRequestHeaders ") + std::to_string(id()));
auto result = getRequestHeaderPairs();
auto pairs = result->pairs();
LOG_INFO(std::string("headers: ") + std::to_string(pairs.size()));
for (auto& p : pairs) {
LOG_INFO(std::string(p.first) + std::string(" -> ") + std::string(p.second));
}
return FilterHeadersStatus::Continue;
}
FilterHeadersStatus ExampleContext::onResponseHeaders(uint32_t, bool) {
LOG_DEBUG(std::string("onResponseHeaders ") + std::to_string(id()));
auto result = getResponseHeaderPairs();
auto pairs = result->pairs();
LOG_INFO(std::string("headers: ") + std::to_string(pairs.size()));
for (auto& p : pairs) {
LOG_INFO(std::string(p.first) + std::string(" -> ") + std::string(p.second));
}
addResponseHeader("X-Wasm-custom", "FOO");
replaceResponseHeader("content-type", "text/plain; charset=utf-8");
removeResponseHeader("content-length");
return FilterHeadersStatus::Continue;
}
FilterDataStatus ExampleContext::onRequestBody(size_t body_buffer_length,
bool /* end_of_stream */) {
auto body = getBufferBytes(WasmBufferType::HttpRequestBody, 0, body_buffer_length);
LOG_ERROR(std::string("onRequestBody ") + std::string(body->view()));
return FilterDataStatus::Continue;
}
FilterDataStatus ExampleContext::onResponseBody(size_t /* body_buffer_length */,
bool /* end_of_stream */) {
setBuffer(WasmBufferType::HttpResponseBody, 0, 12, "Hello, world");
return FilterDataStatus::Continue;
}
void ExampleContext::onDone() { LOG_WARN(std::string("onDone " + std::to_string(id()))); }
void ExampleContext::onLog() { LOG_WARN(std::string("onLog " + std::to_string(id()))); }
void ExampleContext::onDelete() { LOG_WARN(std::string("onDelete " + std::to_string(id()))); }
<commit_msg>examples: fix Wasm example. (#17218)<commit_after>// NOLINT(namespace-envoy)
#include <string>
#include <string_view>
#include <unordered_map>
#include "proxy_wasm_intrinsics.h"
class ExampleRootContext : public RootContext {
public:
explicit ExampleRootContext(uint32_t id, std::string_view root_id) : RootContext(id, root_id) {}
bool onStart(size_t) override;
bool onConfigure(size_t) override;
void onTick() override;
};
class ExampleContext : public Context {
public:
explicit ExampleContext(uint32_t id, RootContext* root) : Context(id, root) {}
void onCreate() override;
FilterHeadersStatus onRequestHeaders(uint32_t headers, bool end_of_stream) override;
FilterDataStatus onRequestBody(size_t body_buffer_length, bool end_of_stream) override;
FilterHeadersStatus onResponseHeaders(uint32_t headers, bool end_of_stream) override;
FilterDataStatus onResponseBody(size_t body_buffer_length, bool end_of_stream) override;
void onDone() override;
void onLog() override;
void onDelete() override;
};
static RegisterContextFactory register_ExampleContext(CONTEXT_FACTORY(ExampleContext),
ROOT_FACTORY(ExampleRootContext),
"my_root_id");
bool ExampleRootContext::onStart(size_t) {
LOG_TRACE("onStart");
return true;
}
bool ExampleRootContext::onConfigure(size_t) {
LOG_TRACE("onConfigure");
proxy_set_tick_period_milliseconds(1000); // 1 sec
return true;
}
void ExampleRootContext::onTick() { LOG_TRACE("onTick"); }
void ExampleContext::onCreate() { LOG_WARN(std::string("onCreate " + std::to_string(id()))); }
FilterHeadersStatus ExampleContext::onRequestHeaders(uint32_t, bool) {
LOG_DEBUG(std::string("onRequestHeaders ") + std::to_string(id()));
auto result = getRequestHeaderPairs();
auto pairs = result->pairs();
LOG_INFO(std::string("headers: ") + std::to_string(pairs.size()));
for (auto& p : pairs) {
LOG_INFO(std::string(p.first) + std::string(" -> ") + std::string(p.second));
}
return FilterHeadersStatus::Continue;
}
FilterHeadersStatus ExampleContext::onResponseHeaders(uint32_t, bool) {
LOG_DEBUG(std::string("onResponseHeaders ") + std::to_string(id()));
auto result = getResponseHeaderPairs();
auto pairs = result->pairs();
LOG_INFO(std::string("headers: ") + std::to_string(pairs.size()));
for (auto& p : pairs) {
LOG_INFO(std::string(p.first) + std::string(" -> ") + std::string(p.second));
}
addResponseHeader("X-Wasm-custom", "FOO");
replaceResponseHeader("content-type", "text/plain; charset=utf-8");
removeResponseHeader("content-length");
return FilterHeadersStatus::Continue;
}
FilterDataStatus ExampleContext::onRequestBody(size_t body_buffer_length,
bool /* end_of_stream */) {
auto body = getBufferBytes(WasmBufferType::HttpRequestBody, 0, body_buffer_length);
LOG_ERROR(std::string("onRequestBody ") + std::string(body->view()));
return FilterDataStatus::Continue;
}
FilterDataStatus ExampleContext::onResponseBody(size_t body_buffer_length,
bool /* end_of_stream */) {
setBuffer(WasmBufferType::HttpResponseBody, 0, body_buffer_length, "Hello, world\n");
return FilterDataStatus::Continue;
}
void ExampleContext::onDone() { LOG_WARN(std::string("onDone " + std::to_string(id()))); }
void ExampleContext::onLog() { LOG_WARN(std::string("onLog " + std::to_string(id()))); }
void ExampleContext::onDelete() { LOG_WARN(std::string("onDelete " + std::to_string(id()))); }
<|endoftext|>
|
<commit_before>#include "Comms.h"
#include "Video_Decoder.h"
//#include "Menu_System.h"
//#include "Splash_Menu_Page.h"
//#include "Main_Menu_Page.h"
#include "utils/Clock.h"
#include "IHAL.h"
#ifdef RASPBERRY_PI
# include "PI_HAL.h"
#else
# include "GLFW_HAL.h"
#endif
#include "imgui.h"
#include "HUD.h"
namespace silk
{
int s_version_major = 1;
int s_version_minor = 0;
std::string s_program_path;
std::unique_ptr<silk::IHAL> s_hal;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//This prints an "Assertion failed" message and aborts.
void __assert_fail(const char *__assertion, const char *__file, unsigned int __line, const char *__function)
{
QASSERT_MSG(false, "assert: {}:{}: {}: {}", __file, __line, __function, __assertion);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void signal_callback_handler(int signum)
{
printf("Caught signal %d\n", signum);
if (silk::s_hal)
{
silk::s_hal->shutdown();
}
exit(signum);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger()));
q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC));
// boost::shared_ptr<asio::io_service::work> work(new asio::io_service::work(s_async_io_service));
// std::thread_group worker_threads;
// for(int x = 0; x < 4; ++x)
// {
// worker_threads.create_thread(boost::bind(&asio::io_service::run, &s_async_io_service));
// }
signal(SIGHUP, signal_callback_handler);
signal(SIGINT, signal_callback_handler);
signal(SIGCONT, signal_callback_handler);
signal(SIGTERM, signal_callback_handler);
silk::s_program_path = argv[0];
size_t off = silk::s_program_path.find_last_of('/');
if (off != std::string::npos)
{
silk::s_program_path = silk::s_program_path.substr(0, off);
}
QLOGI("Program path: {}.", silk::s_program_path);
#ifdef RASPBERRY_PI
silk::s_hal.reset(new silk::PI_HAL());
#else
silk::s_hal.reset(new silk::GLFW_HAL());
#endif
silk::IHAL& hal = *silk::s_hal;
ts::Result<void> result = hal.init();
if (result != ts::success)
{
QLOGE("Cannot init hal: {}.", result.error().what());
exit(1);
}
silk::HUD hud(hal);
math::vec2u32 display_size = hal.get_display_size();
ImGuiStyle& style = ImGui::GetStyle();
style.ScrollbarSize = display_size.x / 80.f;
style.TouchExtraPadding = ImVec2(style.ScrollbarSize * 2.f, style.ScrollbarSize * 2.f);
//style.ItemSpacing = ImVec2(size.x / 200, size.x / 200);
//style.ItemInnerSpacing = ImVec2(style.ItemSpacing.x / 2, style.ItemSpacing.y / 2);
ImGuiIO& io = ImGui::GetIO();
io.FontGlobalScale = 2.f;
Video_Decoder decoder;
decoder.init();
Clock::time_point last_tp = Clock::now();
math::vec2u16 resolution;
typedef std::vector<uint8_t> Video_Packet;
typedef Pool<Video_Packet>::Ptr Video_Packet_ptr;
Pool<Video_Packet> video_packet_pool;
Queue<Video_Packet_ptr> video_packet_queue(32);
//FILE* f = fopen("video.h264", "wb");
hal.get_comms().on_video_data_received = [&video_packet_pool, &video_packet_queue, &resolution](void const* data, size_t size, math::vec2u16 const& res)
{
//fwrite(data, size, 1, f);
//fflush(f);
Video_Packet_ptr packet = video_packet_pool.acquire();
packet->resize(size);
memcpy(packet->data(), data, size);
video_packet_queue.push_back(packet, false);
resolution = res;
};
float temperature = 0.f;
Clock::time_point last_comms_history_tp = Clock::now();
std::vector<float> tx_rssi_history;
std::vector<float> rx_rssi_history;
std::vector<float> packets_dropped_history;
std::vector<float> packets_received_history;
std::vector<float> packets_sent_history;
float brightness = 80.f;
float fan_speed = 100.f;
hal.set_backlight(brightness / 100.f);
hal.set_fan_speed(fan_speed / 100.f);
bool single_phy = false;
silk::stream::ICamera_Commands::Value camera_commands;
while (hal.process())
{
Video_Packet_ptr packet;
while (video_packet_queue.pop_front(packet, false))
{
decoder.decode_data(packet->data(), packet->size(), resolution);
packet = nullptr;
}
decoder.release_buffers();
Clock::time_point now = Clock::now();
Clock::duration dt = now - last_tp;
last_tp = now;
io.DeltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(dt).count();
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImVec2(display_size.x, display_size.y));
ImGui::SetNextWindowBgAlpha(0);
ImGui::Begin("", nullptr, ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoInputs);
ImGui::Image((void*)(decoder.get_video_texture_id() | 0x80000000), ImVec2(display_size.x, display_size.y));
hud.draw();
ImGui::Begin("HAL");
{
static int counter = 0;
ImGui::Text("Hello, world!"); // Display some text (you can use a format string too)
if (ImGui::SliderFloat("Brightness", &brightness, 10.f, 100.f, "%.0f%%"))
{
hal.set_backlight(brightness / 100.f);
}
if (ImGui::SliderFloat("Fan", &fan_speed, 10.f, 100.f, "%.0f%%"))
{
hal.set_fan_speed(fan_speed / 100.f);
}
temperature = hal.get_temperature();
ImGui::Text("Temperature = %.2f'C", temperature);
if (now - last_comms_history_tp >= std::chrono::milliseconds(100))
{
last_comms_history_tp = now;
silk::Comms::Stats stats = hal.get_comms().get_stats();
tx_rssi_history.push_back(stats.tx_rssi);
while (tx_rssi_history.size() > 10 * 5) { tx_rssi_history.erase(tx_rssi_history.begin()); }
rx_rssi_history.push_back(stats.rx_rssi);
while (rx_rssi_history.size() > 10 * 5) { rx_rssi_history.erase(rx_rssi_history.begin()); }
packets_dropped_history.push_back(stats.packets_dropped_per_second);
while (packets_dropped_history.size() > 10 * 5) { packets_dropped_history.erase(packets_dropped_history.begin()); }
packets_received_history.push_back(stats.packets_received_per_second);
while (packets_received_history.size() > 10 * 5) { packets_received_history.erase(packets_received_history.begin()); }
packets_sent_history.push_back(stats.packets_sent_per_second);
while (packets_sent_history.size() > 10 * 5) { packets_sent_history.erase(packets_sent_history.begin()); }
}
if (!tx_rssi_history.empty())
{
ImGui::Text("TX = %ddBm", (int)tx_rssi_history.back());
ImGui::PlotLines("History",
tx_rssi_history.data(), tx_rssi_history.size(),
0, NULL,
-128.f, 128.f,
ImVec2(0, display_size.y / 20));
}
if (!rx_rssi_history.empty())
{
ImGui::Text("RX = %ddBm", (int)rx_rssi_history.back());
ImGui::PlotLines("History",
rx_rssi_history.data(), rx_rssi_history.size(),
0, NULL,
-128.f, 128.f,
ImVec2(0, display_size.y / 20));
}
if (!packets_dropped_history.empty())
{
ImGui::Text("Dropped = %.2f", packets_dropped_history.back());
auto minmax = std::minmax_element(packets_dropped_history.begin(), packets_dropped_history.end());
ImGui::PlotLines("History",
packets_dropped_history.data(), packets_dropped_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
if (!packets_received_history.empty())
{
ImGui::Text("Received = %.2f", packets_received_history.back());
auto minmax = std::minmax_element(packets_received_history.begin(), packets_received_history.end());
ImGui::PlotLines("History",
packets_received_history.data(), packets_received_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
if (!packets_sent_history.empty())
{
ImGui::Text("Sent = %.2f", packets_sent_history.back());
auto minmax = std::minmax_element(packets_sent_history.begin(), packets_sent_history.end());
ImGui::PlotLines("History",
packets_sent_history.data(), packets_sent_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
bool hq = camera_commands.quality == silk::stream::ICamera_Commands::Quality::HIGH;
ImGui::Checkbox("HQ Video", &hq);
camera_commands.quality = hq ? silk::stream::ICamera_Commands::Quality::HIGH : silk::stream::ICamera_Commands::Quality::LOW;
ImGui::SameLine();
ImGui::Checkbox("Record Video", &camera_commands.recording);
hal.get_comms().send_camera_commands_value(camera_commands);
ImGui::Checkbox("Single Phy", &single_phy);
hal.get_comms().set_single_phy(single_phy);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
ImGui::End();
ImGui::End();
//std::this_thread::sleep_for(std::chrono::microseconds(1));
ImGui::Render();
}
hal.shutdown();
return 0;
}
<commit_msg>Inverted the camera image<commit_after>#include "Comms.h"
#include "Video_Decoder.h"
//#include "Menu_System.h"
//#include "Splash_Menu_Page.h"
//#include "Main_Menu_Page.h"
#include "utils/Clock.h"
#include "IHAL.h"
#ifdef RASPBERRY_PI
# include "PI_HAL.h"
#else
# include "GLFW_HAL.h"
#endif
#include "imgui.h"
#include "HUD.h"
namespace silk
{
int s_version_major = 1;
int s_version_minor = 0;
std::string s_program_path;
std::unique_ptr<silk::IHAL> s_hal;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//This prints an "Assertion failed" message and aborts.
void __assert_fail(const char *__assertion, const char *__file, unsigned int __line, const char *__function)
{
QASSERT_MSG(false, "assert: {}:{}: {}: {}", __file, __line, __function, __assertion);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void signal_callback_handler(int signum)
{
printf("Caught signal %d\n", signum);
if (silk::s_hal)
{
silk::s_hal->shutdown();
}
exit(signum);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
q::logging::add_logger(q::logging::Logger_uptr(new q::logging::Console_Logger()));
q::logging::set_decorations(q::logging::Decorations(q::logging::Decoration::TIMESTAMP, q::logging::Decoration::LEVEL, q::logging::Decoration::TOPIC));
// boost::shared_ptr<asio::io_service::work> work(new asio::io_service::work(s_async_io_service));
// std::thread_group worker_threads;
// for(int x = 0; x < 4; ++x)
// {
// worker_threads.create_thread(boost::bind(&asio::io_service::run, &s_async_io_service));
// }
signal(SIGHUP, signal_callback_handler);
signal(SIGINT, signal_callback_handler);
signal(SIGCONT, signal_callback_handler);
signal(SIGTERM, signal_callback_handler);
silk::s_program_path = argv[0];
size_t off = silk::s_program_path.find_last_of('/');
if (off != std::string::npos)
{
silk::s_program_path = silk::s_program_path.substr(0, off);
}
QLOGI("Program path: {}.", silk::s_program_path);
#ifdef RASPBERRY_PI
silk::s_hal.reset(new silk::PI_HAL());
#else
silk::s_hal.reset(new silk::GLFW_HAL());
#endif
silk::IHAL& hal = *silk::s_hal;
ts::Result<void> result = hal.init();
if (result != ts::success)
{
QLOGE("Cannot init hal: {}.", result.error().what());
exit(1);
}
silk::HUD hud(hal);
math::vec2u32 display_size = hal.get_display_size();
ImGuiStyle& style = ImGui::GetStyle();
style.ScrollbarSize = display_size.x / 80.f;
style.TouchExtraPadding = ImVec2(style.ScrollbarSize * 2.f, style.ScrollbarSize * 2.f);
//style.ItemSpacing = ImVec2(size.x / 200, size.x / 200);
//style.ItemInnerSpacing = ImVec2(style.ItemSpacing.x / 2, style.ItemSpacing.y / 2);
ImGuiIO& io = ImGui::GetIO();
io.FontGlobalScale = 2.f;
Video_Decoder decoder;
decoder.init();
Clock::time_point last_tp = Clock::now();
math::vec2u16 resolution;
typedef std::vector<uint8_t> Video_Packet;
typedef Pool<Video_Packet>::Ptr Video_Packet_ptr;
Pool<Video_Packet> video_packet_pool;
Queue<Video_Packet_ptr> video_packet_queue(32);
//FILE* f = fopen("video.h264", "wb");
hal.get_comms().on_video_data_received = [&video_packet_pool, &video_packet_queue, &resolution](void const* data, size_t size, math::vec2u16 const& res)
{
//fwrite(data, size, 1, f);
//fflush(f);
Video_Packet_ptr packet = video_packet_pool.acquire();
packet->resize(size);
memcpy(packet->data(), data, size);
video_packet_queue.push_back(packet, false);
resolution = res;
};
float temperature = 0.f;
Clock::time_point last_comms_history_tp = Clock::now();
std::vector<float> tx_rssi_history;
std::vector<float> rx_rssi_history;
std::vector<float> packets_dropped_history;
std::vector<float> packets_received_history;
std::vector<float> packets_sent_history;
float brightness = 80.f;
float fan_speed = 100.f;
hal.set_backlight(brightness / 100.f);
hal.set_fan_speed(fan_speed / 100.f);
bool single_phy = false;
silk::stream::ICamera_Commands::Value camera_commands;
while (hal.process())
{
Video_Packet_ptr packet;
while (video_packet_queue.pop_front(packet, false))
{
decoder.decode_data(packet->data(), packet->size(), resolution);
packet = nullptr;
}
decoder.release_buffers();
Clock::time_point now = Clock::now();
Clock::duration dt = now - last_tp;
last_tp = now;
io.DeltaTime = std::chrono::duration_cast<std::chrono::duration<float>>(dt).count();
ImGui::NewFrame();
ImGui::SetNextWindowPos(ImVec2(0, 0));
ImGui::SetNextWindowSize(ImVec2(display_size.x, display_size.y));
ImGui::SetNextWindowBgAlpha(0);
ImGui::Begin("", nullptr, ImGuiWindowFlags_NoTitleBar |
ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove |
ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoInputs);
ImGui::Image((void*)(decoder.get_video_texture_id() | 0x80000000),
ImVec2(display_size.x, display_size.y),
ImVec2(0, 1),
ImVec2(1, 0));
hud.draw();
ImGui::Begin("HAL");
{
static int counter = 0;
ImGui::Text("Hello, world!"); // Display some text (you can use a format string too)
if (ImGui::SliderFloat("Brightness", &brightness, 10.f, 100.f, "%.0f%%"))
{
hal.set_backlight(brightness / 100.f);
}
if (ImGui::SliderFloat("Fan", &fan_speed, 10.f, 100.f, "%.0f%%"))
{
hal.set_fan_speed(fan_speed / 100.f);
}
temperature = hal.get_temperature();
ImGui::Text("Temperature = %.2f'C", temperature);
if (now - last_comms_history_tp >= std::chrono::milliseconds(100))
{
last_comms_history_tp = now;
silk::Comms::Stats stats = hal.get_comms().get_stats();
tx_rssi_history.push_back(stats.tx_rssi);
while (tx_rssi_history.size() > 10 * 5) { tx_rssi_history.erase(tx_rssi_history.begin()); }
rx_rssi_history.push_back(stats.rx_rssi);
while (rx_rssi_history.size() > 10 * 5) { rx_rssi_history.erase(rx_rssi_history.begin()); }
packets_dropped_history.push_back(stats.packets_dropped_per_second);
while (packets_dropped_history.size() > 10 * 5) { packets_dropped_history.erase(packets_dropped_history.begin()); }
packets_received_history.push_back(stats.packets_received_per_second);
while (packets_received_history.size() > 10 * 5) { packets_received_history.erase(packets_received_history.begin()); }
packets_sent_history.push_back(stats.packets_sent_per_second);
while (packets_sent_history.size() > 10 * 5) { packets_sent_history.erase(packets_sent_history.begin()); }
}
if (!tx_rssi_history.empty())
{
ImGui::Text("TX = %ddBm", (int)tx_rssi_history.back());
ImGui::PlotLines("History",
tx_rssi_history.data(), tx_rssi_history.size(),
0, NULL,
-128.f, 128.f,
ImVec2(0, display_size.y / 20));
}
if (!rx_rssi_history.empty())
{
ImGui::Text("RX = %ddBm", (int)rx_rssi_history.back());
ImGui::PlotLines("History",
rx_rssi_history.data(), rx_rssi_history.size(),
0, NULL,
-128.f, 128.f,
ImVec2(0, display_size.y / 20));
}
if (!packets_dropped_history.empty())
{
ImGui::Text("Dropped = %.2f", packets_dropped_history.back());
auto minmax = std::minmax_element(packets_dropped_history.begin(), packets_dropped_history.end());
ImGui::PlotLines("History",
packets_dropped_history.data(), packets_dropped_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
if (!packets_received_history.empty())
{
ImGui::Text("Received = %.2f", packets_received_history.back());
auto minmax = std::minmax_element(packets_received_history.begin(), packets_received_history.end());
ImGui::PlotLines("History",
packets_received_history.data(), packets_received_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
if (!packets_sent_history.empty())
{
ImGui::Text("Sent = %.2f", packets_sent_history.back());
auto minmax = std::minmax_element(packets_sent_history.begin(), packets_sent_history.end());
ImGui::PlotLines("History",
packets_sent_history.data(), packets_sent_history.size(),
0, NULL,
*minmax.first, *minmax.second,
ImVec2(0, display_size.y / 20));
}
bool hq = camera_commands.quality == silk::stream::ICamera_Commands::Quality::HIGH;
ImGui::Checkbox("HQ Video", &hq);
camera_commands.quality = hq ? silk::stream::ICamera_Commands::Quality::HIGH : silk::stream::ICamera_Commands::Quality::LOW;
ImGui::SameLine();
ImGui::Checkbox("Record Video", &camera_commands.recording);
hal.get_comms().send_camera_commands_value(camera_commands);
ImGui::Checkbox("Single Phy", &single_phy);
hal.get_comms().set_single_phy(single_phy);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
}
ImGui::End();
ImGui::End();
//std::this_thread::sleep_for(std::chrono::microseconds(1));
ImGui::Render();
}
hal.shutdown();
return 0;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Simulation.h"
#include <thread>
#include <chrono>
namespace sim
{
Simulation *Simulation::singleton = nullptr;
void Simulation::reset()
{
assert(Simulation::singleton == nullptr);
Simulation::singleton = this;
numberOfThreads = 1;
tournamentID = 0;
randomSeed = (unsigned int)std::chrono::system_clock::now().time_since_epoch().count();
}
Simulation::Simulation(json_spirit::Value &jsonData)
{
reset();
json_spirit::Object jsonObject = jsonData.get_obj();
// It is crucial that the teams are setup before the rules.
// To achieve that, we just delay rule initialization.
json_spirit::Array ruleData;
for (json_spirit::Pair &pair : jsonObject)
{
std::string &key = pair.name_;
if (key == "thread_count") numberOfThreads = pair.value_.get_int();
else if (key == "run_count") numberOfRuns = pair.value_.get_int();
else if (key == "tournament_id") tournamentID = pair.value_.get_int();
else if (key == "tournament_type") tournamentType = pair.value_.get_str();
else if (key == "teams") setupTeams(pair.value_.get_array());
else if (key == "rules") ruleData = pair.value_.get_array();
else if (key == "match_database") setupKnownMatches(pair.value_.get_array());
else
std::cerr << "sim::Simulation: invalid property \"" << key << "\"" << std::endl;
}
// Finally (after the teams are setup) init the rules.
if (!ruleData.empty())
setupRules(ruleData);
}
Simulation::~Simulation()
{
for (auto &tournament : tournaments)
delete tournament;
}
void Simulation::setupTeams(json_spirit::Array &teamData)
{
int teamIndex = 0;
for (json_spirit::Value &val : teamData)
{
teams.push_back(Team(val.get_obj(), teamIndex++));
}
}
void Simulation::setupRules(json_spirit::Array &ruleData)
{
for (json_spirit::Value &val : ruleData)
{
rules.push_back(Rule(val.get_obj()));
}
}
void Simulation::setupKnownMatches(json_spirit::Array &matches)
{
for (json_spirit::Value &val : matches)
{
json_spirit::Object &data = val.get_obj();
int teams[2] = { -1, -1 };
int goals[2] = { -1, -1 };
bool hadOvertime = false;
std::string cluster = "all";
int bofRound = -1;
for (json_spirit::Pair &pair : data)
{
std::string &key = pair.name_;
if (key == "teams")
{
for (int i = 0; i < 2; ++i)
teams[i] = pair.value_.get_array().at(i).get_int();
}
else if (key == "goals")
{
for (int i = 0; i < 2; ++i)
goals[i] = pair.value_.get_array().at(i).get_int();
}
else if (key == "bof_round")
{
bofRound = pair.value_.get_int();
}
}
assert(bofRound != -1);
assert(teams[0] != -1);
assert(goals[0] != -1);
if (!knownMatchResults.count(bofRound))
knownMatchResults[bofRound] = std::vector<KnownMatchResult>();
knownMatchResults[bofRound].push_back(KnownMatchResult(bofRound, cluster, teams, goals, hadOvertime));
}
}
void Simulation::execute()
{
// some safety & sanity checks
if (teams.empty())
{
throw "No teams are active. Aborting the tournament.";
}
if (rules.empty())
{
throw "No rules are active. Aborting the tournament.";
}
// 16 threads for one tournament sound impractical
int realThreadCount = std::min(numberOfThreads, numberOfRuns);
std::vector<std::thread> threads;
threads.resize(realThreadCount);
tournaments.resize(realThreadCount);
int remainingRuns = numberOfRuns;
int runsPerThread = numberOfRuns / realThreadCount;
for (int i = 0; i < realThreadCount; ++i, remainingRuns -= runsPerThread)
{
int runsForTournament = std::min(remainingRuns, runsPerThread);
// make sure that there are no remaining runs that don't get distributed
// example: 20 runs and 8 threads, runs per thread = 2, only 2*8=16 tournaments would be started
if (i == realThreadCount - 1)
runsForTournament = remainingRuns;
tournaments[i] = Tournament::newOfType(tournamentType, this, runsForTournament);
tournaments[i]->doSanityChecks(); // allow the tournament some checking prior to the launch
threads[i] = std::thread(&Tournament::start, tournaments[i]);
}
// wait for the simulation to finish
for (auto &thread : threads)
{
thread.join();
}
// setup rank data
{ // scope
std::unique_ptr<Tournament> tournament(Tournament::newOfType(tournamentType, this, 0));
for (RankData & const rank : tournament->getRankDataAssignment())
ranks.push_back(rank);
}
// and then join the results
for (Tournament* &tournament : tournaments)
{
// first the team data
for (auto &clusterToMerge : tournament->clusterTeamResults)
{
std::map<int, TeamResult> &cluster = clusterTeamResults[clusterToMerge.first];
for (auto &team : teams)
{
if (!cluster.count(team.id))
cluster.emplace(std::make_pair(team.id, TeamResult(clusterToMerge.second[team.id])));
else
cluster[team.id].merge(clusterToMerge.second[team.id]);
}
}
// and then the match cluster statistics
for (auto &clusterToMerge : tournament->clusterMatchResultStatisticsLists)
{
clusterMatchResultStatisticsLists[clusterToMerge.first].merge(clusterToMerge.second);
}
}
}
json_spirit::Object Simulation::getJSONResults()
{
json_spirit::Object root;
root.push_back(json_spirit::Pair("tournament_id", tournamentID));
root.push_back(json_spirit::Pair("ranks", json_spirit::Array()));
json_spirit::Array &ranks = root.back().value_.get_array();
fillRankResults(ranks);
root.push_back(json_spirit::Pair("matches", json_spirit::Object()));
json_spirit::Object &matches= root.back().value_.get_obj();
for (auto &cluster : clusterTeamResults)
{
matches.push_back(json_spirit::Pair(cluster.first, json_spirit::Object()));
json_spirit::Object &match = matches.back().value_.get_obj();
match.push_back(json_spirit::Pair("teams", json_spirit::Array()));
json_spirit::Array &teams = match.back().value_.get_array();
fillTeamResults(teams, cluster.first);
match.push_back(json_spirit::Pair("results", json_spirit::Array()));
json_spirit::Array &results = match.back().value_.get_array();
fillMatchResults(results, cluster.first);
if (cluster.first != "all")
{
match.push_back(json_spirit::Pair("bof_round", clusterMatchResultStatisticsLists[cluster.first].bofRound));
match.push_back(json_spirit::Pair("game_in_round", clusterMatchResultStatisticsLists[cluster.first].gameInRound));
}
else
{
match.push_back(json_spirit::Pair("bof_round", 0));
match.push_back(json_spirit::Pair("game_in_round", 0));
}
}
return root;
}
void Simulation::fillRankResults(json_spirit::Array &ranks)
{
for (RankData &rankData : this->ranks)
ranks.push_back(rankData.toJSONObject());
}
void Simulation::fillMatchResults(json_spirit::Array &results, std::string cluster)
{
results = clusterMatchResultStatisticsLists[cluster].toJSONArray();
}
void Simulation::fillTeamResults(json_spirit::Array &teamList, std::string cluster)
{
for (auto &team : teams)
{
json_spirit::Object teamData;
teamData.push_back(json_spirit::Pair("id", team.id));
if (cluster == "all")
{
teamData.push_back(json_spirit::Pair("ranks", clusterTeamResults[cluster][team.id].rankDataToJSONArray(ranks)));
teamData.push_back(json_spirit::Pair("avg_place", clusterTeamResults[cluster][team.id].getAvgPlace()));
}
teamData.push_back(json_spirit::Pair("match_data", clusterTeamResults[cluster][team.id].toJSONObject()));
teamData.push_back(json_spirit::Pair("avg_goals", clusterTeamResults[cluster][team.id].getAvgGoals()));
teamList.push_back(teamData);
}
}
} // namespace sim<commit_msg>fixed invalid declaration of a reference to a constant value<commit_after>#include "stdafx.h"
#include "Simulation.h"
#include <thread>
#include <chrono>
namespace sim
{
Simulation *Simulation::singleton = nullptr;
void Simulation::reset()
{
assert(Simulation::singleton == nullptr);
Simulation::singleton = this;
numberOfThreads = 1;
tournamentID = 0;
randomSeed = (unsigned int)std::chrono::system_clock::now().time_since_epoch().count();
}
Simulation::Simulation(json_spirit::Value &jsonData)
{
reset();
json_spirit::Object jsonObject = jsonData.get_obj();
// It is crucial that the teams are setup before the rules.
// To achieve that, we just delay rule initialization.
json_spirit::Array ruleData;
for (json_spirit::Pair &pair : jsonObject)
{
std::string &key = pair.name_;
if (key == "thread_count") numberOfThreads = pair.value_.get_int();
else if (key == "run_count") numberOfRuns = pair.value_.get_int();
else if (key == "tournament_id") tournamentID = pair.value_.get_int();
else if (key == "tournament_type") tournamentType = pair.value_.get_str();
else if (key == "teams") setupTeams(pair.value_.get_array());
else if (key == "rules") ruleData = pair.value_.get_array();
else if (key == "match_database") setupKnownMatches(pair.value_.get_array());
else
std::cerr << "sim::Simulation: invalid property \"" << key << "\"" << std::endl;
}
// Finally (after the teams are setup) init the rules.
if (!ruleData.empty())
setupRules(ruleData);
}
Simulation::~Simulation()
{
for (auto &tournament : tournaments)
delete tournament;
}
void Simulation::setupTeams(json_spirit::Array &teamData)
{
int teamIndex = 0;
for (json_spirit::Value &val : teamData)
{
teams.push_back(Team(val.get_obj(), teamIndex++));
}
}
void Simulation::setupRules(json_spirit::Array &ruleData)
{
for (json_spirit::Value &val : ruleData)
{
rules.push_back(Rule(val.get_obj()));
}
}
void Simulation::setupKnownMatches(json_spirit::Array &matches)
{
for (json_spirit::Value &val : matches)
{
json_spirit::Object &data = val.get_obj();
int teams[2] = { -1, -1 };
int goals[2] = { -1, -1 };
bool hadOvertime = false;
std::string cluster = "all";
int bofRound = -1;
for (json_spirit::Pair &pair : data)
{
std::string &key = pair.name_;
if (key == "teams")
{
for (int i = 0; i < 2; ++i)
teams[i] = pair.value_.get_array().at(i).get_int();
}
else if (key == "goals")
{
for (int i = 0; i < 2; ++i)
goals[i] = pair.value_.get_array().at(i).get_int();
}
else if (key == "bof_round")
{
bofRound = pair.value_.get_int();
}
}
assert(bofRound != -1);
assert(teams[0] != -1);
assert(goals[0] != -1);
if (!knownMatchResults.count(bofRound))
knownMatchResults[bofRound] = std::vector<KnownMatchResult>();
knownMatchResults[bofRound].push_back(KnownMatchResult(bofRound, cluster, teams, goals, hadOvertime));
}
}
void Simulation::execute()
{
// some safety & sanity checks
if (teams.empty())
{
throw "No teams are active. Aborting the tournament.";
}
if (rules.empty())
{
throw "No rules are active. Aborting the tournament.";
}
// 16 threads for one tournament sound impractical
int realThreadCount = std::min(numberOfThreads, numberOfRuns);
std::vector<std::thread> threads;
threads.resize(realThreadCount);
tournaments.resize(realThreadCount);
int remainingRuns = numberOfRuns;
int runsPerThread = numberOfRuns / realThreadCount;
for (int i = 0; i < realThreadCount; ++i, remainingRuns -= runsPerThread)
{
int runsForTournament = std::min(remainingRuns, runsPerThread);
// make sure that there are no remaining runs that don't get distributed
// example: 20 runs and 8 threads, runs per thread = 2, only 2*8=16 tournaments would be started
if (i == realThreadCount - 1)
runsForTournament = remainingRuns;
tournaments[i] = Tournament::newOfType(tournamentType, this, runsForTournament);
tournaments[i]->doSanityChecks(); // allow the tournament some checking prior to the launch
threads[i] = std::thread(&Tournament::start, tournaments[i]);
}
// wait for the simulation to finish
for (auto &thread : threads)
{
thread.join();
}
// setup rank data
{ // scope
std::unique_ptr<Tournament> tournament(Tournament::newOfType(tournamentType, this, 0));
for (RankData const & rank : tournament->getRankDataAssignment())
ranks.push_back(rank);
}
// and then join the results
for (Tournament* &tournament : tournaments)
{
// first the team data
for (auto &clusterToMerge : tournament->clusterTeamResults)
{
std::map<int, TeamResult> &cluster = clusterTeamResults[clusterToMerge.first];
for (auto &team : teams)
{
if (!cluster.count(team.id))
cluster.emplace(std::make_pair(team.id, TeamResult(clusterToMerge.second[team.id])));
else
cluster[team.id].merge(clusterToMerge.second[team.id]);
}
}
// and then the match cluster statistics
for (auto &clusterToMerge : tournament->clusterMatchResultStatisticsLists)
{
clusterMatchResultStatisticsLists[clusterToMerge.first].merge(clusterToMerge.second);
}
}
}
json_spirit::Object Simulation::getJSONResults()
{
json_spirit::Object root;
root.push_back(json_spirit::Pair("tournament_id", tournamentID));
root.push_back(json_spirit::Pair("ranks", json_spirit::Array()));
json_spirit::Array &ranks = root.back().value_.get_array();
fillRankResults(ranks);
root.push_back(json_spirit::Pair("matches", json_spirit::Object()));
json_spirit::Object &matches= root.back().value_.get_obj();
for (auto &cluster : clusterTeamResults)
{
matches.push_back(json_spirit::Pair(cluster.first, json_spirit::Object()));
json_spirit::Object &match = matches.back().value_.get_obj();
match.push_back(json_spirit::Pair("teams", json_spirit::Array()));
json_spirit::Array &teams = match.back().value_.get_array();
fillTeamResults(teams, cluster.first);
match.push_back(json_spirit::Pair("results", json_spirit::Array()));
json_spirit::Array &results = match.back().value_.get_array();
fillMatchResults(results, cluster.first);
if (cluster.first != "all")
{
match.push_back(json_spirit::Pair("bof_round", clusterMatchResultStatisticsLists[cluster.first].bofRound));
match.push_back(json_spirit::Pair("game_in_round", clusterMatchResultStatisticsLists[cluster.first].gameInRound));
}
else
{
match.push_back(json_spirit::Pair("bof_round", 0));
match.push_back(json_spirit::Pair("game_in_round", 0));
}
}
return root;
}
void Simulation::fillRankResults(json_spirit::Array &ranks)
{
for (RankData &rankData : this->ranks)
ranks.push_back(rankData.toJSONObject());
}
void Simulation::fillMatchResults(json_spirit::Array &results, std::string cluster)
{
results = clusterMatchResultStatisticsLists[cluster].toJSONArray();
}
void Simulation::fillTeamResults(json_spirit::Array &teamList, std::string cluster)
{
for (auto &team : teams)
{
json_spirit::Object teamData;
teamData.push_back(json_spirit::Pair("id", team.id));
if (cluster == "all")
{
teamData.push_back(json_spirit::Pair("ranks", clusterTeamResults[cluster][team.id].rankDataToJSONArray(ranks)));
teamData.push_back(json_spirit::Pair("avg_place", clusterTeamResults[cluster][team.id].getAvgPlace()));
}
teamData.push_back(json_spirit::Pair("match_data", clusterTeamResults[cluster][team.id].toJSONObject()));
teamData.push_back(json_spirit::Pair("avg_goals", clusterTeamResults[cluster][team.id].getAvgGoals()));
teamList.push_back(teamData);
}
}
} // namespace sim<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: toolbarsmenucontroller.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2006-04-07 10:18:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#define __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_HELPER_POPUPMENUCONTROLLERBASE_HXX_
#include <helper/popupmenucontrollerbase.hxx>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XPOPUPMENUCONTROLLER_HPP_
#include <com/sun/star/frame/XPopupMenuController.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <com/sun/star/frame/XLayoutManager.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGER_HPP_
#include <com/sun/star/ui/XUIConfigurationManager.hpp>
#endif
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _TOOLKIT_AWT_VCLXMENU_HXX_
#include <toolkit/awt/vclxmenu.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _UNOTOOLS_INTLWRAPPER_HXX
#include <unotools/intlwrapper.hxx>
#endif
#include <vector>
namespace framework
{
class ToolbarsMenuController : public PopupMenuControllerBase
{
public:
ToolbarsMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
virtual ~ToolbarsMenuController();
// XServiceInfo
DECLARE_XSERVICEINFO
// XPopupMenuController
virtual void SAL_CALL setPopupMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu >& PopupMenu ) throw (::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );
// XMenuListener
virtual void SAL_CALL highlight( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL select( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL activate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deactivate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );
struct ExecuteInfo
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
::com::sun::star::util::URL aTargetURL;
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs;
};
DECL_STATIC_LINK( ToolbarsMenuController, ExecuteHdl_Impl, ExecuteInfo* );
private:
void fillPopupMenu( com::sun::star::uno::Reference< com::sun::star::awt::XPopupMenu >& rPopupMenu );
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > getLayoutManagerToolbars( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager >& rLayoutManager );
rtl::OUString getUINameFromCommand( const rtl::OUString& rCommandURL );
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > getDispatchFromCommandURL( const rtl::OUString& rCommandURL );
void addCommand( com::sun::star::uno::Reference< com::sun::star::awt::XPopupMenu >& rPopupMenu, const rtl::OUString& rCommandURL, USHORT nHelpId, const rtl::OUString& aLabel );
sal_Bool isContextSensitiveToolbarNonVisible();
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xPersistentWindowState;
::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > m_xURLTransformer;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xUICommandDescription;
::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationManager > m_xModuleCfgMgr;
::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationManager > m_xDocCfgMgr;
rtl::OUString m_aModuleIdentifier;
rtl::OUString m_aPropUIName;
rtl::OUString m_aPropResourceURL;
sal_Bool m_bModuleIdentified;
sal_Bool m_bResetActive;
std::vector< rtl::OUString > m_aCommandVector;
IntlWrapper m_aIntlWrapper;
};
}
#endif // __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.8.358); FILE MERGED 2008/04/01 15:18:29 thb 1.8.358.3: #i85898# Stripping all external header guards 2008/04/01 10:57:58 thb 1.8.358.2: #i85898# Stripping all external header guards 2008/03/28 15:34:58 rt 1.8.358.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: toolbarsmenucontroller.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#define __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#include <helper/popupmenucontrollerbase.hxx>
#include <stdtypes.h>
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/frame/XStatusListener.hpp>
#include <com/sun/star/frame/XPopupMenuController.hpp>
#include <com/sun/star/frame/XLayoutManager.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/ui/XUIConfigurationManager.hpp>
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#include <toolkit/awt/vclxmenu.hxx>
#include <cppuhelper/weak.hxx>
#include <rtl/ustring.hxx>
#include <unotools/intlwrapper.hxx>
#include <vector>
namespace framework
{
class ToolbarsMenuController : public PopupMenuControllerBase
{
public:
ToolbarsMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
virtual ~ToolbarsMenuController();
// XServiceInfo
DECLARE_XSERVICEINFO
// XPopupMenuController
virtual void SAL_CALL setPopupMenu( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPopupMenu >& PopupMenu ) throw (::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );
// XMenuListener
virtual void SAL_CALL highlight( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL select( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL activate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deactivate( const ::com::sun::star::awt::MenuEvent& rEvent ) throw (::com::sun::star::uno::RuntimeException);
// XEventListener
virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );
struct ExecuteInfo
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
::com::sun::star::util::URL aTargetURL;
::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs;
};
DECL_STATIC_LINK( ToolbarsMenuController, ExecuteHdl_Impl, ExecuteInfo* );
private:
void fillPopupMenu( com::sun::star::uno::Reference< com::sun::star::awt::XPopupMenu >& rPopupMenu );
::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > getLayoutManagerToolbars( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager >& rLayoutManager );
rtl::OUString getUINameFromCommand( const rtl::OUString& rCommandURL );
::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > getDispatchFromCommandURL( const rtl::OUString& rCommandURL );
void addCommand( com::sun::star::uno::Reference< com::sun::star::awt::XPopupMenu >& rPopupMenu, const rtl::OUString& rCommandURL, USHORT nHelpId, const rtl::OUString& aLabel );
sal_Bool isContextSensitiveToolbarNonVisible();
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xPersistentWindowState;
::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > m_xURLTransformer;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xUICommandDescription;
::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationManager > m_xModuleCfgMgr;
::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationManager > m_xDocCfgMgr;
rtl::OUString m_aModuleIdentifier;
rtl::OUString m_aPropUIName;
rtl::OUString m_aPropResourceURL;
sal_Bool m_bModuleIdentified;
sal_Bool m_bResetActive;
std::vector< rtl::OUString > m_aCommandVector;
IntlWrapper m_aIntlWrapper;
};
}
#endif // __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
<|endoftext|>
|
<commit_before>/*
* main.cpp
* MOX_AE
*
* Created by Brendan Bolles on 8/26/15.
* Copyright 2015 fnord. All rights reserved.
*
*/
#include <MoxFiles/FrameBuffer.h>
#include <iostream>
#include <math.h>
using namespace MoxFiles;
static FrameBufferPtr
MakeRGBRamp()
{
const int width = 256;
const int height = 1;
FrameBufferPtr frame = new FrameBuffer(width, height);
const size_t subpixel_size = sizeof(unsigned char);
const size_t pixel_size = subpixel_size * 3;
const size_t rowbytes = pixel_size * width;
const size_t data_size = rowbytes * height;
DataChunkPtr data = new DataChunk(data_size);
frame->attachData(data);
unsigned char *origin = data->Data;
const char *chan[3] = {"R", "G", "B"};
for(int i = 0; i < 3; i++)
{
frame->insert(chan[i], Slice(MoxFiles::UINT8, (char *)origin + (i * subpixel_size), pixel_size, rowbytes));
}
unsigned char *pix = origin;
for(int x = 0; x < width; x++)
{
for(int c = 0; c < 3; c++)
{
*pix++ = x;
}
}
return frame;
}
static FrameBufferPtr
MakeYCbCrRamp()
{
const int width = 256;
const int height = 1;
FrameBufferPtr frame = new FrameBuffer(width, height);
const size_t subpixel_size = sizeof(unsigned char);
const size_t pixel_size = subpixel_size * 3;
const size_t rowbytes = pixel_size * width;
const size_t data_size = rowbytes * height;
DataChunkPtr data = new DataChunk(data_size);
frame->attachData(data);
unsigned char *origin = data->Data;
const char *chan[3] = {"Y", "Cb", "Cr"};
for(int i = 0; i < 3; i++)
{
frame->insert(chan[i], Slice(MoxFiles::UINT8, (char *)origin + (i * subpixel_size), pixel_size, rowbytes));
}
unsigned char *pix = origin;
for(int x = 0; x < width; x++)
{
*pix++ = x;
*pix++ = 128;
*pix++ = 128;
}
return frame;
}
static bool
FrameBufferYUVTest()
{
bool success = true;
FrameBufferPtr start_ramp = MakeRGBRamp();
FrameBufferPtr yuv_ramp = MakeYCbCrRamp();
FrameBufferPtr end_ramp = MakeRGBRamp();
yuv_ramp->copyFromFrame(*start_ramp);
end_ramp->copyFromFrame(*yuv_ramp);
Slice &R_start = (*start_ramp)["R"];
Slice &G_start = (*start_ramp)["G"];
Slice &B_start = (*start_ramp)["B"];
Slice &Y_mid = (*yuv_ramp)["Y"];
Slice &Cb_mid = (*yuv_ramp)["Cb"];
Slice &Cr_mid = (*yuv_ramp)["Cr"];
Slice &R_end = (*end_ramp)["R"];
Slice &G_end = (*end_ramp)["G"];
Slice &B_end = (*end_ramp)["B"];
unsigned char *R_s = (unsigned char *)R_start.base;
unsigned char *G_s = (unsigned char *)G_start.base;
unsigned char *B_s = (unsigned char *)B_start.base;
unsigned char *Y_m = (unsigned char *)Y_mid.base;
unsigned char *Cb_m = (unsigned char *)Cb_mid.base;
unsigned char *Cr_m = (unsigned char *)Cr_mid.base;
unsigned char *R_e = (unsigned char *)R_end.base;
unsigned char *G_e = (unsigned char *)G_end.base;
unsigned char *B_e = (unsigned char *)B_end.base;
const int R_s_step = R_start.xStride / sizeof(unsigned char);
const int Y_m_step = Y_mid.xStride / sizeof(unsigned char);
const int R_e_step = R_end.xStride / sizeof(unsigned char);
for(int x = 0; x < 256; x++)
{
//std::cout << "{" << (int)*R_s << "} -> {" << (int)*Y_m << "} -> {" << (int)*R_e << "}" << std::endl;
if(abs((int)*R_s - (int)*R_e) > 1)
success = false;
R_s += R_s_step;
Y_m += Y_m_step;
R_e += R_e_step;
}
return success;
}
int main(int argc, char * const argv[])
{
bool success = true;
try
{
std::cout << "FrameBufferYUVTest...";
const bool yuv_test = FrameBufferYUVTest();
std::cout << (yuv_test ? "success" : "failed") << std::endl;
if(!yuv_test)
success = false;
}
catch(std::exception &e)
{
std::cout << "Exception thrown: " << e.what() << std::endl;
success = false;
}
std::cout << std::endl;
if(success)
std::cout << "Tests successful!" << std::endl;
else
std::cout << "Tests failed :`(" << std::endl;
return (success ? 0 : -1);
}<commit_msg>Experimenting with YCgCo<commit_after>/*
* main.cpp
* MOX_AE
*
* Created by Brendan Bolles on 8/26/15.
* Copyright 2015 fnord. All rights reserved.
*
*/
#include <MoxFiles/FrameBuffer.h>
#include <iostream>
#include <math.h>
using namespace MoxFiles;
static FrameBufferPtr
MakeRGBRamp()
{
const int width = 256;
const int height = 1;
FrameBufferPtr frame = new FrameBuffer(width, height);
const size_t subpixel_size = sizeof(unsigned char);
const size_t pixel_size = subpixel_size * 3;
const size_t rowbytes = pixel_size * width;
const size_t data_size = rowbytes * height;
DataChunkPtr data = new DataChunk(data_size);
frame->attachData(data);
unsigned char *origin = data->Data;
const char *chan[3] = {"R", "G", "B"};
for(int i = 0; i < 3; i++)
{
frame->insert(chan[i], Slice(MoxFiles::UINT8, (char *)origin + (i * subpixel_size), pixel_size, rowbytes));
}
unsigned char *pix = origin;
for(int x = 0; x < width; x++)
{
for(int c = 0; c < 3; c++)
{
*pix++ = x;
}
}
return frame;
}
static FrameBufferPtr
MakeYCbCrRamp()
{
const int width = 256;
const int height = 1;
FrameBufferPtr frame = new FrameBuffer(width, height);
const size_t subpixel_size = sizeof(unsigned char);
const size_t pixel_size = subpixel_size * 3;
const size_t rowbytes = pixel_size * width;
const size_t data_size = rowbytes * height;
DataChunkPtr data = new DataChunk(data_size);
frame->attachData(data);
unsigned char *origin = data->Data;
const char *chan[3] = {"Y", "Cb", "Cr"};
for(int i = 0; i < 3; i++)
{
frame->insert(chan[i], Slice(MoxFiles::UINT8, (char *)origin + (i * subpixel_size), pixel_size, rowbytes));
}
unsigned char *pix = origin;
for(int x = 0; x < width; x++)
{
*pix++ = x;
*pix++ = 128;
*pix++ = 128;
}
return frame;
}
static bool
FrameBufferYUVTest()
{
bool success = true;
FrameBufferPtr start_ramp = MakeRGBRamp();
FrameBufferPtr yuv_ramp = MakeYCbCrRamp();
FrameBufferPtr end_ramp = MakeRGBRamp();
yuv_ramp->copyFromFrame(*start_ramp);
end_ramp->copyFromFrame(*yuv_ramp);
Slice &R_start = (*start_ramp)["R"];
Slice &G_start = (*start_ramp)["G"];
Slice &B_start = (*start_ramp)["B"];
Slice &Y_mid = (*yuv_ramp)["Y"];
Slice &Cb_mid = (*yuv_ramp)["Cb"];
Slice &Cr_mid = (*yuv_ramp)["Cr"];
Slice &R_end = (*end_ramp)["R"];
Slice &G_end = (*end_ramp)["G"];
Slice &B_end = (*end_ramp)["B"];
unsigned char *R_s = (unsigned char *)R_start.base;
unsigned char *G_s = (unsigned char *)G_start.base;
unsigned char *B_s = (unsigned char *)B_start.base;
unsigned char *Y_m = (unsigned char *)Y_mid.base;
unsigned char *Cb_m = (unsigned char *)Cb_mid.base;
unsigned char *Cr_m = (unsigned char *)Cr_mid.base;
unsigned char *R_e = (unsigned char *)R_end.base;
unsigned char *G_e = (unsigned char *)G_end.base;
unsigned char *B_e = (unsigned char *)B_end.base;
const int R_s_step = R_start.xStride / sizeof(unsigned char);
const int Y_m_step = Y_mid.xStride / sizeof(unsigned char);
const int R_e_step = R_end.xStride / sizeof(unsigned char);
for(int x = 0; x < 256; x++)
{
//std::cout << "{" << (int)*R_s << "} -> {" << (int)*Y_m << "} -> {" << (int)*R_e << "}" << std::endl;
if(abs((int)*R_s - (int)*R_e) > 1)
success = false;
R_s += R_s_step;
Y_m += Y_m_step;
R_e += R_e_step;
}
return success;
}
template <typename T, int MAX>
static bool
YCgCoTest()
{
// This test fails. You can not perform RGB -> YCgCo -> RGB at 8-bit without loss. You can
// do it losslessly if you allocate two more bits for YCgCo.
bool success = true;
const float norm = (MAX + 1) / 2;
for(int r = 0; r <= MAX; r++)
{
for(int g = 0; g <= MAX; g++)
{
for(int b = 0; b <= MAX; b++)
{
const T Y = ((float)r / 4.0) + ((float)g / 2.0) + ((float)b / 4.0) + 0.5;
const T Cg = ((float)r / -4.0) + ((float)g / 2.0) + ((float)b / -4.0) + norm + 0.5;
const T Co = ((float)r / 2.0) + ((float)b / -2.0) + norm + 0.5;
const T R = (int)Y - ((int)Cg - (int)norm) + ((int)Co - (int)norm);
const T G = (int)Y + ((int)Cg - (int)norm);
const T B = (int)Y - ((int)Cg - (int)norm) - ((int)Co - (int)norm);
// ------
/*
// another way to do it
//float Co_f = (float)r - (float)b;
//float temp = (float)b + (Co_f / 2.0);
//float Cg_f = (float)g - temp;
//float Y_f = temp + (Cg_f / 2.0);
float Y_f = ((float)r / 4.0) + ((float)g / 2.0) + ((float)b / 4.0);
float Cg_f = ((float)r / -4.0) + ((float)g / 2.0) + ((float)b / -4.0);
float Co_f = ((float)r / 2.0) + ((float)b / -2.0);
const T Y = Y_f + 0.5;
const T Cg = Cg_f + norm + 0.5;
const T Co = Co_f + norm + 0.5;
//Y_f = Y;
//Cg_f = (float)Cg - norm;
//Co_f = (float)Co - norm;
float temp2 = Y_f - Cg_f;
float R_f = temp2 + Co_f;
float G_f = Y_f + Cg_f;
float B_f = temp2 - Co_f;
const T R = R_f + 0.5;
const T G = G_f + 0.5;
const T B = B_f + 0.5;
*/
// ---------
/*
// cool alternative YCoCg24 that actually works found here
// http://stackoverflow.com/questions/10566668/lossless-rgb-to-ycbcr-transformation
const T Co = ((int)b - (int)r) % 0x100;
const int temp = ((int)r + ((int)Co >> 1)) % 0x100;
const T Cg = ((int)temp - (int)g) % 0x100;
const T Y = ((int)g + ((int)Cg >> 1)) % 0x100;
const T G = ((int)Y - ((int)Cg >> 1)) % 0x100;
const int temp2 = ((int)G + (int)Cg) % 0x100;
const T R = ((int)temp2 - ((int)Co >> 1)) % 0x100;
const T B = ((int)R + (int)Co) % 0x100;
seems similar to YCoCg-R here
// http://research.microsoft.com/pubs/102040/2008_ColorTransforms_MalvarSullivanSrinivasan.PDF
*/
// -----------
/*
// JPEG 2000 reversible color transform
// https://en.wikipedia.org/wiki/JPEG_2000#Color_components_transformation
// Doesn't seem totally reversible without more bits
const T Y = (((float)r + (2.0 * (float)g) + (float)b) / 4.0) + 0.5;
const int Cb = (int)b - (int)g;
const int Cr = (int)r - (int)g;
const int Cg = Cb; // for display only
const int Co = Cr;
const T G = (float)Y - (((float)Cb + (float)Cr) / 4.0) + 0.5;
const T R = Cr + G;
const T B = Cb + G;
*/
std::cout << "{" << (int)r << ", " << (int)g << ", " << (int)b << "} -> ";
std::cout << "{" << (int)Y << ", " << (int)Cg << ", " << (int)Co << "} -> ";
std::cout << "{" << (int)R << ", " << (int)G << ", " << (int)B << "}";
if(r != R || g != G || b != B)
{
std::cout << " NO MATCH";
success = false;
}
std::cout << std::endl;
}
}
}
return success;
}
int main(int argc, char * const argv[])
{
bool success = true;
try
{
std::cout << "FrameBufferYUVTest...";
const bool yuv_test = FrameBufferYUVTest();
std::cout << (yuv_test ? "success" : "failed") << std::endl;
if(!yuv_test)
success = false;
//std::cout << "YCgCoTest...";
//const bool ycgco_test = YCgCoTest<unsigned char, 255>();
//std::cout << (ycgco_test ? "success" : "failed") << std::endl;
//if(!ycgco_test)
// success = false;
}
catch(std::exception &e)
{
std::cout << "Exception thrown: " << e.what() << std::endl;
success = false;
}
std::cout << std::endl;
if(success)
std::cout << "Tests successful!" << std::endl;
else
std::cout << "Tests failed :`(" << std::endl;
return (success ? 0 : -1);
}<|endoftext|>
|
<commit_before>// $Id: property.C,v 1.25 2001/05/17 01:30:49 oliver Exp $
#include <BALL/CONCEPT/property.h>
#include <BALL/CONCEPT/persistenceManager.h>
#include <BALL/CONCEPT/textPersistenceManager.h>
using namespace std;
namespace BALL
{
NamedProperty::NamedProperty()
throw()
: PersistentObject(),
type_(NONE),
name_("")
{
}
NamedProperty::NamedProperty(const NamedProperty& property)
throw()
: PersistentObject(property),
type_(property.type_),
name_(property.name_)
{
if (type_ != STRING)
{
data_ = property.data_;
}
else
{
data_.s = new string(*property.data_.s);
}
}
void NamedProperty::persistentWrite(PersistenceManager& pm, const char* name) const
throw()
{
pm.writeObjectHeader(this, name);
pm.writePrimitive((int)type_, "type_");
pm.writePrimitive(String(name_), "name_");
switch (type_)
{
case INT: pm.writePrimitive(data_.i, "data_.i"); break;
case FLOAT: pm.writePrimitive(data_.f, "data_.f"); break;
case DOUBLE: pm.writePrimitive(data_.d, "data_.d"); break;
case UNSIGNED_INT: pm.writePrimitive(data_.ui, "data_.ui"); break;
case BOOL: pm.writePrimitive(data_.b, "data_.b"); break;
case OBJECT: pm.writeObjectPointer(data_.object, "data_.object"); break;
case NONE: break;
case STRING: pm.writePrimitive(String(*data_.s), "data_.s"); break;
default:
Log.error() << "cannot write unknown property type: " << (int)type_ << endl;
}
pm.writeObjectTrailer(name);
}
void NamedProperty::persistentRead(PersistenceManager& pm)
throw()
{
int type;
pm.readPrimitive(type, "type_");
type_ = (Type)type;
String s;
pm.readPrimitive(s, "name_");
name_ = s;
switch (type_)
{
case INT: pm.readPrimitive(data_.i, "data_.i"); break;
case FLOAT: pm.readPrimitive(data_.f, "data_.f"); break;
case DOUBLE: pm.readPrimitive(data_.d, "data_.d"); break;
case UNSIGNED_INT: pm.readPrimitive(data_.ui, "data_.ui"); break;
case BOOL: pm.readPrimitive(data_.b, "data_.b"); break;
case NONE: break;
case STRING:
// we have to create a new string
pm.readPrimitive(s, "data_.s");
data_.s = new string(s);
break;
case OBJECT:
// the persistence manager will take care of
// reading the object and will set this pointer afterwards
pm.readObjectPointer(data_.object, "data_.object");
break;
default:
Log.error() << "Unknown type while reading NamedProperty: " << (int)type_ << endl;
}
}
/// Output operator
ostream& operator << (std::ostream& s, const NamedProperty& property)
throw()
{
s << property.type_;
s << endl;
s << property.name_;
s << endl;
switch (property.type_)
{
case NamedProperty::BOOL: s << property.data_.b; break;
case NamedProperty::INT: s << property.data_.i; break;
case NamedProperty::UNSIGNED_INT: s << property.data_.ui; break;
case NamedProperty::FLOAT: s << property.data_.f; break;
case NamedProperty::DOUBLE: s << property.data_.d; break;
case NamedProperty::STRING: s << *property.data_.s; break;
case NamedProperty::OBJECT:
{
TextPersistenceManager pm;
pm.setOstream(s);
pm.writeObjectPointer(property.data_.object, "data_.object");
break;
}
case NamedProperty::NONE : break;
default:
Log.error() << "Unknown type while writing NamedProperty: " << (int)property.type_ << endl;
}
return s;
}
/// Input operator
istream& operator >> (std::istream& s, NamedProperty& property)
throw()
{
Index tmp;
s >> tmp;
property.type_ = (NamedProperty::Type)tmp;
s >> property.name_;
switch (property.type_)
{
case NamedProperty::BOOL : s >> property.data_.b; break;
case NamedProperty::INT : s >> property.data_.i; break;
case NamedProperty::UNSIGNED_INT : s >> property.data_.ui; break;
case NamedProperty::FLOAT : s >> property.data_.f; break;
case NamedProperty::DOUBLE :s >> property.data_.d; break;
case NamedProperty::OBJECT :
{
TextPersistenceManager pm;
pm.setIstream(s);
pm.readObjectPointer(property.data_.object, "data_.object");
break;
}
case NamedProperty::NONE : break;
case NamedProperty::STRING :
{
string str;
s >> str;
property.data_.s = new string(str);
break;
}
default:
Log.error() << "Unknown type while reading NamedProperty: " << (int)property.type_ << endl;
}
return s;
}
ostream& operator << (ostream& s, const PropertyManager& property_manager)
throw()
{
s << property_manager.bitvector_;
s << endl;
s << property_manager.named_properties_.size();
s << endl;
vector<NamedProperty>::const_iterator it = property_manager.named_properties_.begin();
for (; it != property_manager.named_properties_.end(); ++it)
{
s << *it << endl;
}
return s;
}
istream& operator >> (istream& s, PropertyManager& property_manager)
throw()
{
int size;
s >> property_manager.bitvector_;
s >> size;
NamedProperty np;
for (int i = 0; i < size; i++)
{
s >> np;
property_manager.setProperty(np);
}
return s;
}
void PropertyManager::write(PersistenceManager& pm) const
throw()
{
pm.writeStorableObject(bitvector_, "bitvector_");
Size size = (Size)named_properties_.size();
pm.writePrimitive(size, "size");
for (Size i = 0; i < size; i++)
{
named_properties_[i].persistentWrite(pm, "");
}
}
bool PropertyManager::read(PersistenceManager& pm)
throw()
{
if (!pm.readStorableObject(bitvector_, "bitvector_"))
{
return false;
}
NamedProperty property("");
named_properties_.clear();
Size size = 0;
pm.readPrimitive(size, "size");
for (Size i = 0; i < size; i++)
{
pm.checkObjectHeader(property, "");
property.persistentRead(pm);
pm.checkObjectTrailer("");
named_properties_.push_back(property);
}
return true;
}
void PropertyManager::set(const PropertyManager& property_manager, bool /* deep */)
throw()
{
bitvector_ = property_manager.bitvector_;
named_properties_ = property_manager.named_properties_;
}
void PropertyManager::setProperty(const NamedProperty& property)
throw()
{
// search whether the property already exists
vector<NamedProperty>::iterator it = named_properties_.begin();
for (; it != named_properties_.end(); ++it)
{
if (it->getName() == property.getName())
{
// yes, it exists. Erase the old content
named_properties_.erase(it);
break;
}
}
// add the new content
named_properties_.push_back(property);
}
void PropertyManager::setProperty(const string& name)
throw()
{
// search whether a property with the same name already exists
vector<NamedProperty>::iterator it = named_properties_.begin();
for (; it != named_properties_.end(); ++it)
{
if (it->getName() == name)
{
// yes, it exists. Erase the old content
named_properties_.erase(it);
break;
}
}
// add the new content
named_properties_.push_back(NamedProperty(name));
}
const NamedProperty& PropertyManager::getProperty(const string& name) const
throw()
{
for (Size i = 0; i < named_properties_.size(); ++i)
{
if (named_properties_[i].getName() == name)
{
return named_properties_[i];
}
}
return RTTI::getDefault<NamedProperty>();
}
void PropertyManager::clearProperty(const string& name)
throw()
{
vector<NamedProperty>::iterator it = named_properties_.begin();
for (; it != named_properties_.end(); ++it)
{
if (it->getName() == name)
{
named_properties_.erase(it);
break;
}
}
}
bool PropertyManager::hasProperty(const string& name) const
throw()
{
for (Size i = 0; i < named_properties_.size(); i++)
{
if (named_properties_[i].getName() == name)
{
return true;
}
}
return false;
}
void PropertyManager::dump(ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_CLASS_HEADER(s, PropertyManager, this);
BALL_DUMP_DEPTH(s, depth);
s << bitvector_ << endl;
for (Size i = 0; i < named_properties_.size(); ++i)
{
BALL_DUMP_DEPTH(s, depth);
s << "(" << named_properties_[i].getName();
switch (named_properties_[i].getType())
{
case NamedProperty::NONE:
s << "NONE: ";
break;
case NamedProperty::BOOL:
s << "BOOL: " << named_properties_[i].getBool();
break;
case NamedProperty::INT:
s << "INT: " << named_properties_[i].getInt();
break;
case NamedProperty::UNSIGNED_INT:
s << "UNSIGNED_INT: " << named_properties_[i].getUnsignedInt();
break;
case NamedProperty::FLOAT:
s << "FLOAT: " << named_properties_[i].getFloat();
break;
case NamedProperty::DOUBLE:
s << "DOUBLE: " << named_properties_[i].getDouble();
break;
case NamedProperty::STRING:
s << "STRING: " << (char)34 << named_properties_[i].getString().c_str() << (char)34;
break;
case NamedProperty::OBJECT:
s << "OBJECT: " << named_properties_[i].getObject();
}
s << ")" << endl;
}
BALL_DUMP_STREAM_SUFFIX(s);
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/CONCEPT/property.iC>
# endif
} // namespace BALL
<commit_msg>fixed: removed deep parameter for set method<commit_after>// $Id: property.C,v 1.26 2001/06/14 00:31:12 oliver Exp $
#include <BALL/CONCEPT/property.h>
#include <BALL/CONCEPT/persistenceManager.h>
#include <BALL/CONCEPT/textPersistenceManager.h>
using namespace std;
namespace BALL
{
NamedProperty::NamedProperty()
throw()
: PersistentObject(),
type_(NONE),
name_("")
{
}
NamedProperty::NamedProperty(const NamedProperty& property)
throw()
: PersistentObject(property),
type_(property.type_),
name_(property.name_)
{
if (type_ != STRING)
{
data_ = property.data_;
}
else
{
data_.s = new string(*property.data_.s);
}
}
void NamedProperty::persistentWrite(PersistenceManager& pm, const char* name) const
throw()
{
pm.writeObjectHeader(this, name);
pm.writePrimitive((int)type_, "type_");
pm.writePrimitive(String(name_), "name_");
switch (type_)
{
case INT: pm.writePrimitive(data_.i, "data_.i"); break;
case FLOAT: pm.writePrimitive(data_.f, "data_.f"); break;
case DOUBLE: pm.writePrimitive(data_.d, "data_.d"); break;
case UNSIGNED_INT: pm.writePrimitive(data_.ui, "data_.ui"); break;
case BOOL: pm.writePrimitive(data_.b, "data_.b"); break;
case OBJECT: pm.writeObjectPointer(data_.object, "data_.object"); break;
case NONE: break;
case STRING: pm.writePrimitive(String(*data_.s), "data_.s"); break;
default:
Log.error() << "cannot write unknown property type: " << (int)type_ << endl;
}
pm.writeObjectTrailer(name);
}
void NamedProperty::persistentRead(PersistenceManager& pm)
throw()
{
int type;
pm.readPrimitive(type, "type_");
type_ = (Type)type;
String s;
pm.readPrimitive(s, "name_");
name_ = s;
switch (type_)
{
case INT: pm.readPrimitive(data_.i, "data_.i"); break;
case FLOAT: pm.readPrimitive(data_.f, "data_.f"); break;
case DOUBLE: pm.readPrimitive(data_.d, "data_.d"); break;
case UNSIGNED_INT: pm.readPrimitive(data_.ui, "data_.ui"); break;
case BOOL: pm.readPrimitive(data_.b, "data_.b"); break;
case NONE: break;
case STRING:
// we have to create a new string
pm.readPrimitive(s, "data_.s");
data_.s = new string(s);
break;
case OBJECT:
// the persistence manager will take care of
// reading the object and will set this pointer afterwards
pm.readObjectPointer(data_.object, "data_.object");
break;
default:
Log.error() << "Unknown type while reading NamedProperty: " << (int)type_ << endl;
}
}
/// Output operator
ostream& operator << (std::ostream& s, const NamedProperty& property)
throw()
{
s << property.type_;
s << endl;
s << property.name_;
s << endl;
switch (property.type_)
{
case NamedProperty::BOOL: s << property.data_.b; break;
case NamedProperty::INT: s << property.data_.i; break;
case NamedProperty::UNSIGNED_INT: s << property.data_.ui; break;
case NamedProperty::FLOAT: s << property.data_.f; break;
case NamedProperty::DOUBLE: s << property.data_.d; break;
case NamedProperty::STRING: s << *property.data_.s; break;
case NamedProperty::OBJECT:
{
TextPersistenceManager pm;
pm.setOstream(s);
pm.writeObjectPointer(property.data_.object, "data_.object");
break;
}
case NamedProperty::NONE : break;
default:
Log.error() << "Unknown type while writing NamedProperty: " << (int)property.type_ << endl;
}
return s;
}
/// Input operator
istream& operator >> (std::istream& s, NamedProperty& property)
throw()
{
Index tmp;
s >> tmp;
property.type_ = (NamedProperty::Type)tmp;
s >> property.name_;
switch (property.type_)
{
case NamedProperty::BOOL : s >> property.data_.b; break;
case NamedProperty::INT : s >> property.data_.i; break;
case NamedProperty::UNSIGNED_INT : s >> property.data_.ui; break;
case NamedProperty::FLOAT : s >> property.data_.f; break;
case NamedProperty::DOUBLE :s >> property.data_.d; break;
case NamedProperty::OBJECT :
{
TextPersistenceManager pm;
pm.setIstream(s);
pm.readObjectPointer(property.data_.object, "data_.object");
break;
}
case NamedProperty::NONE : break;
case NamedProperty::STRING :
{
string str;
s >> str;
property.data_.s = new string(str);
break;
}
default:
Log.error() << "Unknown type while reading NamedProperty: " << (int)property.type_ << endl;
}
return s;
}
ostream& operator << (ostream& s, const PropertyManager& property_manager)
throw()
{
s << property_manager.bitvector_;
s << endl;
s << property_manager.named_properties_.size();
s << endl;
vector<NamedProperty>::const_iterator it = property_manager.named_properties_.begin();
for (; it != property_manager.named_properties_.end(); ++it)
{
s << *it << endl;
}
return s;
}
istream& operator >> (istream& s, PropertyManager& property_manager)
throw()
{
int size;
s >> property_manager.bitvector_;
s >> size;
NamedProperty np;
for (int i = 0; i < size; i++)
{
s >> np;
property_manager.setProperty(np);
}
return s;
}
void PropertyManager::write(PersistenceManager& pm) const
throw()
{
pm.writeStorableObject(bitvector_, "bitvector_");
Size size = (Size)named_properties_.size();
pm.writePrimitive(size, "size");
for (Size i = 0; i < size; i++)
{
named_properties_[i].persistentWrite(pm, "");
}
}
bool PropertyManager::read(PersistenceManager& pm)
throw()
{
if (!pm.readStorableObject(bitvector_, "bitvector_"))
{
return false;
}
NamedProperty property("");
named_properties_.clear();
Size size = 0;
pm.readPrimitive(size, "size");
for (Size i = 0; i < size; i++)
{
pm.checkObjectHeader(property, "");
property.persistentRead(pm);
pm.checkObjectTrailer("");
named_properties_.push_back(property);
}
return true;
}
void PropertyManager::set(const PropertyManager& property_manager)
throw()
{
bitvector_ = property_manager.bitvector_;
named_properties_ = property_manager.named_properties_;
}
void PropertyManager::setProperty(const NamedProperty& property)
throw()
{
// search whether the property already exists
vector<NamedProperty>::iterator it = named_properties_.begin();
for (; it != named_properties_.end(); ++it)
{
if (it->getName() == property.getName())
{
// yes, it exists. Erase the old content
named_properties_.erase(it);
break;
}
}
// add the new content
named_properties_.push_back(property);
}
void PropertyManager::setProperty(const string& name)
throw()
{
// search whether a property with the same name already exists
vector<NamedProperty>::iterator it = named_properties_.begin();
for (; it != named_properties_.end(); ++it)
{
if (it->getName() == name)
{
// yes, it exists. Erase the old content
named_properties_.erase(it);
break;
}
}
// add the new content
named_properties_.push_back(NamedProperty(name));
}
const NamedProperty& PropertyManager::getProperty(const string& name) const
throw()
{
for (Size i = 0; i < named_properties_.size(); ++i)
{
if (named_properties_[i].getName() == name)
{
return named_properties_[i];
}
}
return RTTI::getDefault<NamedProperty>();
}
void PropertyManager::clearProperty(const string& name)
throw()
{
vector<NamedProperty>::iterator it = named_properties_.begin();
for (; it != named_properties_.end(); ++it)
{
if (it->getName() == name)
{
named_properties_.erase(it);
break;
}
}
}
bool PropertyManager::hasProperty(const string& name) const
throw()
{
for (Size i = 0; i < named_properties_.size(); i++)
{
if (named_properties_[i].getName() == name)
{
return true;
}
}
return false;
}
void PropertyManager::dump(ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_CLASS_HEADER(s, PropertyManager, this);
BALL_DUMP_DEPTH(s, depth);
s << bitvector_ << endl;
for (Size i = 0; i < named_properties_.size(); ++i)
{
BALL_DUMP_DEPTH(s, depth);
s << "(" << named_properties_[i].getName();
switch (named_properties_[i].getType())
{
case NamedProperty::NONE:
s << "NONE: ";
break;
case NamedProperty::BOOL:
s << "BOOL: " << named_properties_[i].getBool();
break;
case NamedProperty::INT:
s << "INT: " << named_properties_[i].getInt();
break;
case NamedProperty::UNSIGNED_INT:
s << "UNSIGNED_INT: " << named_properties_[i].getUnsignedInt();
break;
case NamedProperty::FLOAT:
s << "FLOAT: " << named_properties_[i].getFloat();
break;
case NamedProperty::DOUBLE:
s << "DOUBLE: " << named_properties_[i].getDouble();
break;
case NamedProperty::STRING:
s << "STRING: " << (char)34 << named_properties_[i].getString().c_str() << (char)34;
break;
case NamedProperty::OBJECT:
s << "OBJECT: " << named_properties_[i].getObject();
}
s << ")" << endl;
}
BALL_DUMP_STREAM_SUFFIX(s);
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/CONCEPT/property.iC>
# endif
} // namespace BALL
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bridge_provider.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:21:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include "remote_bridge.hxx"
#include <osl/diagnose.h>
#include <uno/mapping.hxx>
#include <uno/environment.h>
#include <bridges/remote/remote.h>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::bridge;
namespace remotebridges_bridge
{
OInstanceProviderWrapper::OInstanceProviderWrapper(
const Reference <XInstanceProvider > & rProvider,
ORemoteBridge * pBridgeCallback ) :
m_rProvider( rProvider ),
m_pBridgeCallback( pBridgeCallback ),
m_nRef( 0 )
{
g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
acquire = thisAcquire;
release = thisRelease;
getInstance = thisGetInstance;
}
OInstanceProviderWrapper::~OInstanceProviderWrapper()
{
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
void OInstanceProviderWrapper::thisAcquire( remote_InstanceProvider *p )
{
OInstanceProviderWrapper * m = (OInstanceProviderWrapper *) p;
osl_incrementInterlockedCount( &(m->m_nRef ) );
}
void OInstanceProviderWrapper::thisRelease( remote_InstanceProvider *p )
{
OInstanceProviderWrapper * m = ( OInstanceProviderWrapper *) p;
if( ! osl_decrementInterlockedCount( &(m->m_nRef ) ) )
{
delete m;
}
}
static void convertToRemoteRuntimeException ( uno_Any **ppException,
const ::rtl::OUString &sMessage,
const Reference< XInterface > &rContext,
Mapping &map )
{
uno_type_any_construct( *ppException ,
0 ,
getCppuType( (RuntimeException *)0 ).getTypeLibType() ,
0 );
typelib_CompoundTypeDescription * pCompType = 0 ;
getCppuType( (Exception*)0 ).getDescription( (typelib_TypeDescription **) &pCompType );
if( ! ((typelib_TypeDescription *)pCompType)->bComplete )
{
typelib_typedescription_complete( (typelib_TypeDescription**) &pCompType );
}
char *pValue = (char*) (*ppException)->pData;
rtl_uString_assign( (rtl_uString ** ) pValue , sMessage.pData );
*((remote_Interface**) pValue+pCompType->pMemberOffsets[1]) =
(remote_Interface*) map.mapInterface(
rContext.get(), getCppuType( &rContext) );
typelib_typedescription_release( (typelib_TypeDescription *) pCompType );
}
void OInstanceProviderWrapper::thisGetInstance(
remote_InstanceProvider * pProvider ,
uno_Environment *pEnvRemote,
remote_Interface **ppRemoteI,
rtl_uString *pInstanceName,
typelib_InterfaceTypeDescription *pType,
uno_Any **ppException
)
{
OInstanceProviderWrapper * m = (OInstanceProviderWrapper *)pProvider;
OSL_ASSERT( ppRemoteI );
if( *ppRemoteI )
{
(*ppRemoteI)->release( *ppRemoteI );
*ppRemoteI = 0;
}
if( OUString( pType->aBase.pTypeName ) ==
getCppuType( (Reference<XInterface>*)0).getTypeName() )
{
OUString sCppuName( RTL_CONSTASCII_USTRINGPARAM( CPPU_CURRENT_LANGUAGE_BINDING_NAME ) );
uno_Environment *pEnvThis = 0;
uno_getEnvironment( &pEnvThis ,
sCppuName.pData ,
0 );
Mapping map( pEnvThis , pEnvRemote );
pEnvThis->release( pEnvThis );
try
{
Reference< XInterface > r = m->m_rProvider->getInstance(
OUString( pInstanceName ) );
*ppRemoteI = (remote_Interface*) map.mapInterface (
r.get(),
getCppuType( (Reference< XInterface > *) 0 )
);
if( *ppRemoteI && m->m_pBridgeCallback )
{
m->m_pBridgeCallback->objectMappedSuccesfully();
m->m_pBridgeCallback = 0;
}
*ppException = 0;
}
catch( ::com::sun::star::container::NoSuchElementException &e )
{
// NoSuchElementException not specified, so convert it to a runtime exception
convertToRemoteRuntimeException(
ppException , e.Message.pData , e.Context.get(), map );
}
catch( ::com::sun::star::uno::RuntimeException &e )
{
convertToRemoteRuntimeException(
ppException , e.Message.pData , e.Context.get(), map );
}
}
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.4.126); FILE MERGED 2005/09/22 20:50:51 sb 1.4.126.2: RESYNC: (1.4-1.5); FILE MERGED 2005/09/09 15:43:21 sb 1.4.126.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bridge_provider.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 13:16:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include "remote_bridge.hxx"
#include <osl/diagnose.h>
#include <uno/mapping.hxx>
#include <uno/environment.h>
#include <bridges/remote/remote.h>
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::bridge;
namespace remotebridges_bridge
{
OInstanceProviderWrapper::OInstanceProviderWrapper(
const Reference <XInstanceProvider > & rProvider,
ORemoteBridge * pBridgeCallback ) :
m_rProvider( rProvider ),
m_nRef( 0 ),
m_pBridgeCallback( pBridgeCallback )
{
g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
acquire = thisAcquire;
release = thisRelease;
getInstance = thisGetInstance;
}
OInstanceProviderWrapper::~OInstanceProviderWrapper()
{
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
void OInstanceProviderWrapper::thisAcquire( remote_InstanceProvider *p )
{
OInstanceProviderWrapper * m = (OInstanceProviderWrapper *) p;
osl_incrementInterlockedCount( &(m->m_nRef ) );
}
void OInstanceProviderWrapper::thisRelease( remote_InstanceProvider *p )
{
OInstanceProviderWrapper * m = ( OInstanceProviderWrapper *) p;
if( ! osl_decrementInterlockedCount( &(m->m_nRef ) ) )
{
delete m;
}
}
static void convertToRemoteRuntimeException ( uno_Any **ppException,
const ::rtl::OUString &sMessage,
const Reference< XInterface > &rContext,
Mapping &map )
{
uno_type_any_construct( *ppException ,
0 ,
getCppuType( (RuntimeException *)0 ).getTypeLibType() ,
0 );
typelib_CompoundTypeDescription * pCompType = 0 ;
getCppuType( (Exception*)0 ).getDescription( (typelib_TypeDescription **) &pCompType );
if( ! ((typelib_TypeDescription *)pCompType)->bComplete )
{
typelib_typedescription_complete( (typelib_TypeDescription**) &pCompType );
}
char *pValue = (char*) (*ppException)->pData;
rtl_uString_assign( (rtl_uString ** ) pValue , sMessage.pData );
*((remote_Interface**) pValue+pCompType->pMemberOffsets[1]) =
(remote_Interface*) map.mapInterface(
rContext.get(), getCppuType( &rContext) );
typelib_typedescription_release( (typelib_TypeDescription *) pCompType );
}
void OInstanceProviderWrapper::thisGetInstance(
remote_InstanceProvider * pProvider ,
uno_Environment *pEnvRemote,
remote_Interface **ppRemoteI,
rtl_uString *pInstanceName,
typelib_InterfaceTypeDescription *pType,
uno_Any **ppException
)
{
OInstanceProviderWrapper * m = (OInstanceProviderWrapper *)pProvider;
OSL_ASSERT( ppRemoteI );
if( *ppRemoteI )
{
(*ppRemoteI)->release( *ppRemoteI );
*ppRemoteI = 0;
}
if( OUString( pType->aBase.pTypeName ) ==
getCppuType( (Reference<XInterface>*)0).getTypeName() )
{
OUString sCppuName( RTL_CONSTASCII_USTRINGPARAM( CPPU_CURRENT_LANGUAGE_BINDING_NAME ) );
uno_Environment *pEnvThis = 0;
uno_getEnvironment( &pEnvThis ,
sCppuName.pData ,
0 );
Mapping map( pEnvThis , pEnvRemote );
pEnvThis->release( pEnvThis );
try
{
Reference< XInterface > r = m->m_rProvider->getInstance(
OUString( pInstanceName ) );
*ppRemoteI = (remote_Interface*) map.mapInterface (
r.get(),
getCppuType( (Reference< XInterface > *) 0 )
);
if( *ppRemoteI && m->m_pBridgeCallback )
{
m->m_pBridgeCallback->objectMappedSuccesfully();
m->m_pBridgeCallback = 0;
}
*ppException = 0;
}
catch( ::com::sun::star::container::NoSuchElementException &e )
{
// NoSuchElementException not specified, so convert it to a runtime exception
convertToRemoteRuntimeException(
ppException , e.Message.pData , e.Context.get(), map );
}
catch( ::com::sun::star::uno::RuntimeException &e )
{
convertToRemoteRuntimeException(
ppException , e.Message.pData , e.Context.get(), map );
}
}
}
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2018 Baldur Karlsson
*
* 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 "spirv_common.h"
#include "common/common.h"
#undef min
#undef max
#include "3rdparty/glslang/glslang/Public/ShaderLang.h"
static bool inited = false;
std::vector<glslang::TShader *> allocatedShaders;
std::vector<glslang::TProgram *> allocatedPrograms;
void InitSPIRVCompiler()
{
if(!inited)
{
glslang::InitializeProcess();
inited = true;
}
}
void ShutdownSPIRVCompiler()
{
if(inited)
{
// programs must be deleted before shaders
for(glslang::TProgram *program : allocatedPrograms)
delete program;
for(glslang::TShader *shader : allocatedShaders)
delete shader;
allocatedPrograms.clear();
allocatedShaders.clear();
glslang::FinalizeProcess();
}
}
void SPIRVFillCBufferVariables(const rdcarray<ShaderConstant> &invars,
vector<ShaderVariable> &outvars, const bytebuf &data,
size_t baseOffset)
{
for(size_t v = 0; v < invars.size(); v++)
{
std::string basename = invars[v].name;
uint32_t rows = invars[v].type.descriptor.rows;
uint32_t cols = invars[v].type.descriptor.columns;
uint32_t elems = RDCMAX(1U, invars[v].type.descriptor.elements);
bool rowMajor = invars[v].type.descriptor.rowMajorStorage != 0;
bool isArray = elems > 1;
size_t dataOffset =
baseOffset + invars[v].reg.vec * sizeof(float) * 4 + invars[v].reg.comp * sizeof(float);
if(!invars[v].type.members.empty() || (rows == 0 && cols == 0))
{
ShaderVariable var;
var.name = basename;
var.rows = var.columns = 0;
var.type = VarType::Float;
var.rowMajor = rowMajor;
vector<ShaderVariable> varmembers;
if(isArray)
{
for(uint32_t i = 0; i < elems; i++)
{
ShaderVariable vr;
vr.name = StringFormat::Fmt("%s[%u]", basename.c_str(), i);
vr.rows = vr.columns = 0;
vr.type = VarType::Float;
vr.rowMajor = rowMajor;
vector<ShaderVariable> mems;
SPIRVFillCBufferVariables(invars[v].type.members, mems, data, dataOffset);
dataOffset += invars[v].type.descriptor.arrayByteStride;
vr.isStruct = true;
vr.members = mems;
varmembers.push_back(vr);
}
var.isStruct = false;
}
else
{
var.isStruct = true;
SPIRVFillCBufferVariables(invars[v].type.members, varmembers, data, dataOffset);
}
{
var.members = varmembers;
outvars.push_back(var);
}
continue;
}
size_t outIdx = outvars.size();
outvars.resize(outvars.size() + 1);
{
outvars[outIdx].name = basename;
outvars[outIdx].rows = 1;
outvars[outIdx].type = invars[v].type.descriptor.type;
outvars[outIdx].isStruct = false;
outvars[outIdx].columns = cols;
outvars[outIdx].rowMajor = rowMajor;
size_t elemByteSize = 4;
if(outvars[outIdx].type == VarType::Double)
elemByteSize = 8;
ShaderVariable &var = outvars[outIdx];
if(!isArray)
{
outvars[outIdx].rows = rows;
if(dataOffset < data.size())
{
const byte *d = &data[dataOffset];
RDCASSERT(rows <= 4 && rows * cols <= 16, rows, cols);
if(!rowMajor)
{
uint32_t tmp[16] = {0};
for(uint32_t c = 0; c < cols; c++)
{
size_t srcoffs = 4 * elemByteSize * c;
size_t dstoffs = rows * elemByteSize * c;
memcpy((byte *)(tmp) + dstoffs, d + srcoffs,
RDCMIN(data.size() - dataOffset + srcoffs, elemByteSize * rows));
}
// transpose
for(size_t r = 0; r < rows; r++)
for(size_t c = 0; c < cols; c++)
outvars[outIdx].value.uv[r * cols + c] = tmp[c * rows + r];
}
else
{
for(uint32_t r = 0; r < rows; r++)
{
size_t srcoffs = 4 * elemByteSize * r;
size_t dstoffs = cols * elemByteSize * r;
memcpy((byte *)(&outvars[outIdx].value.uv[0]) + dstoffs, d + srcoffs,
RDCMIN(data.size() - dataOffset + srcoffs, elemByteSize * cols));
}
}
}
}
else
{
var.name = outvars[outIdx].name;
var.rows = 0;
var.columns = 0;
bool isMatrix = rows > 1 && cols > 1;
vector<ShaderVariable> varmembers;
varmembers.resize(elems);
std::string base = outvars[outIdx].name;
// primary is the 'major' direction
// so we copy secondaryDim number of primaryDim-sized elements
uint32_t primaryDim = cols;
uint32_t secondaryDim = rows;
if(isMatrix && rowMajor)
{
primaryDim = rows;
secondaryDim = cols;
}
for(uint32_t e = 0; e < elems; e++)
{
varmembers[e].name = StringFormat::Fmt("%s[%u]", base.c_str(), e);
varmembers[e].rows = rows;
varmembers[e].type = invars[v].type.descriptor.type;
varmembers[e].isStruct = false;
varmembers[e].columns = cols;
varmembers[e].rowMajor = rowMajor;
size_t rowDataOffset = dataOffset;
dataOffset += invars[v].type.descriptor.arrayByteStride;
if(rowDataOffset < data.size())
{
const byte *d = &data[rowDataOffset];
// each primary element (row or column) is stored in a float4.
// we copy some padding here, but that will come out in the wash
// when we transpose
for(uint32_t s = 0; s < secondaryDim; s++)
{
uint32_t matStride = primaryDim;
if(matStride == 3)
matStride = 4;
memcpy(&(varmembers[e].value.uv[primaryDim * s]), d + matStride * elemByteSize * s,
RDCMIN(data.size() - rowDataOffset, elemByteSize * primaryDim));
}
if(!rowMajor)
{
ShaderVariable tmp = varmembers[e];
// transpose
for(size_t ri = 0; ri < rows; ri++)
for(size_t ci = 0; ci < cols; ci++)
varmembers[e].value.uv[ri * cols + ci] = tmp.value.uv[ci * rows + ri];
}
}
}
{
var.isStruct = false;
var.members = varmembers;
}
}
}
}
}
void FillSpecConstantVariables(const rdcarray<ShaderConstant> &invars,
std::vector<ShaderVariable> &outvars,
const std::vector<SpecConstant> &specInfo)
{
outvars.resize(invars.size());
for(size_t v = 0; v < invars.size(); v++)
{
outvars[v].rows = invars[v].type.descriptor.rows;
outvars[v].columns = invars[v].type.descriptor.columns;
outvars[v].isStruct = !invars[v].type.members.empty();
RDCASSERT(!outvars[v].isStruct);
outvars[v].name = invars[v].name;
outvars[v].type = invars[v].type.descriptor.type;
outvars[v].value.uv[0] = (invars[v].defaultValue & 0xFFFFFFFF);
outvars[v].value.uv[1] = ((invars[v].defaultValue >> 32) & 0xFFFFFFFF);
}
// find any actual values specified
for(size_t i = 0; i < specInfo.size(); i++)
{
for(size_t v = 0; v < invars.size(); v++)
{
if(specInfo[i].specID == invars[v].reg.vec)
{
memcpy(outvars[v].value.uv, specInfo[i].data.data(),
RDCMIN(specInfo[i].data.size(), sizeof(outvars[v].value.uv)));
break;
}
}
}
}
void glslangGetProgramInterfaceiv(glslang::TProgram *program, ReflectionInterface programInterface,
ReflectionProperty pname, int32_t *params)
{
*params = 0;
if(pname == ReflectionProperty::ActiveResources)
{
switch(programInterface)
{
case ReflectionInterface::Input: *params = program->getNumLiveAttributes(); break;
case ReflectionInterface::Output:
// unsupported
*params = 0;
break;
case ReflectionInterface::Uniform: *params = program->getNumLiveUniformVariables(); break;
case ReflectionInterface::UniformBlock: *params = program->getNumLiveUniformBlocks(); break;
case ReflectionInterface::ShaderStorageBlock:
// unsupported
*params = 0;
break;
case ReflectionInterface::AtomicCounterBuffer:
// unsupported
*params = 0;
break;
}
}
else
{
RDCERR("Unsupported reflection property %d", pname);
}
}
void glslangGetProgramResourceiv(glslang::TProgram *program, ReflectionInterface programInterface,
uint32_t index, const std::vector<ReflectionProperty> &props,
int32_t bufSize, int32_t *length, int32_t *params)
{
if(programInterface == ReflectionInterface::Output ||
programInterface == ReflectionInterface::ShaderStorageBlock ||
programInterface == ReflectionInterface::AtomicCounterBuffer)
{
RDCWARN("unsupported program interface");
}
// all of our properties are single-element values, so we just loop up to buffer size or number of
// properties, whichever comes first.
for(size_t i = 0; i < RDCMIN((size_t)bufSize, props.size()); i++)
{
switch(props[i])
{
case ReflectionProperty::ActiveResources:
RDCERR("Unhandled reflection property ActiveResources");
params[i] = 0;
break;
case ReflectionProperty::BufferBinding:
RDCASSERT(programInterface == ReflectionInterface::UniformBlock);
params[i] = program->getUniformBlockBinding(index);
break;
case ReflectionProperty::TopLevelArrayStride:
// TODO glslang doesn't give us this
params[i] = 16;
break;
case ReflectionProperty::BlockIndex:
RDCASSERT(programInterface == ReflectionInterface::Uniform);
params[i] = program->getUniformBlockIndex(index);
break;
case ReflectionProperty::ArraySize:
if(programInterface == ReflectionInterface::Uniform)
params[i] = program->getUniformArraySize(index);
else if(programInterface == ReflectionInterface::Input)
// TODO assuming all inputs are non-arrayed
params[i] = 1;
else
RDCERR("Unsupported interface for ArraySize query");
break;
case ReflectionProperty::IsRowMajor:
// TODO glslang doesn't expose this, assume column major.
params[i] = 0;
break;
case ReflectionProperty::NumActiveVariables:
// TODO glslang doesn't give us this
params[i] = 1;
break;
case ReflectionProperty::BufferDataSize:
RDCASSERT(programInterface == ReflectionInterface::UniformBlock);
params[i] = program->getUniformBlockSize(index);
break;
case ReflectionProperty::NameLength:
// The name length includes a terminating null character.
if(programInterface == ReflectionInterface::Uniform)
params[i] = (int32_t)strlen(program->getUniformName(index)) + 1;
else if(programInterface == ReflectionInterface::UniformBlock)
params[i] = (int32_t)strlen(program->getUniformBlockName(index)) + 1;
else if(programInterface == ReflectionInterface::Input)
params[i] = (int32_t)strlen(program->getAttributeName(index)) + 1;
else
RDCERR("Unsupported interface for NameLEngth query");
break;
case ReflectionProperty::Type:
if(programInterface == ReflectionInterface::Uniform)
params[i] = program->getUniformType(index);
else if(programInterface == ReflectionInterface::Input)
params[i] = program->getAttributeType(index);
else
RDCERR("Unsupported interface for Type query");
break;
case ReflectionProperty::LocationComponent:
// TODO glslang doesn't give us this information
params[i] = 0;
break;
case ReflectionProperty::ReferencedByVertexShader:
case ReflectionProperty::ReferencedByTessControlShader:
case ReflectionProperty::ReferencedByTessEvaluationShader:
case ReflectionProperty::ReferencedByGeometryShader:
case ReflectionProperty::ReferencedByFragmentShader:
case ReflectionProperty::ReferencedByComputeShader:
// TODO glslang doesn't give us this information
params[i] = 1;
break;
case ReflectionProperty::AtomicCounterBufferIndex:
RDCERR("Atomic counters not supported");
break;
case ReflectionProperty::Offset:
RDCASSERT(programInterface == ReflectionInterface::Uniform);
params[i] = program->getUniformBufferOffset(index);
break;
case ReflectionProperty::MatrixStride:
RDCASSERT(programInterface == ReflectionInterface::Uniform);
// TODO glslang doesn't give us this information
params[i] = 64;
break;
case ReflectionProperty::ArrayStride:
RDCASSERT(programInterface == ReflectionInterface::Uniform);
// TODO glslang doesn't give us this information
params[i] = 64;
break;
case ReflectionProperty::Location:
// have to query the actual implementation, which is handled elsewhere. We return either -1
// for uniforms that don't have a location (i.e. are in a block) or 0 for bare uniforms
if(programInterface == ReflectionInterface::Uniform)
params[i] = program->getUniformBlockIndex(index) >= 0 ? -1 : 0;
else if(programInterface == ReflectionInterface::Input)
params[i] = index;
break;
}
}
}
const char *glslangGetProgramResourceName(glslang::TProgram *program,
ReflectionInterface programInterface, uint32_t index)
{
const char *fetchedName = "";
switch(programInterface)
{
case ReflectionInterface::Input: fetchedName = program->getAttributeName(index); break;
case ReflectionInterface::Output: RDCWARN("Output attributes unsupported"); break;
case ReflectionInterface::Uniform: fetchedName = program->getUniformName(index); break;
case ReflectionInterface::UniformBlock:
fetchedName = program->getUniformBlockName(index);
break;
case ReflectionInterface::ShaderStorageBlock:
RDCWARN("shader storage blocks unsupported");
break;
case ReflectionInterface::AtomicCounterBuffer:
RDCWARN("atomic counter buffers unsupported");
break;
}
return fetchedName;
}
<commit_msg>Keep going after finding a specialization constant match<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2018 Baldur Karlsson
*
* 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 "spirv_common.h"
#include "common/common.h"
#undef min
#undef max
#include "3rdparty/glslang/glslang/Public/ShaderLang.h"
static bool inited = false;
std::vector<glslang::TShader *> allocatedShaders;
std::vector<glslang::TProgram *> allocatedPrograms;
void InitSPIRVCompiler()
{
if(!inited)
{
glslang::InitializeProcess();
inited = true;
}
}
void ShutdownSPIRVCompiler()
{
if(inited)
{
// programs must be deleted before shaders
for(glslang::TProgram *program : allocatedPrograms)
delete program;
for(glslang::TShader *shader : allocatedShaders)
delete shader;
allocatedPrograms.clear();
allocatedShaders.clear();
glslang::FinalizeProcess();
}
}
void SPIRVFillCBufferVariables(const rdcarray<ShaderConstant> &invars,
vector<ShaderVariable> &outvars, const bytebuf &data,
size_t baseOffset)
{
for(size_t v = 0; v < invars.size(); v++)
{
std::string basename = invars[v].name;
uint32_t rows = invars[v].type.descriptor.rows;
uint32_t cols = invars[v].type.descriptor.columns;
uint32_t elems = RDCMAX(1U, invars[v].type.descriptor.elements);
bool rowMajor = invars[v].type.descriptor.rowMajorStorage != 0;
bool isArray = elems > 1;
size_t dataOffset =
baseOffset + invars[v].reg.vec * sizeof(float) * 4 + invars[v].reg.comp * sizeof(float);
if(!invars[v].type.members.empty() || (rows == 0 && cols == 0))
{
ShaderVariable var;
var.name = basename;
var.rows = var.columns = 0;
var.type = VarType::Float;
var.rowMajor = rowMajor;
vector<ShaderVariable> varmembers;
if(isArray)
{
for(uint32_t i = 0; i < elems; i++)
{
ShaderVariable vr;
vr.name = StringFormat::Fmt("%s[%u]", basename.c_str(), i);
vr.rows = vr.columns = 0;
vr.type = VarType::Float;
vr.rowMajor = rowMajor;
vector<ShaderVariable> mems;
SPIRVFillCBufferVariables(invars[v].type.members, mems, data, dataOffset);
dataOffset += invars[v].type.descriptor.arrayByteStride;
vr.isStruct = true;
vr.members = mems;
varmembers.push_back(vr);
}
var.isStruct = false;
}
else
{
var.isStruct = true;
SPIRVFillCBufferVariables(invars[v].type.members, varmembers, data, dataOffset);
}
{
var.members = varmembers;
outvars.push_back(var);
}
continue;
}
size_t outIdx = outvars.size();
outvars.resize(outvars.size() + 1);
{
outvars[outIdx].name = basename;
outvars[outIdx].rows = 1;
outvars[outIdx].type = invars[v].type.descriptor.type;
outvars[outIdx].isStruct = false;
outvars[outIdx].columns = cols;
outvars[outIdx].rowMajor = rowMajor;
size_t elemByteSize = 4;
if(outvars[outIdx].type == VarType::Double)
elemByteSize = 8;
ShaderVariable &var = outvars[outIdx];
if(!isArray)
{
outvars[outIdx].rows = rows;
if(dataOffset < data.size())
{
const byte *d = &data[dataOffset];
RDCASSERT(rows <= 4 && rows * cols <= 16, rows, cols);
if(!rowMajor)
{
uint32_t tmp[16] = {0};
for(uint32_t c = 0; c < cols; c++)
{
size_t srcoffs = 4 * elemByteSize * c;
size_t dstoffs = rows * elemByteSize * c;
memcpy((byte *)(tmp) + dstoffs, d + srcoffs,
RDCMIN(data.size() - dataOffset + srcoffs, elemByteSize * rows));
}
// transpose
for(size_t r = 0; r < rows; r++)
for(size_t c = 0; c < cols; c++)
outvars[outIdx].value.uv[r * cols + c] = tmp[c * rows + r];
}
else
{
for(uint32_t r = 0; r < rows; r++)
{
size_t srcoffs = 4 * elemByteSize * r;
size_t dstoffs = cols * elemByteSize * r;
memcpy((byte *)(&outvars[outIdx].value.uv[0]) + dstoffs, d + srcoffs,
RDCMIN(data.size() - dataOffset + srcoffs, elemByteSize * cols));
}
}
}
}
else
{
var.name = outvars[outIdx].name;
var.rows = 0;
var.columns = 0;
bool isMatrix = rows > 1 && cols > 1;
vector<ShaderVariable> varmembers;
varmembers.resize(elems);
std::string base = outvars[outIdx].name;
// primary is the 'major' direction
// so we copy secondaryDim number of primaryDim-sized elements
uint32_t primaryDim = cols;
uint32_t secondaryDim = rows;
if(isMatrix && rowMajor)
{
primaryDim = rows;
secondaryDim = cols;
}
for(uint32_t e = 0; e < elems; e++)
{
varmembers[e].name = StringFormat::Fmt("%s[%u]", base.c_str(), e);
varmembers[e].rows = rows;
varmembers[e].type = invars[v].type.descriptor.type;
varmembers[e].isStruct = false;
varmembers[e].columns = cols;
varmembers[e].rowMajor = rowMajor;
size_t rowDataOffset = dataOffset;
dataOffset += invars[v].type.descriptor.arrayByteStride;
if(rowDataOffset < data.size())
{
const byte *d = &data[rowDataOffset];
// each primary element (row or column) is stored in a float4.
// we copy some padding here, but that will come out in the wash
// when we transpose
for(uint32_t s = 0; s < secondaryDim; s++)
{
uint32_t matStride = primaryDim;
if(matStride == 3)
matStride = 4;
memcpy(&(varmembers[e].value.uv[primaryDim * s]), d + matStride * elemByteSize * s,
RDCMIN(data.size() - rowDataOffset, elemByteSize * primaryDim));
}
if(!rowMajor)
{
ShaderVariable tmp = varmembers[e];
// transpose
for(size_t ri = 0; ri < rows; ri++)
for(size_t ci = 0; ci < cols; ci++)
varmembers[e].value.uv[ri * cols + ci] = tmp.value.uv[ci * rows + ri];
}
}
}
{
var.isStruct = false;
var.members = varmembers;
}
}
}
}
}
void FillSpecConstantVariables(const rdcarray<ShaderConstant> &invars,
std::vector<ShaderVariable> &outvars,
const std::vector<SpecConstant> &specInfo)
{
outvars.resize(invars.size());
for(size_t v = 0; v < invars.size(); v++)
{
outvars[v].rows = invars[v].type.descriptor.rows;
outvars[v].columns = invars[v].type.descriptor.columns;
outvars[v].isStruct = !invars[v].type.members.empty();
RDCASSERT(!outvars[v].isStruct);
outvars[v].name = invars[v].name;
outvars[v].type = invars[v].type.descriptor.type;
outvars[v].value.uv[0] = (invars[v].defaultValue & 0xFFFFFFFF);
outvars[v].value.uv[1] = ((invars[v].defaultValue >> 32) & 0xFFFFFFFF);
}
// find any actual values specified
for(size_t i = 0; i < specInfo.size(); i++)
{
for(size_t v = 0; v < invars.size(); v++)
{
if(specInfo[i].specID == invars[v].reg.vec)
{
memcpy(outvars[v].value.uv, specInfo[i].data.data(),
RDCMIN(specInfo[i].data.size(), sizeof(outvars[v].value.uv)));
}
}
}
}
void glslangGetProgramInterfaceiv(glslang::TProgram *program, ReflectionInterface programInterface,
ReflectionProperty pname, int32_t *params)
{
*params = 0;
if(pname == ReflectionProperty::ActiveResources)
{
switch(programInterface)
{
case ReflectionInterface::Input: *params = program->getNumLiveAttributes(); break;
case ReflectionInterface::Output:
// unsupported
*params = 0;
break;
case ReflectionInterface::Uniform: *params = program->getNumLiveUniformVariables(); break;
case ReflectionInterface::UniformBlock: *params = program->getNumLiveUniformBlocks(); break;
case ReflectionInterface::ShaderStorageBlock:
// unsupported
*params = 0;
break;
case ReflectionInterface::AtomicCounterBuffer:
// unsupported
*params = 0;
break;
}
}
else
{
RDCERR("Unsupported reflection property %d", pname);
}
}
void glslangGetProgramResourceiv(glslang::TProgram *program, ReflectionInterface programInterface,
uint32_t index, const std::vector<ReflectionProperty> &props,
int32_t bufSize, int32_t *length, int32_t *params)
{
if(programInterface == ReflectionInterface::Output ||
programInterface == ReflectionInterface::ShaderStorageBlock ||
programInterface == ReflectionInterface::AtomicCounterBuffer)
{
RDCWARN("unsupported program interface");
}
// all of our properties are single-element values, so we just loop up to buffer size or number of
// properties, whichever comes first.
for(size_t i = 0; i < RDCMIN((size_t)bufSize, props.size()); i++)
{
switch(props[i])
{
case ReflectionProperty::ActiveResources:
RDCERR("Unhandled reflection property ActiveResources");
params[i] = 0;
break;
case ReflectionProperty::BufferBinding:
RDCASSERT(programInterface == ReflectionInterface::UniformBlock);
params[i] = program->getUniformBlockBinding(index);
break;
case ReflectionProperty::TopLevelArrayStride:
// TODO glslang doesn't give us this
params[i] = 16;
break;
case ReflectionProperty::BlockIndex:
RDCASSERT(programInterface == ReflectionInterface::Uniform);
params[i] = program->getUniformBlockIndex(index);
break;
case ReflectionProperty::ArraySize:
if(programInterface == ReflectionInterface::Uniform)
params[i] = program->getUniformArraySize(index);
else if(programInterface == ReflectionInterface::Input)
// TODO assuming all inputs are non-arrayed
params[i] = 1;
else
RDCERR("Unsupported interface for ArraySize query");
break;
case ReflectionProperty::IsRowMajor:
// TODO glslang doesn't expose this, assume column major.
params[i] = 0;
break;
case ReflectionProperty::NumActiveVariables:
// TODO glslang doesn't give us this
params[i] = 1;
break;
case ReflectionProperty::BufferDataSize:
RDCASSERT(programInterface == ReflectionInterface::UniformBlock);
params[i] = program->getUniformBlockSize(index);
break;
case ReflectionProperty::NameLength:
// The name length includes a terminating null character.
if(programInterface == ReflectionInterface::Uniform)
params[i] = (int32_t)strlen(program->getUniformName(index)) + 1;
else if(programInterface == ReflectionInterface::UniformBlock)
params[i] = (int32_t)strlen(program->getUniformBlockName(index)) + 1;
else if(programInterface == ReflectionInterface::Input)
params[i] = (int32_t)strlen(program->getAttributeName(index)) + 1;
else
RDCERR("Unsupported interface for NameLEngth query");
break;
case ReflectionProperty::Type:
if(programInterface == ReflectionInterface::Uniform)
params[i] = program->getUniformType(index);
else if(programInterface == ReflectionInterface::Input)
params[i] = program->getAttributeType(index);
else
RDCERR("Unsupported interface for Type query");
break;
case ReflectionProperty::LocationComponent:
// TODO glslang doesn't give us this information
params[i] = 0;
break;
case ReflectionProperty::ReferencedByVertexShader:
case ReflectionProperty::ReferencedByTessControlShader:
case ReflectionProperty::ReferencedByTessEvaluationShader:
case ReflectionProperty::ReferencedByGeometryShader:
case ReflectionProperty::ReferencedByFragmentShader:
case ReflectionProperty::ReferencedByComputeShader:
// TODO glslang doesn't give us this information
params[i] = 1;
break;
case ReflectionProperty::AtomicCounterBufferIndex:
RDCERR("Atomic counters not supported");
break;
case ReflectionProperty::Offset:
RDCASSERT(programInterface == ReflectionInterface::Uniform);
params[i] = program->getUniformBufferOffset(index);
break;
case ReflectionProperty::MatrixStride:
RDCASSERT(programInterface == ReflectionInterface::Uniform);
// TODO glslang doesn't give us this information
params[i] = 64;
break;
case ReflectionProperty::ArrayStride:
RDCASSERT(programInterface == ReflectionInterface::Uniform);
// TODO glslang doesn't give us this information
params[i] = 64;
break;
case ReflectionProperty::Location:
// have to query the actual implementation, which is handled elsewhere. We return either -1
// for uniforms that don't have a location (i.e. are in a block) or 0 for bare uniforms
if(programInterface == ReflectionInterface::Uniform)
params[i] = program->getUniformBlockIndex(index) >= 0 ? -1 : 0;
else if(programInterface == ReflectionInterface::Input)
params[i] = index;
break;
}
}
}
const char *glslangGetProgramResourceName(glslang::TProgram *program,
ReflectionInterface programInterface, uint32_t index)
{
const char *fetchedName = "";
switch(programInterface)
{
case ReflectionInterface::Input: fetchedName = program->getAttributeName(index); break;
case ReflectionInterface::Output: RDCWARN("Output attributes unsupported"); break;
case ReflectionInterface::Uniform: fetchedName = program->getUniformName(index); break;
case ReflectionInterface::UniformBlock:
fetchedName = program->getUniformBlockName(index);
break;
case ReflectionInterface::ShaderStorageBlock:
RDCWARN("shader storage blocks unsupported");
break;
case ReflectionInterface::AtomicCounterBuffer:
RDCWARN("atomic counter buffers unsupported");
break;
}
return fetchedName;
}
<|endoftext|>
|
<commit_before>#include <boost/test/unit_test.hpp>
#include "functions/all_simplifications.hh"
#include "functions/complex.hh"
#include "functions/operators.hh"
#include "functions/streaming.hh"
BOOST_AUTO_TEST_CASE(complex_test) {
using namespace manifolds;
static_assert(ComplexOutputType<decltype(x)>::value == NeverComplex, "");
BOOST_CHECK_EQUAL(Simplify(Real()(x)), x);
BOOST_CHECK_EQUAL(Simplify(Imag()(x)), zero);
BOOST_CHECK_EQUAL(Phase(), Arg());
auto r_phase = Simplify(Phase()(x));
BOOST_CHECK_EQUAL(r_phase(3), 0);
BOOST_CHECK_EQUAL(r_phase(-3), -M_PI);
BOOST_CHECK_EQUAL(Simplify(Real()(I)), zero);
BOOST_CHECK_EQUAL(Simplify(Imag()(I)), GetIPolynomial<1>());
BOOST_CHECK_EQUAL(Simplify(Norm()(I)), GetIPolynomial<1>());
BOOST_CHECK_EQUAL(Simplify(Norm()(x)), x * x);
BOOST_CHECK_EQUAL(Simplify(Conjugate()(I)), -I);
BOOST_CHECK_EQUAL(Simplify(Conjugate()(x)), x);
BOOST_CHECK_EQUAL(Simplify(I(x)), I);
BOOST_CHECK_EQUAL(Simplify(GetIPolynomial<1, 1, 1, 1, 1, 1>()(I)),
GetIPolynomial<1>() + I);
BOOST_CHECK_EQUAL(Simplify(GetIPolynomial<0, 0, 1>()(I)),
GetIPolynomial<-1>());
BOOST_CHECK_EQUAL(Simplify(Real()(GetIPolynomial<1>() * I + x)), x);
BOOST_CHECK_EQUAL(Simplify(Imag()(GetIPolynomial<1>() * I + x)), GetIPolynomial<1>());
BOOST_CHECK_EQUAL(Simplify(Real()((I + Sin()(x)) * (I + Cos()(x)))),
(Sin()*Cos())(x) - GetIPolynomial<1>());
}
<commit_msg>Added two more tests<commit_after>#include <boost/test/unit_test.hpp>
#include "functions/all_simplifications.hh"
#include "functions/complex.hh"
#include "functions/operators.hh"
#include "functions/streaming.hh"
BOOST_AUTO_TEST_CASE(complex_test) {
using namespace manifolds;
static_assert(ComplexOutputType<decltype(x)>::value == NeverComplex, "");
BOOST_CHECK_EQUAL(Simplify(Real()(x)), x);
BOOST_CHECK_EQUAL(Simplify(Imag()(x)), zero);
BOOST_CHECK_EQUAL(Phase(), Arg());
auto r_phase = Simplify(Phase()(x));
BOOST_CHECK_EQUAL(r_phase(3), 0);
BOOST_CHECK_EQUAL(r_phase(-3), -M_PI);
BOOST_CHECK_EQUAL(Simplify(Real()(I)), zero);
BOOST_CHECK_EQUAL(Simplify(Imag()(I)), GetIPolynomial<1>());
BOOST_CHECK_EQUAL(Simplify(Norm()(I)), GetIPolynomial<1>());
BOOST_CHECK_EQUAL(Simplify(Norm()(x)), x * x);
BOOST_CHECK_EQUAL(Simplify(Conjugate()(I)), -I);
BOOST_CHECK_EQUAL(Simplify(Conjugate()(x)), x);
BOOST_CHECK_EQUAL(Simplify(I(x)), I);
BOOST_CHECK_EQUAL(Simplify(GetIPolynomial<1, 1, 1, 1, 1, 1>()(I)),
GetIPolynomial<1>() + I);
BOOST_CHECK_EQUAL(Simplify(GetIPolynomial<0, 0, 1>()(I)),
GetIPolynomial<-1>());
BOOST_CHECK_EQUAL(Simplify(Real()(GetIPolynomial<1>() * I + x)), x);
BOOST_CHECK_EQUAL(Simplify(Imag()(GetIPolynomial<1>() * I + x)), GetIPolynomial<1>());
BOOST_CHECK_EQUAL(Simplify(Real()((I + Sin()(x)) * (I + Cos()(x)))),
(Sin()*Cos())(x) - GetIPolynomial<1>());
BOOST_CHECK_EQUAL(Simplify(GetIPolynomial<1,2,3,4,5,6,7>()(Sign())),
(GetIPolynomial<16,12>()(Sign())));
BOOST_CHECK_EQUAL(Simplify(GetPolynomial(1,2,3,4,5,6,7)(Sign())),
GetPolynomial(16,12)(Sign()));
}
<|endoftext|>
|
<commit_before><commit_msg>updated testing for utilities<commit_after><|endoftext|>
|
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/scheduler/renderer_scheduler.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop_proxy.h"
#include "content/public/common/content_switches.h"
#include "content/renderer/scheduler/null_renderer_scheduler.h"
#include "content/renderer/scheduler/renderer_scheduler_impl.h"
namespace content {
RendererScheduler::RendererScheduler() {
}
RendererScheduler::~RendererScheduler() {
}
// static
scoped_ptr<RendererScheduler> RendererScheduler::Create() {
CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kDisableBlinkScheduler)) {
return make_scoped_ptr(new NullRendererScheduler());
} else {
return make_scoped_ptr(
new RendererSchedulerImpl(base::MessageLoopProxy::current()));
}
}
} // namespace content
<commit_msg>Revert "content: Enable the RendererScheduler by default."<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/scheduler/renderer_scheduler.h"
#include "content/renderer/scheduler/null_renderer_scheduler.h"
namespace content {
RendererScheduler::RendererScheduler() {
}
RendererScheduler::~RendererScheduler() {
}
// static
scoped_ptr<RendererScheduler> RendererScheduler::Create() {
// TODO(rmcilroy): Use the RendererSchedulerImpl when the scheduler is enabled
return make_scoped_ptr(new NullRendererScheduler());
}
} // namespace content
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/function.h>
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/eval/interpreted_function.h>
#include <vespa/eval/eval/simple_tensor_engine.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
using namespace vespalib::eval;
using vespalib::BenchmarkTimer;
using vespalib::tensor::DefaultTensorEngine;
double budget = 5.00;
//-----------------------------------------------------------------------------
const char *function_str = "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w";
double gcc_function(double p, double o, double q, double f, double w) {
return (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w;
}
//-----------------------------------------------------------------------------
const char *big_function_str = "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
"(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
"(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
"(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w";
double big_gcc_function(double p, double o, double q, double f, double w) {
return (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w;
}
//-----------------------------------------------------------------------------
struct Fixture {
std::shared_ptr<Function const> function;
InterpretedFunction interpreted_simple;
InterpretedFunction interpreted;
CompiledFunction separate;
CompiledFunction array;
CompiledFunction lazy;
Fixture(const vespalib::string &expr)
: function(Function::parse(expr)),
interpreted_simple(SimpleTensorEngine::ref(), *function, NodeTypes()),
interpreted(DefaultTensorEngine::ref(), *function,
NodeTypes(*function, std::vector<ValueType>(function->num_params(), ValueType::double_type()))),
separate(*function, PassParams::SEPARATE),
array(*function, PassParams::ARRAY),
lazy(*function, PassParams::LAZY) {}
};
//-----------------------------------------------------------------------------
Fixture small(function_str);
Fixture big(big_function_str);
std::vector<double> test_params = {1.0, 2.0, 3.0, 4.0, 5.0};
//-----------------------------------------------------------------------------
double empty_function_5(double, double, double, double, double) { return 0.0; }
double estimate_cost_us(const std::vector<double> ¶ms, CompiledFunction::expand<5>::type function) {
CompiledFunction::expand<5>::type empty = empty_function_5;
auto actual = [&](){function(params[0], params[1], params[2], params[3], params[4]);};
auto baseline = [&](){empty(params[0], params[1], params[2], params[3], params[4]);};
return BenchmarkTimer::benchmark(actual, baseline, budget) * 1000.0 * 1000.0;
}
TEST("measure small function eval/jit/gcc speed") {
Fixture &fixture = small;
CompiledFunction::expand<5>::type fun = gcc_function;
EXPECT_EQUAL(fixture.separate.get_function<5>()(1,2,3,4,5), fun(1,2,3,4,5));
EXPECT_EQUAL(fixture.separate.get_function<5>()(5,4,3,2,1), fun(5,4,3,2,1));
double interpret_simple_time = fixture.interpreted_simple.estimate_cost_us(test_params, budget);
fprintf(stderr, "interpret (simple): %g us\n", interpret_simple_time);
double interpret_time = fixture.interpreted.estimate_cost_us(test_params, budget);
fprintf(stderr, "interpret: %g us\n", interpret_time);
double jit_time = estimate_cost_us(test_params, fixture.separate.get_function<5>());
fprintf(stderr, "jit compiled: %g us\n", jit_time);
double gcc_time = estimate_cost_us(test_params, fun);
fprintf(stderr, "gcc compiled: %g us\n", gcc_time);
double default_vs_simple_speed = (1.0/interpret_time)/(1.0/interpret_simple_time);
double jit_vs_interpret_speed = (1.0/jit_time)/(1.0/interpret_time);
double gcc_vs_jit_speed = (1.0/gcc_time)/(1.0/jit_time);
fprintf(stderr, "default typed vs simple untyped interpret speed: %g\n", default_vs_simple_speed);
fprintf(stderr, "jit speed compared to interpret: %g\n", jit_vs_interpret_speed);
fprintf(stderr, "gcc speed compared to jit: %g\n", gcc_vs_jit_speed);
double jit_time_separate = fixture.separate.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (separate) us\n", jit_time_separate);
double jit_time_array = fixture.array.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (array) us\n", jit_time_array);
double jit_time_lazy = fixture.lazy.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (lazy) us\n", jit_time_lazy);
double separate_vs_array_speed = (1.0/jit_time_separate)/(1.0/jit_time_array);
double array_vs_lazy_speed = (1.0/jit_time_array)/(1.0/jit_time_lazy);
fprintf(stderr, "seperate params speed compared to array params: %g\n", separate_vs_array_speed);
fprintf(stderr, "array params speed compared to lazy params: %g\n", array_vs_lazy_speed);
}
TEST("measure big function eval/jit/gcc speed") {
Fixture &fixture = big;
CompiledFunction::expand<5>::type fun = big_gcc_function;
EXPECT_EQUAL(fixture.separate.get_function<5>()(1,2,3,4,5), fun(1,2,3,4,5));
EXPECT_EQUAL(fixture.separate.get_function<5>()(5,4,3,2,1), fun(5,4,3,2,1));
double interpret_simple_time = fixture.interpreted_simple.estimate_cost_us(test_params, budget);
fprintf(stderr, "interpret (simple): %g us\n", interpret_simple_time);
double interpret_time = fixture.interpreted.estimate_cost_us(test_params, budget);
fprintf(stderr, "interpret: %g us\n", interpret_time);
double jit_time = estimate_cost_us(test_params, fixture.separate.get_function<5>());
fprintf(stderr, "jit compiled: %g us\n", jit_time);
double gcc_time = estimate_cost_us(test_params, fun);
fprintf(stderr, "gcc compiled: %g us\n", gcc_time);
double default_vs_simple_speed = (1.0/interpret_time)/(1.0/interpret_simple_time);
double jit_vs_interpret_speed = (1.0/jit_time)/(1.0/interpret_time);
double gcc_vs_jit_speed = (1.0/gcc_time)/(1.0/jit_time);
fprintf(stderr, "default typed vs simple untyped interpret speed: %g\n", default_vs_simple_speed);
fprintf(stderr, "jit speed compared to interpret: %g\n", jit_vs_interpret_speed);
fprintf(stderr, "gcc speed compared to jit: %g\n", gcc_vs_jit_speed);
double jit_time_separate = fixture.separate.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (separate) us\n", jit_time_separate);
double jit_time_array = fixture.array.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (array) us\n", jit_time_array);
double jit_time_lazy = fixture.lazy.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (lazy) us\n", jit_time_lazy);
double separate_vs_array_speed = (1.0/jit_time_separate)/(1.0/jit_time_array);
double array_vs_lazy_speed = (1.0/jit_time_array)/(1.0/jit_time_lazy);
fprintf(stderr, "seperate params speed compared to array params: %g\n", separate_vs_array_speed);
fprintf(stderr, "array params speed compared to lazy params: %g\n", array_vs_lazy_speed);
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>Revert unintended change<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/function.h>
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/eval/interpreted_function.h>
#include <vespa/eval/eval/simple_tensor_engine.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/tensor/default_tensor_engine.h>
using namespace vespalib::eval;
using vespalib::BenchmarkTimer;
using vespalib::tensor::DefaultTensorEngine;
double budget = 0.25;
//-----------------------------------------------------------------------------
const char *function_str = "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w";
double gcc_function(double p, double o, double q, double f, double w) {
return (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w;
}
//-----------------------------------------------------------------------------
const char *big_function_str = "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
"(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
"(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
"(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w";
double big_gcc_function(double p, double o, double q, double f, double w) {
return (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w;
}
//-----------------------------------------------------------------------------
struct Fixture {
std::shared_ptr<Function const> function;
InterpretedFunction interpreted_simple;
InterpretedFunction interpreted;
CompiledFunction separate;
CompiledFunction array;
CompiledFunction lazy;
Fixture(const vespalib::string &expr)
: function(Function::parse(expr)),
interpreted_simple(SimpleTensorEngine::ref(), *function, NodeTypes()),
interpreted(DefaultTensorEngine::ref(), *function,
NodeTypes(*function, std::vector<ValueType>(function->num_params(), ValueType::double_type()))),
separate(*function, PassParams::SEPARATE),
array(*function, PassParams::ARRAY),
lazy(*function, PassParams::LAZY) {}
};
//-----------------------------------------------------------------------------
Fixture small(function_str);
Fixture big(big_function_str);
std::vector<double> test_params = {1.0, 2.0, 3.0, 4.0, 5.0};
//-----------------------------------------------------------------------------
double empty_function_5(double, double, double, double, double) { return 0.0; }
double estimate_cost_us(const std::vector<double> ¶ms, CompiledFunction::expand<5>::type function) {
CompiledFunction::expand<5>::type empty = empty_function_5;
auto actual = [&](){function(params[0], params[1], params[2], params[3], params[4]);};
auto baseline = [&](){empty(params[0], params[1], params[2], params[3], params[4]);};
return BenchmarkTimer::benchmark(actual, baseline, budget) * 1000.0 * 1000.0;
}
TEST("measure small function eval/jit/gcc speed") {
Fixture &fixture = small;
CompiledFunction::expand<5>::type fun = gcc_function;
EXPECT_EQUAL(fixture.separate.get_function<5>()(1,2,3,4,5), fun(1,2,3,4,5));
EXPECT_EQUAL(fixture.separate.get_function<5>()(5,4,3,2,1), fun(5,4,3,2,1));
double interpret_simple_time = fixture.interpreted_simple.estimate_cost_us(test_params, budget);
fprintf(stderr, "interpret (simple): %g us\n", interpret_simple_time);
double interpret_time = fixture.interpreted.estimate_cost_us(test_params, budget);
fprintf(stderr, "interpret: %g us\n", interpret_time);
double jit_time = estimate_cost_us(test_params, fixture.separate.get_function<5>());
fprintf(stderr, "jit compiled: %g us\n", jit_time);
double gcc_time = estimate_cost_us(test_params, fun);
fprintf(stderr, "gcc compiled: %g us\n", gcc_time);
double default_vs_simple_speed = (1.0/interpret_time)/(1.0/interpret_simple_time);
double jit_vs_interpret_speed = (1.0/jit_time)/(1.0/interpret_time);
double gcc_vs_jit_speed = (1.0/gcc_time)/(1.0/jit_time);
fprintf(stderr, "default typed vs simple untyped interpret speed: %g\n", default_vs_simple_speed);
fprintf(stderr, "jit speed compared to interpret: %g\n", jit_vs_interpret_speed);
fprintf(stderr, "gcc speed compared to jit: %g\n", gcc_vs_jit_speed);
double jit_time_separate = fixture.separate.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (separate) us\n", jit_time_separate);
double jit_time_array = fixture.array.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (array) us\n", jit_time_array);
double jit_time_lazy = fixture.lazy.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (lazy) us\n", jit_time_lazy);
double separate_vs_array_speed = (1.0/jit_time_separate)/(1.0/jit_time_array);
double array_vs_lazy_speed = (1.0/jit_time_array)/(1.0/jit_time_lazy);
fprintf(stderr, "seperate params speed compared to array params: %g\n", separate_vs_array_speed);
fprintf(stderr, "array params speed compared to lazy params: %g\n", array_vs_lazy_speed);
}
TEST("measure big function eval/jit/gcc speed") {
Fixture &fixture = big;
CompiledFunction::expand<5>::type fun = big_gcc_function;
EXPECT_EQUAL(fixture.separate.get_function<5>()(1,2,3,4,5), fun(1,2,3,4,5));
EXPECT_EQUAL(fixture.separate.get_function<5>()(5,4,3,2,1), fun(5,4,3,2,1));
double interpret_simple_time = fixture.interpreted_simple.estimate_cost_us(test_params, budget);
fprintf(stderr, "interpret (simple): %g us\n", interpret_simple_time);
double interpret_time = fixture.interpreted.estimate_cost_us(test_params, budget);
fprintf(stderr, "interpret: %g us\n", interpret_time);
double jit_time = estimate_cost_us(test_params, fixture.separate.get_function<5>());
fprintf(stderr, "jit compiled: %g us\n", jit_time);
double gcc_time = estimate_cost_us(test_params, fun);
fprintf(stderr, "gcc compiled: %g us\n", gcc_time);
double default_vs_simple_speed = (1.0/interpret_time)/(1.0/interpret_simple_time);
double jit_vs_interpret_speed = (1.0/jit_time)/(1.0/interpret_time);
double gcc_vs_jit_speed = (1.0/gcc_time)/(1.0/jit_time);
fprintf(stderr, "default typed vs simple untyped interpret speed: %g\n", default_vs_simple_speed);
fprintf(stderr, "jit speed compared to interpret: %g\n", jit_vs_interpret_speed);
fprintf(stderr, "gcc speed compared to jit: %g\n", gcc_vs_jit_speed);
double jit_time_separate = fixture.separate.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (separate) us\n", jit_time_separate);
double jit_time_array = fixture.array.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (array) us\n", jit_time_array);
double jit_time_lazy = fixture.lazy.estimate_cost_us(test_params, budget);
fprintf(stderr, "jit compiled: %g (lazy) us\n", jit_time_lazy);
double separate_vs_array_speed = (1.0/jit_time_separate)/(1.0/jit_time_array);
double array_vs_lazy_speed = (1.0/jit_time_array)/(1.0/jit_time_lazy);
fprintf(stderr, "seperate params speed compared to array params: %g\n", separate_vs_array_speed);
fprintf(stderr, "array params speed compared to lazy params: %g\n", array_vs_lazy_speed);
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 1998 Stephen Williams (steve@icarus.com)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined(WINNT)
#ident "$Id: eval.cc,v 1.6 1999/09/16 04:18:15 steve Exp $"
#endif
# include "PExpr.h"
# include "netlist.h"
verinum* PExpr::eval_const(const Design*, const string&) const
{
return 0;
}
verinum* PEBinary::eval_const(const Design*des, const string&path) const
{
verinum*l = left_->eval_const(des, path);
if (l == 0) return 0;
verinum*r = right_->eval_const(des, path);
if (r == 0) {
delete l;
return 0;
}
verinum*res;
switch (op_) {
case '-': {
long lv = l->as_long();
long rv = r->as_long();
res = new verinum(lv-rv, l->len());
break;
}
default:
delete l;
delete r;
return 0;
}
return res;
}
verinum* PEIdent::eval_const(const Design*des, const string&path) const
{
assert(msb_ == 0);
const NetExpr*expr = des->find_parameter(path, text_);
if (expr == 0) {
cerr << get_line() << ": unable to evaluate " << text_ <<
" in this context (" << path << ")." << endl;
return 0;
}
const NetEConst*eval = dynamic_cast<const NetEConst*>(expr);
assert(eval);
return new verinum(eval->value());
}
verinum* PENumber::eval_const(const Design*, const string&) const
{
return new verinum(value());
}
verinum* PETernary::eval_const(const Design*, const string&) const
{
assert(0);
}
/*
* $Log: eval.cc,v $
* Revision 1.6 1999/09/16 04:18:15 steve
* elaborate concatenation repeats.
*
* Revision 1.5 1999/08/06 04:05:28 steve
* Handle scope of parameters.
*
* Revision 1.4 1999/07/17 19:51:00 steve
* netlist support for ternary operator.
*
* Revision 1.3 1999/05/30 01:11:46 steve
* Exressions are trees that can duplicate, and not DAGS.
*
* Revision 1.2 1999/05/10 00:16:58 steve
* Parse and elaborate the concatenate operator
* in structural contexts, Replace vector<PExpr*>
* and list<PExpr*> with svector<PExpr*>, evaluate
* constant expressions with parameters, handle
* memories as lvalues.
*
* Parse task declarations, integer types.
*
* Revision 1.1 1998/11/03 23:28:58 steve
* Introduce verilog to CVS.
*
*/
<commit_msg> Remove spurious message.<commit_after>/*
* Copyright (c) 1998 Stephen Williams (steve@icarus.com)
*
* This source code is free software; you can redistribute it
* and/or modify it in source code form under the terms of the GNU
* General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#if !defined(WINNT)
#ident "$Id: eval.cc,v 1.7 1999/09/18 01:52:48 steve Exp $"
#endif
# include "PExpr.h"
# include "netlist.h"
verinum* PExpr::eval_const(const Design*, const string&) const
{
return 0;
}
verinum* PEBinary::eval_const(const Design*des, const string&path) const
{
verinum*l = left_->eval_const(des, path);
if (l == 0) return 0;
verinum*r = right_->eval_const(des, path);
if (r == 0) {
delete l;
return 0;
}
verinum*res;
switch (op_) {
case '-': {
long lv = l->as_long();
long rv = r->as_long();
res = new verinum(lv-rv, l->len());
break;
}
default:
delete l;
delete r;
return 0;
}
return res;
}
/*
* Evaluate an identifier as a constant expression. This is only
* possible if the identifier is that of a parameter.
*/
verinum* PEIdent::eval_const(const Design*des, const string&path) const
{
assert(msb_ == 0);
const NetExpr*expr = des->find_parameter(path, text_);
if (expr == 0)
return 0;
const NetEConst*eval = dynamic_cast<const NetEConst*>(expr);
assert(eval);
return new verinum(eval->value());
}
verinum* PENumber::eval_const(const Design*, const string&) const
{
return new verinum(value());
}
verinum* PETernary::eval_const(const Design*, const string&) const
{
assert(0);
}
/*
* $Log: eval.cc,v $
* Revision 1.7 1999/09/18 01:52:48 steve
* Remove spurious message.
*
* Revision 1.6 1999/09/16 04:18:15 steve
* elaborate concatenation repeats.
*
* Revision 1.5 1999/08/06 04:05:28 steve
* Handle scope of parameters.
*
* Revision 1.4 1999/07/17 19:51:00 steve
* netlist support for ternary operator.
*
* Revision 1.3 1999/05/30 01:11:46 steve
* Exressions are trees that can duplicate, and not DAGS.
*
* Revision 1.2 1999/05/10 00:16:58 steve
* Parse and elaborate the concatenate operator
* in structural contexts, Replace vector<PExpr*>
* and list<PExpr*> with svector<PExpr*>, evaluate
* constant expressions with parameters, handle
* memories as lvalues.
*
* Parse task declarations, integer types.
*
* Revision 1.1 1998/11/03 23:28:58 steve
* Introduce verilog to CVS.
*
*/
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2019, University of Edinburgh
// 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 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 <exotica_ilqr_solver/ilqr_solver.h>
REGISTER_MOTIONSOLVER_TYPE("ILQRSolver", exotica::ILQRSolver)
namespace exotica
{
void ILQRSolver::SpecifyProblem(PlanningProblemPtr pointer)
{
if (pointer->type() != "exotica::DynamicTimeIndexedShootingProblem")
{
ThrowNamed("This ILQRSolver can't solve problem of type '" << pointer->type() << "'!");
}
MotionSolver::SpecifyProblem(pointer);
prob_ = std::static_pointer_cast<DynamicTimeIndexedShootingProblem>(pointer);
dynamics_solver_ = prob_->GetScene()->GetDynamicsSolver();
}
void ILQRSolver::BackwardPass()
{
// constexpr double min_clamp_ = -1e10;
// constexpr double max_clamp_ = 1e10;
const int T = prob_->get_T();
const double dt = dynamics_solver_->get_dt();
const Eigen::MatrixXd& Qf = prob_->get_Qf();
const Eigen::MatrixXd R = dt * prob_->get_R();
const Eigen::MatrixXd& X_star = prob_->get_X_star();
// eq. 18
vk_gains_[T - 1] = Qf * dynamics_solver_->StateDelta(prob_->get_X(T - 1), X_star.col(T - 1));
// vk_gains_[T - 1] = vk_gains_[T - 1].unaryExpr([min_clamp_, max_clamp_](double x) -> double {
// return std::min(std::max(x, min_clamp_), max_clamp_);
// });
Eigen::MatrixXd Sk = Qf;
// Sk = Sk.unaryExpr([min_clamp_, max_clamp_](double x) -> double {
// return std::min(std::max(x, min_clamp_), max_clamp_);
// });
// vk_gains_[T - 1] = vk_gains_[T - 1].unaryExpr([min_clamp_, max_clamp_](double x) -> double {
// return std::min(std::max(x, min_clamp_), max_clamp_);
// });
for (int t = T - 2; t >= 0; t--)
{
Eigen::VectorXd x = prob_->get_X(t), u = prob_->get_U(t);
Eigen::MatrixXd Ak = dynamics_solver_->fx(x, u), Bk = dynamics_solver_->fu(x, u),
Q = dt * prob_->get_Q(t);
// eq. 13-16
Ak.noalias() = Ak * dt + Eigen::MatrixXd::Identity(Ak.rows(), Ak.cols());
Bk.noalias() = Bk * dt;
// this inverse is common for all factors
// TODO: use LLT
const Eigen::MatrixXd _inv =
(Eigen::MatrixXd::Identity(R.rows(), R.cols()) * parameters_.RegularizationRate + R + Bk.transpose() * Sk * Bk).inverse();
Kv_gains_[t] = _inv * Bk.transpose();
K_gains_[t] = _inv * Bk.transpose() * Sk * Ak;
Ku_gains_[t] = _inv * R;
Sk = Ak.transpose() * Sk * (Ak - Bk * K_gains_[t]) + Q;
vk_gains_[t] = ((Ak - Bk * K_gains_[t]).transpose() * vk_gains_[t + 1]) -
(K_gains_[t].transpose() * R * u) + (Q * x);
// fix for large values
// Sk = Sk.unaryExpr([min_clamp_, max_clamp_](double x) -> double {
// return std::min(std::max(x, min_clamp_), max_clamp_);
// });
// vk_gains_[t] = vk_gains_[t].unaryExpr([min_clamp_, max_clamp_](double x) -> double {
// return std::min(std::max(x, min_clamp_), max_clamp_);
// });
}
}
double ILQRSolver::ForwardPass(const double alpha, Eigen::MatrixXdRefConst ref_x, Eigen::MatrixXdRefConst ref_u)
{
double cost = 0;
const int T = prob_->get_T();
const Eigen::MatrixXd control_limits = dynamics_solver_->get_control_limits();
const double dt = dynamics_solver_->get_dt();
Eigen::VectorXd delta_uk(dynamics_solver_->get_num_controls()), u(dynamics_solver_->get_num_controls());
for (int t = 0; t < T - 1; ++t)
{
u = ref_u.col(t);
// eq. 12
delta_uk = -Ku_gains_[t] * u - Kv_gains_[t] * vk_gains_[t + 1] -
K_gains_[t] * dynamics_solver_->StateDelta(prob_->get_X(t), ref_x.col(t));
u.noalias() += alpha * delta_uk;
// clamp controls
u = u.cwiseMax(control_limits.col(0)).cwiseMin(control_limits.col(1));
prob_->Update(u, t);
cost += dt * (prob_->GetControlCost(t) + prob_->GetStateCost(t));
}
// add terminal cost
cost += prob_->GetStateCost(T - 1);
return cost;
}
void ILQRSolver::Solve(Eigen::MatrixXd& solution)
{
if (!prob_) ThrowNamed("Solver has not been initialized!");
Timer planning_timer, backward_pass_timer, line_search_timer;
const int T = prob_->get_T();
const int NU = prob_->get_num_controls();
const int NX = prob_->get_num_positions() + prob_->get_num_velocities();
const double dt = dynamics_solver_->get_dt();
prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);
prob_->PreUpdate();
double cost = 0;
for (int t = 0; t < T - 1; ++t)
{
prob_->Update(prob_->get_U(t), t);
cost += dt * (prob_->GetControlCost(t) + prob_->GetStateCost(t));
}
// add terminal cost
cost += prob_->GetStateCost(T - 1);
prob_->SetCostEvolution(0, cost);
// initialize Gain matrices
K_gains_.assign(T, Eigen::MatrixXd(NU, NX));
Ku_gains_.assign(T, Eigen::MatrixXd(NU, NU));
Kv_gains_.assign(T, Eigen::MatrixXd(NU, NX));
vk_gains_.assign(T, Eigen::MatrixXd(NX, 1));
// all of the below are not pointers, since we want to copy over
// solutions across iterations
Eigen::MatrixXd new_U = prob_->get_U();
solution.resize(T - 1, NU);
if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Running ILQR solver for max " << GetNumberOfMaxIterations() << " iterations");
double cost_prev = cost;
int last_best_iteration = 0;
Eigen::VectorXd alpha_space = Eigen::VectorXd::LinSpaced(11, 0.0, -3.0);
for (int ai = 0; ai < alpha_space.size(); ++ai)
{
alpha_space(ai) = std::pow(10.0, alpha_space(ai));
}
double time_taken_backward_pass = 0.0, time_taken_forward_pass = 0.0;
for (int iteration = 1; iteration <= GetNumberOfMaxIterations(); ++iteration)
{
// Check whether user interrupted (Ctrl+C)
if (Server::IsRos() && !ros::ok())
{
if (debug_) HIGHLIGHT("Solving cancelled by user");
prob_->termination_criterion = TerminationCriterion::UserDefined;
break;
}
// Backwards pass computes the gains
backward_pass_timer.Reset();
BackwardPass();
time_taken_backward_pass = backward_pass_timer.GetDuration();
// Forward pass to compute new control trajectory
line_search_timer.Reset();
// Make a copy to compare against
Eigen::MatrixXd ref_x = prob_->get_X(),
ref_u = prob_->get_U();
// Perform a backtracking line search to find the best rate
double best_alpha = 0;
for (int ai = 0; ai < alpha_space.size(); ++ai)
{
const double& alpha = alpha_space(ai);
double rollout_cost = ForwardPass(alpha, ref_x, ref_u);
if (rollout_cost < cost_prev && !std::isnan(rollout_cost))
{
cost = rollout_cost;
new_U = prob_->get_U();
best_alpha = alpha;
break;
}
}
// Finiteness checks
if (!new_U.allFinite() || !std::isfinite(cost))
{
prob_->termination_criterion = TerminationCriterion::Divergence;
WARNING_NAMED("ILQRSolver", "Diverged: Controls or cost are not finite.");
return;
}
time_taken_forward_pass = line_search_timer.GetDuration();
if (debug_)
{
HIGHLIGHT_NAMED("ILQRSolver", "Iteration " << iteration << std::setprecision(3) << ":\tBackward pass: " << time_taken_backward_pass << " s\tForward pass: " << time_taken_forward_pass << " s\tCost: " << cost << "\talpha: " << best_alpha);
}
//
// Stopping criteria checks
//
// Relative function tolerance
// (f_t-1 - f_t) <= functionTolerance * max(1, abs(f_t))
if ((cost_prev - cost) < parameters_.FunctionTolerance * std::max(1.0, std::abs(cost)))
{
// Function tolerance patience check
if (parameters_.FunctionTolerancePatience > 0)
{
if (iteration - last_best_iteration > parameters_.FunctionTolerancePatience)
{
if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Early stopping criterion reached (" << cost << " < " << cost_prev << "). Time: " << planning_timer.GetDuration());
prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
break;
}
}
else
{
if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Function tolerance reached (" << cost << " < " << cost_prev << "). Time: " << planning_timer.GetDuration());
prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
break;
}
}
else
{
// Reset function tolerance patience
last_best_iteration = iteration;
}
// If better than previous iteration, copy solutions for next iteration
if (cost < cost_prev)
{
cost_prev = cost;
// last_best_iteration = iteration;
best_ref_x_ = ref_x;
best_ref_u_ = ref_u;
}
// if (iteration - last_best_iteration > parameters_.FunctionTolerancePatience)
// {
// if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Early stopping criterion reached. Time: " << planning_timer.GetDuration());
// prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
// break;
// }
// if (last_cost - current_cost < parameters_.FunctionTolerance && last_cost - current_cost > 0)
// {
// if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Function tolerance reached. Time: " << planning_timer.GetDuration());
// prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
// break;
// }
if (debug_ && iteration == parameters_.MaxIterations)
{
HIGHLIGHT_NAMED("ILQRSolver", "Max iterations reached. Time: " << planning_timer.GetDuration());
prob_->termination_criterion = TerminationCriterion::IterationLimit;
}
// Roll-out
for (int t = 0; t < T - 1; ++t)
prob_->Update(new_U.col(t), t);
// Set cost evolution
prob_->SetCostEvolution(iteration, cost);
}
// store the best solution found over all iterations
for (int t = 0; t < T - 1; ++t)
{
solution.row(t) = new_U.col(t).transpose();
prob_->Update(new_U.col(t), t);
}
planning_time_ = planning_timer.GetDuration();
}
Eigen::VectorXd ILQRSolver::GetFeedbackControl(Eigen::VectorXdRefConst x, int t) const
{
const Eigen::MatrixXd control_limits = dynamics_solver_->get_control_limits();
Eigen::VectorXd delta_uk = -Ku_gains_[t] * best_ref_u_.col(t) - Kv_gains_[t] * vk_gains_[t + 1] -
K_gains_[t] * dynamics_solver_->StateDelta(x, best_ref_x_.col(t));
Eigen::VectorXd u = best_ref_u_.col(t) + delta_uk;
return u.cwiseMax(control_limits.col(0)).cwiseMin(control_limits.col(1));
}
} // namespace exotica
<commit_msg>[exotica_ilqr_solver] Reintroduce clamping<commit_after>//
// Copyright (c) 2019, University of Edinburgh
// 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 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 <exotica_ilqr_solver/ilqr_solver.h>
REGISTER_MOTIONSOLVER_TYPE("ILQRSolver", exotica::ILQRSolver)
namespace exotica
{
void ILQRSolver::SpecifyProblem(PlanningProblemPtr pointer)
{
if (pointer->type() != "exotica::DynamicTimeIndexedShootingProblem")
{
ThrowNamed("This ILQRSolver can't solve problem of type '" << pointer->type() << "'!");
}
MotionSolver::SpecifyProblem(pointer);
prob_ = std::static_pointer_cast<DynamicTimeIndexedShootingProblem>(pointer);
dynamics_solver_ = prob_->GetScene()->GetDynamicsSolver();
}
void ILQRSolver::BackwardPass()
{
constexpr double min_clamp_ = -1e10;
constexpr double max_clamp_ = 1e10;
const int T = prob_->get_T();
const double dt = dynamics_solver_->get_dt();
const Eigen::MatrixXd& Qf = prob_->get_Qf();
const Eigen::MatrixXd R = dt * prob_->get_R();
const Eigen::MatrixXd& X_star = prob_->get_X_star();
// eq. 18
vk_gains_[T - 1] = Qf * dynamics_solver_->StateDelta(prob_->get_X(T - 1), X_star.col(T - 1));
vk_gains_[T - 1] = vk_gains_[T - 1].unaryExpr([min_clamp_, max_clamp_](double x) -> double {
return std::min(std::max(x, min_clamp_), max_clamp_);
});
Eigen::MatrixXd Sk = Qf;
Sk = Sk.unaryExpr([min_clamp_, max_clamp_](double x) -> double {
return std::min(std::max(x, min_clamp_), max_clamp_);
});
vk_gains_[T - 1] = vk_gains_[T - 1].unaryExpr([min_clamp_, max_clamp_](double x) -> double {
return std::min(std::max(x, min_clamp_), max_clamp_);
});
for (int t = T - 2; t >= 0; t--)
{
Eigen::VectorXd x = prob_->get_X(t), u = prob_->get_U(t);
Eigen::MatrixXd Ak = dynamics_solver_->fx(x, u), Bk = dynamics_solver_->fu(x, u),
Q = dt * prob_->get_Q(t);
// eq. 13-16
Ak.noalias() = Ak * dt + Eigen::MatrixXd::Identity(Ak.rows(), Ak.cols());
Bk.noalias() = Bk * dt;
// this inverse is common for all factors
// TODO: use LLT
const Eigen::MatrixXd _inv =
(Eigen::MatrixXd::Identity(R.rows(), R.cols()) * parameters_.RegularizationRate + R + Bk.transpose() * Sk * Bk).inverse();
Kv_gains_[t] = _inv * Bk.transpose();
K_gains_[t] = _inv * Bk.transpose() * Sk * Ak;
Ku_gains_[t] = _inv * R;
Sk = Ak.transpose() * Sk * (Ak - Bk * K_gains_[t]) + Q;
vk_gains_[t] = ((Ak - Bk * K_gains_[t]).transpose() * vk_gains_[t + 1]) -
(K_gains_[t].transpose() * R * u) + (Q * x);
// fix for large values
Sk = Sk.unaryExpr([min_clamp_, max_clamp_](double x) -> double {
return std::min(std::max(x, min_clamp_), max_clamp_);
});
vk_gains_[t] = vk_gains_[t].unaryExpr([min_clamp_, max_clamp_](double x) -> double {
return std::min(std::max(x, min_clamp_), max_clamp_);
});
}
}
double ILQRSolver::ForwardPass(const double alpha, Eigen::MatrixXdRefConst ref_x, Eigen::MatrixXdRefConst ref_u)
{
double cost = 0;
const int T = prob_->get_T();
const Eigen::MatrixXd control_limits = dynamics_solver_->get_control_limits();
const double dt = dynamics_solver_->get_dt();
Eigen::VectorXd delta_uk(dynamics_solver_->get_num_controls()), u(dynamics_solver_->get_num_controls());
for (int t = 0; t < T - 1; ++t)
{
u = ref_u.col(t);
// eq. 12
delta_uk = -Ku_gains_[t] * u - Kv_gains_[t] * vk_gains_[t + 1] -
K_gains_[t] * dynamics_solver_->StateDelta(prob_->get_X(t), ref_x.col(t));
u.noalias() += alpha * delta_uk;
// clamp controls
u = u.cwiseMax(control_limits.col(0)).cwiseMin(control_limits.col(1));
prob_->Update(u, t);
cost += dt * (prob_->GetControlCost(t) + prob_->GetStateCost(t));
}
// add terminal cost
cost += prob_->GetStateCost(T - 1);
return cost;
}
void ILQRSolver::Solve(Eigen::MatrixXd& solution)
{
if (!prob_) ThrowNamed("Solver has not been initialized!");
Timer planning_timer, backward_pass_timer, line_search_timer;
const int T = prob_->get_T();
const int NU = prob_->get_num_controls();
const int NX = prob_->get_num_positions() + prob_->get_num_velocities();
const double dt = dynamics_solver_->get_dt();
prob_->ResetCostEvolution(GetNumberOfMaxIterations() + 1);
prob_->PreUpdate();
double cost = 0;
for (int t = 0; t < T - 1; ++t)
{
prob_->Update(prob_->get_U(t), t);
cost += dt * (prob_->GetControlCost(t) + prob_->GetStateCost(t));
}
// add terminal cost
cost += prob_->GetStateCost(T - 1);
prob_->SetCostEvolution(0, cost);
// initialize Gain matrices
K_gains_.assign(T, Eigen::MatrixXd(NU, NX));
Ku_gains_.assign(T, Eigen::MatrixXd(NU, NU));
Kv_gains_.assign(T, Eigen::MatrixXd(NU, NX));
vk_gains_.assign(T, Eigen::MatrixXd(NX, 1));
// all of the below are not pointers, since we want to copy over
// solutions across iterations
Eigen::MatrixXd new_U = prob_->get_U();
solution.resize(T - 1, NU);
if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Running ILQR solver for max " << GetNumberOfMaxIterations() << " iterations");
double cost_prev = cost;
int last_best_iteration = 0;
Eigen::VectorXd alpha_space = Eigen::VectorXd::LinSpaced(11, 0.0, -3.0);
for (int ai = 0; ai < alpha_space.size(); ++ai)
{
alpha_space(ai) = std::pow(10.0, alpha_space(ai));
}
double time_taken_backward_pass = 0.0, time_taken_forward_pass = 0.0;
for (int iteration = 1; iteration <= GetNumberOfMaxIterations(); ++iteration)
{
// Check whether user interrupted (Ctrl+C)
if (Server::IsRos() && !ros::ok())
{
if (debug_) HIGHLIGHT("Solving cancelled by user");
prob_->termination_criterion = TerminationCriterion::UserDefined;
break;
}
// Backwards pass computes the gains
backward_pass_timer.Reset();
BackwardPass();
time_taken_backward_pass = backward_pass_timer.GetDuration();
// Forward pass to compute new control trajectory
line_search_timer.Reset();
// Make a copy to compare against
Eigen::MatrixXd ref_x = prob_->get_X(),
ref_u = prob_->get_U();
// Perform a backtracking line search to find the best rate
double best_alpha = 0;
for (int ai = 0; ai < alpha_space.size(); ++ai)
{
const double& alpha = alpha_space(ai);
double rollout_cost = ForwardPass(alpha, ref_x, ref_u);
if (rollout_cost < cost_prev && !std::isnan(rollout_cost))
{
cost = rollout_cost;
new_U = prob_->get_U();
best_alpha = alpha;
break;
}
}
// Finiteness checks
if (!new_U.allFinite() || !std::isfinite(cost))
{
prob_->termination_criterion = TerminationCriterion::Divergence;
WARNING_NAMED("ILQRSolver", "Diverged: Controls or cost are not finite.");
return;
}
time_taken_forward_pass = line_search_timer.GetDuration();
if (debug_)
{
HIGHLIGHT_NAMED("ILQRSolver", "Iteration " << iteration << std::setprecision(3) << ":\tBackward pass: " << time_taken_backward_pass << " s\tForward pass: " << time_taken_forward_pass << " s\tCost: " << cost << "\talpha: " << best_alpha);
}
//
// Stopping criteria checks
//
// Relative function tolerance
// (f_t-1 - f_t) <= functionTolerance * max(1, abs(f_t))
if ((cost_prev - cost) < parameters_.FunctionTolerance * std::max(1.0, std::abs(cost)))
{
// Function tolerance patience check
if (parameters_.FunctionTolerancePatience > 0)
{
if (iteration - last_best_iteration > parameters_.FunctionTolerancePatience)
{
if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Early stopping criterion reached (" << cost << " < " << cost_prev << "). Time: " << planning_timer.GetDuration());
prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
break;
}
}
else
{
if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Function tolerance reached (" << cost << " < " << cost_prev << "). Time: " << planning_timer.GetDuration());
prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
break;
}
}
else
{
// Reset function tolerance patience
last_best_iteration = iteration;
}
// If better than previous iteration, copy solutions for next iteration
if (cost < cost_prev)
{
cost_prev = cost;
// last_best_iteration = iteration;
best_ref_x_ = ref_x;
best_ref_u_ = ref_u;
}
// if (iteration - last_best_iteration > parameters_.FunctionTolerancePatience)
// {
// if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Early stopping criterion reached. Time: " << planning_timer.GetDuration());
// prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
// break;
// }
// if (last_cost - current_cost < parameters_.FunctionTolerance && last_cost - current_cost > 0)
// {
// if (debug_) HIGHLIGHT_NAMED("ILQRSolver", "Function tolerance reached. Time: " << planning_timer.GetDuration());
// prob_->termination_criterion = TerminationCriterion::FunctionTolerance;
// break;
// }
if (debug_ && iteration == parameters_.MaxIterations)
{
HIGHLIGHT_NAMED("ILQRSolver", "Max iterations reached. Time: " << planning_timer.GetDuration());
prob_->termination_criterion = TerminationCriterion::IterationLimit;
}
// Roll-out
for (int t = 0; t < T - 1; ++t)
prob_->Update(new_U.col(t), t);
// Set cost evolution
prob_->SetCostEvolution(iteration, cost);
}
// store the best solution found over all iterations
for (int t = 0; t < T - 1; ++t)
{
solution.row(t) = new_U.col(t).transpose();
prob_->Update(new_U.col(t), t);
}
planning_time_ = planning_timer.GetDuration();
}
Eigen::VectorXd ILQRSolver::GetFeedbackControl(Eigen::VectorXdRefConst x, int t) const
{
const Eigen::MatrixXd control_limits = dynamics_solver_->get_control_limits();
Eigen::VectorXd delta_uk = -Ku_gains_[t] * best_ref_u_.col(t) - Kv_gains_[t] * vk_gains_[t + 1] -
K_gains_[t] * dynamics_solver_->StateDelta(x, best_ref_x_.col(t));
Eigen::VectorXd u = best_ref_u_.col(t) + delta_uk;
return u.cwiseMax(control_limits.col(0)).cwiseMin(control_limits.col(1));
}
} // namespace exotica
<|endoftext|>
|
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
// Include this before af/opencl.h
// Causes conflict between system cl.hpp and opencl/cl.hpp
#if defined(WITH_GRAPHICS)
#include <graphics_common.hpp>
#endif
#include <cl.hpp>
#include <af/version.h>
#include <af/opencl.h>
#include <defines.hpp>
#include <platform.hpp>
#include <functional>
#include <algorithm>
#include <cctype>
#include <vector>
#include <string>
#include <sstream>
#include <stdexcept>
#include <cstring>
#include <algorithm>
#include <map>
#include <errorcodes.hpp>
#include <err_opencl.hpp>
using std::string;
using std::vector;
using std::ostringstream;
using std::runtime_error;
using cl::Platform;
using cl::Context;
using cl::CommandQueue;
using cl::Device;
namespace opencl
{
#if defined (OS_MAC)
static const std::string CL_GL_SHARING_EXT = "cl_APPLE_gl_sharing";
#else
static const std::string CL_GL_SHARING_EXT = "cl_khr_gl_sharing";
#endif
static const char *get_system(void)
{
return
#if defined(ARCH_32)
"32-bit "
#elif defined(ARCH_64)
"64-bit "
#endif
#if defined(OS_LNX)
"Linux";
#elif defined(OS_WIN)
"Windows";
#elif defined(OS_MAC)
"Mac OSX";
#endif
}
DeviceManager& DeviceManager::getInstance()
{
static DeviceManager my_instance;
return my_instance;
}
DeviceManager::~DeviceManager()
{
//TODO: FIXME:
// OpenCL libs on Windows platforms
// are crashing the application at program exit
// most probably a reference counting issue based
// on the investigation done so far. This problem
// doesn't seem to happen on Linux or MacOSX.
// So, clean up OpenCL resources on non-Windows platforms
#ifndef OS_WIN
for (auto q: mQueues) delete q;
for (auto d : mDevices) delete d;
for (auto c : mContexts) delete c;
for (auto p : mPlatforms) delete p;
#endif
}
void DeviceManager::setContext(int device)
{
mActiveQId = device;
mActiveCtxId = device;
}
DeviceManager::DeviceManager()
: mActiveCtxId(0), mActiveQId(0)
{
try {
std::vector<cl::Platform> platforms;
Platform::get(&platforms);
cl_device_type DEVC_TYPES[] = {
CL_DEVICE_TYPE_GPU,
#ifndef OS_MAC
CL_DEVICE_TYPE_ACCELERATOR,
CL_DEVICE_TYPE_CPU
#endif
};
for (auto &platform : platforms)
mPlatforms.push_back(new Platform(platform));
unsigned nDevices = 0;
for (auto devType : DEVC_TYPES) {
for (auto &platform : platforms) {
cl_context_properties cps[3] = {CL_CONTEXT_PLATFORM,
(cl_context_properties)(platform()),
0};
std::vector<Device> devs;
try {
platform.getDevices(devType, &devs);
} catch(const cl::Error &err) {
if (err.err() != CL_DEVICE_NOT_FOUND) {
throw;
}
}
for (auto dev : devs) {
nDevices++;
Context *ctx = new Context(dev, cps);
CommandQueue *cq = new CommandQueue(*ctx, dev);
mDevices.push_back(new Device(dev));
mContexts.push_back(ctx);
mQueues.push_back(cq);
mCtxOffsets.push_back(nDevices);
mIsGLSharingOn.push_back(false);
}
}
}
const char* deviceENV = getenv("AF_OPENCL_DEFAULT_DEVICE");
if(deviceENV) {
std::stringstream s(deviceENV);
int def_device = -1;
s >> def_device;
if(def_device < 0 || def_device >= (int)nDevices) {
printf("WARNING: AF_OPENCL_DEFAULT_DEVICE is out of range\n");
printf("Setting default device as 0\n");
} else {
setContext(def_device);
}
}
} catch (const cl::Error &error) {
CL_TO_AF_ERROR(error);
}
/* loop over devices and replace contexts with
* OpenGL shared contexts whereever applicable */
#if defined(WITH_GRAPHICS)
// Define AF_DISABLE_GRAPHICS with any value to disable initialization
const char* noGraphicsENV = getenv("AF_DISABLE_GRAPHICS");
if(!noGraphicsENV) { // If AF_DISABLE_GRAPHICS is not defined
try {
int devCount = mDevices.size();
fg::Window* wHandle = graphics::ForgeManager::getInstance().getMainWindow();
for(int i=0; i<devCount; ++i)
markDeviceForInterop(i, wHandle);
} catch (...) {
}
}
#endif
}
// http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring/217605#217605
// trim from start
static inline std::string <rim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
static std::string platformMap(std::string &platStr)
{
static bool isFirst = true;
typedef std::map<std::string, std::string> strmap_t;
static strmap_t platMap;
if (isFirst) {
platMap["NVIDIA CUDA"] = "NVIDIA ";
platMap["Intel(R) OpenCL"] = "INTEL ";
platMap["AMD Accelerated Parallel Processing"] = "AMD ";
platMap["Intel Gen OCL Driver"] = "BEIGNET ";
platMap["Apple"] = "APPLE ";
isFirst = false;
}
strmap_t::iterator idx = platMap.find(platStr);
if (idx == platMap.end()) {
return platStr;
} else {
return idx->second;
}
}
std::string getInfo()
{
ostringstream info;
info << "ArrayFire v" << AF_VERSION
<< " (OpenCL, " << get_system() << ", build " << AF_REVISION << ")" << std::endl;
unsigned nDevices = 0;
for (auto context : DeviceManager::getInstance().mContexts) {
vector<Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();
for(auto &device:devices) {
const Platform &platform = device.getInfo<CL_DEVICE_PLATFORM>();
string platStr = platform.getInfo<CL_PLATFORM_NAME>();
bool show_braces = ((unsigned)getActiveDeviceId() == nDevices);
string dstr = device.getInfo<CL_DEVICE_NAME>();
string id = (show_braces ? string("[") : "-") + std::to_string(nDevices) +
(show_braces ? string("]") : "-");
info << id << " " << platformMap(platStr) << ": " << ltrim(dstr) << " ";
#ifndef NDEBUG
info << device.getInfo<CL_DEVICE_VERSION>();
info << " Device driver " << device.getInfo<CL_DRIVER_VERSION>();
info << " FP64 Support("
<< (device.getInfo<CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE>()>0 ? "True" : "False")
<< ")";
#endif
info << std::endl;
nDevices++;
}
}
return info.str();
}
std::string getPlatformName(const cl::Device &device)
{
const Platform &platform = device.getInfo<CL_DEVICE_PLATFORM>();
std::string platStr = platform.getInfo<CL_PLATFORM_NAME>();
return platformMap(platStr);
}
int getDeviceCount()
{
return DeviceManager::getInstance().mQueues.size();
}
int getActiveDeviceId()
{
return DeviceManager::getInstance().mActiveQId;
}
const Context& getContext()
{
DeviceManager& devMngr = DeviceManager::getInstance();
return *(devMngr.mContexts[devMngr.mActiveCtxId]);
}
CommandQueue& getQueue()
{
DeviceManager& devMngr = DeviceManager::getInstance();
return *(devMngr.mQueues[devMngr.mActiveQId]);
}
const cl::Device& getDevice()
{
DeviceManager& devMngr = DeviceManager::getInstance();
return *(devMngr.mDevices[devMngr.mActiveQId]);
}
bool isGLSharingSupported()
{
DeviceManager& devMngr = DeviceManager::getInstance();
return devMngr.mIsGLSharingOn[devMngr.mActiveQId];
}
bool isDoubleSupported(int device)
{
DeviceManager& devMngr = DeviceManager::getInstance();
return (devMngr.mDevices[device]->getInfo<CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE>()>0);
}
void devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)
{
unsigned nDevices = 0;
unsigned currActiveDevId = (unsigned)getActiveDeviceId();
bool devset = false;
for (auto context : DeviceManager::getInstance().mContexts) {
vector<Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();
for (auto &device : devices) {
const Platform &platform = device.getInfo<CL_DEVICE_PLATFORM>();
string platStr = platform.getInfo<CL_PLATFORM_NAME>();
if (currActiveDevId == nDevices) {
string dev_str;
device.getInfo(CL_DEVICE_NAME, &dev_str);
string com_str = device.getInfo<CL_DEVICE_VERSION>();
com_str = com_str.substr(7, 3);
// strip out whitespace from the device string:
const std::string& whitespace = " \t";
const auto strBegin = dev_str.find_first_not_of(whitespace);
const auto strEnd = dev_str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
dev_str = dev_str.substr(strBegin, strRange);
// copy to output
snprintf(d_name, 64, "%s", dev_str.c_str());
snprintf(d_platform, 10, "OpenCL");
snprintf(d_toolkit, 64, "%s", platStr.c_str());
snprintf(d_compute, 10, "%s", com_str.c_str());
devset = true;
}
if(devset) break;
nDevices++;
}
if(devset) break;
}
// Sanitize input
for (int i = 0; i < 31; i++) {
if (d_name[i] == ' ') {
if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;
else d_name[i] = '_';
}
}
}
int setDevice(int device)
{
DeviceManager& devMngr = DeviceManager::getInstance();
if (device >= (int)devMngr.mQueues.size() ||
device>= (int)DeviceManager::MAX_DEVICES) {
//throw runtime_error("@setDevice: invalid device index");
return -1;
}
else {
int old = devMngr.mActiveQId;
devMngr.setContext(device);
return old;
}
}
void sync(int device)
{
try {
int currDevice = getActiveDeviceId();
setDevice(device);
getQueue().finish();
setDevice(currDevice);
} catch (const cl::Error &ex) {
CL_TO_AF_ERROR(ex);
}
}
bool checkExtnAvailability(const Device &pDevice, std::string pName)
{
bool ret_val = false;
// find the extension required
std::string exts = pDevice.getInfo<CL_DEVICE_EXTENSIONS>();
std::stringstream ss(exts);
std::string item;
while (std::getline(ss,item,' ')) {
if (item==pName) {
ret_val = true;
break;
}
}
return ret_val;
}
#if defined(WITH_GRAPHICS)
void DeviceManager::markDeviceForInterop(const int device, const fg::Window* wHandle)
{
try {
if (device >= (int)mQueues.size() ||
device>= (int)DeviceManager::MAX_DEVICES) {
throw cl::Error(CL_INVALID_DEVICE, "Invalid device passed for CL-GL Interop");
}
else {
mQueues[device]->finish();
// check if the device has CL_GL sharing extension enabled
bool temp = checkExtnAvailability(*mDevices[device], CL_GL_SHARING_EXT);
if (!temp) {
printf("Device[%d] has no support for OpenGL Interoperation\n",device);
/* return silently if given device has not OpenGL sharing extension
* enabled so that regular queue is used for it */
return;
}
// call forge to get OpenGL sharing context and details
cl::Platform plat = mDevices[device]->getInfo<CL_DEVICE_PLATFORM>();
#ifdef OS_MAC
CGLContextObj cgl_current_ctx = CGLGetCurrentContext();
CGLShareGroupObj cgl_share_group = CGLGetShareGroup(cgl_current_ctx);
cl_context_properties cps[] = {
CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)cgl_share_group,
0
};
#else
cl_context_properties cps[] = {
CL_GL_CONTEXT_KHR, (cl_context_properties)wHandle->context(),
#if defined(_WIN32) || defined(_MSC_VER)
CL_WGL_HDC_KHR, (cl_context_properties)wHandle->display(),
#else
CL_GLX_DISPLAY_KHR, (cl_context_properties)wHandle->display(),
#endif
CL_CONTEXT_PLATFORM, (cl_context_properties)plat(),
0
};
#endif
Context * ctx = new Context(*mDevices[device], cps);
CommandQueue * cq = new CommandQueue(*ctx, *mDevices[device]);
delete mContexts[device];
delete mQueues[device];
mContexts[device] = ctx;
mQueues[device] = cq;
}
mIsGLSharingOn[device] = true;
} catch (const cl::Error &ex) {
/* If replacing the original context with GL shared context
* failes, don't throw an error and instead fall back to
* original context and use copy via host to support graphics
* on that particular OpenCL device. So mark it as no GL sharing */
}
}
#endif
}
using namespace opencl;
af_err afcl_get_context(cl_context *ctx, const bool retain)
{
*ctx = getContext()();
if (retain) clRetainContext(*ctx);
return AF_SUCCESS;
}
af_err afcl_get_queue(cl_command_queue *queue, const bool retain)
{
*queue = getQueue()();
if (retain) clRetainCommandQueue(*queue);
return AF_SUCCESS;
}
af_err afcl_get_device_id(cl_device_id *id)
{
*id = getDevice()();
return AF_SUCCESS;
}
<commit_msg>fix instantiation of Platform objects<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
// Include this before af/opencl.h
// Causes conflict between system cl.hpp and opencl/cl.hpp
#if defined(WITH_GRAPHICS)
#include <graphics_common.hpp>
#endif
#include <cl.hpp>
#include <af/version.h>
#include <af/opencl.h>
#include <defines.hpp>
#include <platform.hpp>
#include <functional>
#include <algorithm>
#include <cctype>
#include <vector>
#include <string>
#include <sstream>
#include <stdexcept>
#include <cstring>
#include <algorithm>
#include <map>
#include <errorcodes.hpp>
#include <err_opencl.hpp>
using std::string;
using std::vector;
using std::ostringstream;
using std::runtime_error;
using cl::Platform;
using cl::Context;
using cl::CommandQueue;
using cl::Device;
namespace opencl
{
#if defined (OS_MAC)
static const std::string CL_GL_SHARING_EXT = "cl_APPLE_gl_sharing";
#else
static const std::string CL_GL_SHARING_EXT = "cl_khr_gl_sharing";
#endif
static const char *get_system(void)
{
return
#if defined(ARCH_32)
"32-bit "
#elif defined(ARCH_64)
"64-bit "
#endif
#if defined(OS_LNX)
"Linux";
#elif defined(OS_WIN)
"Windows";
#elif defined(OS_MAC)
"Mac OSX";
#endif
}
DeviceManager& DeviceManager::getInstance()
{
static DeviceManager my_instance;
return my_instance;
}
DeviceManager::~DeviceManager()
{
//TODO: FIXME:
// OpenCL libs on Windows platforms
// are crashing the application at program exit
// most probably a reference counting issue based
// on the investigation done so far. This problem
// doesn't seem to happen on Linux or MacOSX.
// So, clean up OpenCL resources on non-Windows platforms
#ifndef OS_WIN
for (auto q: mQueues) delete q;
for (auto d : mDevices) delete d;
for (auto c : mContexts) delete c;
for (auto p : mPlatforms) delete p;
#endif
}
void DeviceManager::setContext(int device)
{
mActiveQId = device;
mActiveCtxId = device;
}
DeviceManager::DeviceManager()
: mActiveCtxId(0), mActiveQId(0)
{
try {
std::vector<cl::Platform> platforms;
Platform::get(&platforms);
cl_device_type DEVC_TYPES[] = {
CL_DEVICE_TYPE_GPU,
#ifndef OS_MAC
CL_DEVICE_TYPE_ACCELERATOR,
CL_DEVICE_TYPE_CPU
#endif
};
for (auto &platform : platforms)
mPlatforms.push_back(new Platform(platform));
unsigned nDevices = 0;
for (auto devType : DEVC_TYPES) {
for (auto &platform : platforms) {
cl_context_properties cps[3] = {CL_CONTEXT_PLATFORM,
(cl_context_properties)(platform()),
0};
std::vector<Device> devs;
try {
platform.getDevices(devType, &devs);
} catch(const cl::Error &err) {
if (err.err() != CL_DEVICE_NOT_FOUND) {
throw;
}
}
for (auto dev : devs) {
nDevices++;
Context *ctx = new Context(dev, cps);
CommandQueue *cq = new CommandQueue(*ctx, dev);
mDevices.push_back(new Device(dev));
mContexts.push_back(ctx);
mQueues.push_back(cq);
mCtxOffsets.push_back(nDevices);
mIsGLSharingOn.push_back(false);
}
}
}
const char* deviceENV = getenv("AF_OPENCL_DEFAULT_DEVICE");
if(deviceENV) {
std::stringstream s(deviceENV);
int def_device = -1;
s >> def_device;
if(def_device < 0 || def_device >= (int)nDevices) {
printf("WARNING: AF_OPENCL_DEFAULT_DEVICE is out of range\n");
printf("Setting default device as 0\n");
} else {
setContext(def_device);
}
}
} catch (const cl::Error &error) {
CL_TO_AF_ERROR(error);
}
/* loop over devices and replace contexts with
* OpenGL shared contexts whereever applicable */
#if defined(WITH_GRAPHICS)
// Define AF_DISABLE_GRAPHICS with any value to disable initialization
const char* noGraphicsENV = getenv("AF_DISABLE_GRAPHICS");
if(!noGraphicsENV) { // If AF_DISABLE_GRAPHICS is not defined
try {
int devCount = mDevices.size();
fg::Window* wHandle = graphics::ForgeManager::getInstance().getMainWindow();
for(int i=0; i<devCount; ++i)
markDeviceForInterop(i, wHandle);
} catch (...) {
}
}
#endif
}
// http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring/217605#217605
// trim from start
static inline std::string <rim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
static std::string platformMap(std::string &platStr)
{
static bool isFirst = true;
typedef std::map<std::string, std::string> strmap_t;
static strmap_t platMap;
if (isFirst) {
platMap["NVIDIA CUDA"] = "NVIDIA ";
platMap["Intel(R) OpenCL"] = "INTEL ";
platMap["AMD Accelerated Parallel Processing"] = "AMD ";
platMap["Intel Gen OCL Driver"] = "BEIGNET ";
platMap["Apple"] = "APPLE ";
isFirst = false;
}
strmap_t::iterator idx = platMap.find(platStr);
if (idx == platMap.end()) {
return platStr;
} else {
return idx->second;
}
}
std::string getInfo()
{
ostringstream info;
info << "ArrayFire v" << AF_VERSION
<< " (OpenCL, " << get_system() << ", build " << AF_REVISION << ")" << std::endl;
unsigned nDevices = 0;
for (auto context : DeviceManager::getInstance().mContexts) {
vector<Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();
for(auto &device:devices) {
const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
string platStr = platform.getInfo<CL_PLATFORM_NAME>();
bool show_braces = ((unsigned)getActiveDeviceId() == nDevices);
string dstr = device.getInfo<CL_DEVICE_NAME>();
string id = (show_braces ? string("[") : "-") + std::to_string(nDevices) +
(show_braces ? string("]") : "-");
info << id << " " << platformMap(platStr) << ": " << ltrim(dstr) << " ";
#ifndef NDEBUG
info << device.getInfo<CL_DEVICE_VERSION>();
info << " Device driver " << device.getInfo<CL_DRIVER_VERSION>();
info << " FP64 Support("
<< (device.getInfo<CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE>()>0 ? "True" : "False")
<< ")";
#endif
info << std::endl;
nDevices++;
}
}
return info.str();
}
std::string getPlatformName(const cl::Device &device)
{
const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
std::string platStr = platform.getInfo<CL_PLATFORM_NAME>();
return platformMap(platStr);
}
int getDeviceCount()
{
return DeviceManager::getInstance().mQueues.size();
}
int getActiveDeviceId()
{
return DeviceManager::getInstance().mActiveQId;
}
const Context& getContext()
{
DeviceManager& devMngr = DeviceManager::getInstance();
return *(devMngr.mContexts[devMngr.mActiveCtxId]);
}
CommandQueue& getQueue()
{
DeviceManager& devMngr = DeviceManager::getInstance();
return *(devMngr.mQueues[devMngr.mActiveQId]);
}
const cl::Device& getDevice()
{
DeviceManager& devMngr = DeviceManager::getInstance();
return *(devMngr.mDevices[devMngr.mActiveQId]);
}
bool isGLSharingSupported()
{
DeviceManager& devMngr = DeviceManager::getInstance();
return devMngr.mIsGLSharingOn[devMngr.mActiveQId];
}
bool isDoubleSupported(int device)
{
DeviceManager& devMngr = DeviceManager::getInstance();
return (devMngr.mDevices[device]->getInfo<CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE>()>0);
}
void devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)
{
unsigned nDevices = 0;
unsigned currActiveDevId = (unsigned)getActiveDeviceId();
bool devset = false;
for (auto context : DeviceManager::getInstance().mContexts) {
vector<Device> devices = context->getInfo<CL_CONTEXT_DEVICES>();
for (auto &device : devices) {
const Platform platform(device.getInfo<CL_DEVICE_PLATFORM>());
string platStr = platform.getInfo<CL_PLATFORM_NAME>();
if (currActiveDevId == nDevices) {
string dev_str;
device.getInfo(CL_DEVICE_NAME, &dev_str);
string com_str = device.getInfo<CL_DEVICE_VERSION>();
com_str = com_str.substr(7, 3);
// strip out whitespace from the device string:
const std::string& whitespace = " \t";
const auto strBegin = dev_str.find_first_not_of(whitespace);
const auto strEnd = dev_str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
dev_str = dev_str.substr(strBegin, strRange);
// copy to output
snprintf(d_name, 64, "%s", dev_str.c_str());
snprintf(d_platform, 10, "OpenCL");
snprintf(d_toolkit, 64, "%s", platStr.c_str());
snprintf(d_compute, 10, "%s", com_str.c_str());
devset = true;
}
if(devset) break;
nDevices++;
}
if(devset) break;
}
// Sanitize input
for (int i = 0; i < 31; i++) {
if (d_name[i] == ' ') {
if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;
else d_name[i] = '_';
}
}
}
int setDevice(int device)
{
DeviceManager& devMngr = DeviceManager::getInstance();
if (device >= (int)devMngr.mQueues.size() ||
device>= (int)DeviceManager::MAX_DEVICES) {
//throw runtime_error("@setDevice: invalid device index");
return -1;
}
else {
int old = devMngr.mActiveQId;
devMngr.setContext(device);
return old;
}
}
void sync(int device)
{
try {
int currDevice = getActiveDeviceId();
setDevice(device);
getQueue().finish();
setDevice(currDevice);
} catch (const cl::Error &ex) {
CL_TO_AF_ERROR(ex);
}
}
bool checkExtnAvailability(const Device &pDevice, std::string pName)
{
bool ret_val = false;
// find the extension required
std::string exts = pDevice.getInfo<CL_DEVICE_EXTENSIONS>();
std::stringstream ss(exts);
std::string item;
while (std::getline(ss,item,' ')) {
if (item==pName) {
ret_val = true;
break;
}
}
return ret_val;
}
#if defined(WITH_GRAPHICS)
void DeviceManager::markDeviceForInterop(const int device, const fg::Window* wHandle)
{
try {
if (device >= (int)mQueues.size() ||
device>= (int)DeviceManager::MAX_DEVICES) {
throw cl::Error(CL_INVALID_DEVICE, "Invalid device passed for CL-GL Interop");
}
else {
mQueues[device]->finish();
// check if the device has CL_GL sharing extension enabled
bool temp = checkExtnAvailability(*mDevices[device], CL_GL_SHARING_EXT);
if (!temp) {
printf("Device[%d] has no support for OpenGL Interoperation\n",device);
/* return silently if given device has not OpenGL sharing extension
* enabled so that regular queue is used for it */
return;
}
// call forge to get OpenGL sharing context and details
cl::Platform plat = mDevices[device]->getInfo<CL_DEVICE_PLATFORM>();
#ifdef OS_MAC
CGLContextObj cgl_current_ctx = CGLGetCurrentContext();
CGLShareGroupObj cgl_share_group = CGLGetShareGroup(cgl_current_ctx);
cl_context_properties cps[] = {
CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)cgl_share_group,
0
};
#else
cl_context_properties cps[] = {
CL_GL_CONTEXT_KHR, (cl_context_properties)wHandle->context(),
#if defined(_WIN32) || defined(_MSC_VER)
CL_WGL_HDC_KHR, (cl_context_properties)wHandle->display(),
#else
CL_GLX_DISPLAY_KHR, (cl_context_properties)wHandle->display(),
#endif
CL_CONTEXT_PLATFORM, (cl_context_properties)plat(),
0
};
#endif
Context * ctx = new Context(*mDevices[device], cps);
CommandQueue * cq = new CommandQueue(*ctx, *mDevices[device]);
delete mContexts[device];
delete mQueues[device];
mContexts[device] = ctx;
mQueues[device] = cq;
}
mIsGLSharingOn[device] = true;
} catch (const cl::Error &ex) {
/* If replacing the original context with GL shared context
* failes, don't throw an error and instead fall back to
* original context and use copy via host to support graphics
* on that particular OpenCL device. So mark it as no GL sharing */
}
}
#endif
}
using namespace opencl;
af_err afcl_get_context(cl_context *ctx, const bool retain)
{
*ctx = getContext()();
if (retain) clRetainContext(*ctx);
return AF_SUCCESS;
}
af_err afcl_get_queue(cl_command_queue *queue, const bool retain)
{
*queue = getQueue()();
if (retain) clRetainCommandQueue(*queue);
return AF_SUCCESS;
}
af_err afcl_get_device_id(cl_device_id *id)
{
*id = getDevice()();
return AF_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "media/base/data_buffer.h"
#include "remoting/jingle_glue/jingle_channel.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/libjingle/source/talk/base/stream.h"
using testing::_;
using testing::Return;
using testing::Mock;
using testing::SetArgumentPointee;
namespace remoting {
namespace {
// Size of test buffer in bytes.
const size_t kBufferSize = 100;
} // namespace
class MockCallback : public JingleChannel::Callback {
public:
MOCK_METHOD2(OnStateChange, void(JingleChannel*, JingleChannel::State));
MOCK_METHOD2(OnPacketReceived, void(JingleChannel*,
scoped_refptr<media::DataBuffer>));
};
class MockStream : public talk_base::StreamInterface {
public:
virtual ~MockStream() {}
MOCK_CONST_METHOD0(GetState, talk_base::StreamState());
MOCK_METHOD4(Read, talk_base::StreamResult(void*, size_t, size_t*, int*));
MOCK_METHOD4(Write, talk_base::StreamResult(const void*, size_t,
size_t*, int*));
MOCK_CONST_METHOD1(GetAvailable, bool(size_t*));
MOCK_METHOD0(Close, void());
MOCK_METHOD3(PostEvent, void(talk_base::Thread*, int, int));
MOCK_METHOD2(PostEvent, void(int, int));
};
TEST(JingleChannelTest, Init) {
JingleThread thread;
MockStream* stream = new MockStream();
MockCallback callback;
EXPECT_CALL(*stream, GetState())
.Times(1)
.WillRepeatedly(Return(talk_base::SS_OPENING));
scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);
EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CONNECTING))
.Times(1);
thread.Start();
EXPECT_EQ(JingleChannel::INITIALIZING, channel->state());
channel->Init(&thread, stream, "user@domain.com");
EXPECT_EQ(JingleChannel::CONNECTING, channel->state());
channel->state_ = JingleChannel::CLOSED;
thread.Stop();
}
TEST(JingleChannelTest, Write) {
JingleThread thread;
MockStream* stream = new MockStream(); // Freed by the channel.
MockCallback callback;
scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);
data->SetDataSize(kBufferSize);
EXPECT_CALL(*stream, Write(static_cast<const void*>(data->GetData()),
kBufferSize, _, _))
.WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),
Return(talk_base::SR_SUCCESS)));
scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);
channel->thread_ = &thread;
channel->stream_.reset(stream);
channel->state_ = JingleChannel::OPEN;
thread.Start();
channel->Write(data);
thread.Stop();
channel->state_ = JingleChannel::CLOSED;
}
TEST(JingleChannelTest, Read) {
JingleThread thread;
MockStream* stream = new MockStream(); // Freed by the channel.
MockCallback callback;
scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);
data->SetDataSize(kBufferSize);
scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);
EXPECT_CALL(callback, OnPacketReceived(channel.get(), _))
.Times(1);
EXPECT_CALL(*stream, GetAvailable(_))
.WillOnce(DoAll(SetArgumentPointee<0>(kBufferSize),
Return(true)))
.WillOnce(DoAll(SetArgumentPointee<0>(0),
Return(true)));
EXPECT_CALL(*stream, Read(_, kBufferSize, _, _))
.WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),
Return(talk_base::SR_SUCCESS)));
channel->thread_ = &thread;
channel->stream_.reset(stream);
channel->state_ = JingleChannel::OPEN;
thread.Start();
channel->OnStreamEvent(stream, talk_base::SE_READ, 0);
thread.Stop();
channel->state_ = JingleChannel::CLOSED;
}
TEST(JingleChannelTest, Close) {
JingleThread thread;
MockStream* stream = new MockStream(); // Freed by the channel.
MockCallback callback;
EXPECT_CALL(*stream, Close())
.Times(1);
scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);
channel->thread_ = &thread;
channel->stream_.reset(stream);
channel->state_ = JingleChannel::OPEN;
thread.Start();
channel->Close();
thread.Stop();
}
} // namespace remoting
<commit_msg>Fixed GMock warning about unexpected call in remoting_unittests. BUG=None TEST=unittests<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "media/base/data_buffer.h"
#include "remoting/jingle_glue/jingle_channel.h"
#include "remoting/jingle_glue/jingle_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/libjingle/source/talk/base/stream.h"
using testing::_;
using testing::Return;
using testing::Mock;
using testing::SetArgumentPointee;
namespace remoting {
namespace {
// Size of test buffer in bytes.
const size_t kBufferSize = 100;
} // namespace
class MockCallback : public JingleChannel::Callback {
public:
MOCK_METHOD2(OnStateChange, void(JingleChannel*, JingleChannel::State));
MOCK_METHOD2(OnPacketReceived, void(JingleChannel*,
scoped_refptr<media::DataBuffer>));
};
class MockStream : public talk_base::StreamInterface {
public:
virtual ~MockStream() {}
MOCK_CONST_METHOD0(GetState, talk_base::StreamState());
MOCK_METHOD4(Read, talk_base::StreamResult(void*, size_t, size_t*, int*));
MOCK_METHOD4(Write, talk_base::StreamResult(const void*, size_t,
size_t*, int*));
MOCK_CONST_METHOD1(GetAvailable, bool(size_t*));
MOCK_METHOD0(Close, void());
MOCK_METHOD3(PostEvent, void(talk_base::Thread*, int, int));
MOCK_METHOD2(PostEvent, void(int, int));
};
TEST(JingleChannelTest, Init) {
JingleThread thread;
MockStream* stream = new MockStream();
MockCallback callback;
EXPECT_CALL(*stream, GetState())
.Times(1)
.WillRepeatedly(Return(talk_base::SS_OPENING));
scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);
EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CONNECTING))
.Times(1);
thread.Start();
EXPECT_EQ(JingleChannel::INITIALIZING, channel->state());
channel->Init(&thread, stream, "user@domain.com");
EXPECT_EQ(JingleChannel::CONNECTING, channel->state());
channel->state_ = JingleChannel::CLOSED;
thread.Stop();
}
TEST(JingleChannelTest, Write) {
JingleThread thread;
MockStream* stream = new MockStream(); // Freed by the channel.
MockCallback callback;
scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);
data->SetDataSize(kBufferSize);
EXPECT_CALL(*stream, Write(static_cast<const void*>(data->GetData()),
kBufferSize, _, _))
.WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),
Return(talk_base::SR_SUCCESS)));
scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);
channel->thread_ = &thread;
channel->stream_.reset(stream);
channel->state_ = JingleChannel::OPEN;
thread.Start();
channel->Write(data);
thread.Stop();
channel->state_ = JingleChannel::CLOSED;
}
TEST(JingleChannelTest, Read) {
JingleThread thread;
MockStream* stream = new MockStream(); // Freed by the channel.
MockCallback callback;
scoped_refptr<media::DataBuffer> data = new media::DataBuffer(kBufferSize);
data->SetDataSize(kBufferSize);
scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);
EXPECT_CALL(callback, OnPacketReceived(channel.get(), _))
.Times(1);
EXPECT_CALL(*stream, GetAvailable(_))
.WillOnce(DoAll(SetArgumentPointee<0>(kBufferSize),
Return(true)))
.WillOnce(DoAll(SetArgumentPointee<0>(0),
Return(true)));
EXPECT_CALL(*stream, Read(_, kBufferSize, _, _))
.WillOnce(DoAll(SetArgumentPointee<2>(kBufferSize),
Return(talk_base::SR_SUCCESS)));
channel->thread_ = &thread;
channel->stream_.reset(stream);
channel->state_ = JingleChannel::OPEN;
thread.Start();
channel->OnStreamEvent(stream, talk_base::SE_READ, 0);
thread.Stop();
channel->state_ = JingleChannel::CLOSED;
}
TEST(JingleChannelTest, Close) {
JingleThread thread;
MockStream* stream = new MockStream(); // Freed by the channel.
MockCallback callback;
EXPECT_CALL(*stream, Close())
.Times(1);
scoped_refptr<JingleChannel> channel = new JingleChannel(&callback);
channel->thread_ = &thread;
channel->stream_.reset(stream);
channel->state_ = JingleChannel::OPEN;
EXPECT_CALL(callback, OnStateChange(channel.get(), JingleChannel::CLOSED))
.Times(1);
thread.Start();
channel->Close();
thread.Stop();
}
} // namespace remoting
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdexcept>
#include <ccpp_dds_dcps.h>
#include "rosidl_generator_cpp/MessageTypeSupport.h"
#include "ros_middleware_interface/handles.h"
#include "ros_middleware_opensplice_cpp/MessageTypeSupport.h"
namespace ros_middleware_interface
{
const char * _prismtech_opensplice_identifier = "opensplice_static";
ros_middleware_interface::NodeHandle create_node()
{
std::cout << "create_node()" << std::endl;
std::cout << " create_node() get_instance" << std::endl;
DDS::DomainParticipantFactory_var dpf_ = DDS::DomainParticipantFactory::get_instance();
if (!dpf_) {
printf(" create_node() could not get participant factory\n");
throw std::runtime_error("could not get participant factory");
};
DDS::DomainId_t domain = 0;
std::cout << " create_node() create_participant in domain " << domain << std::endl;
DDS::DomainParticipant * participant = dpf_->create_participant(
domain, PARTICIPANT_QOS_DEFAULT, NULL,
DDS::STATUS_MASK_NONE);
if (!participant) {
printf(" create_node() could not create participant\n");
throw std::runtime_error("could not create participant");
};
std::cout << " create_node() pass opaque node handle" << std::endl;
ros_middleware_interface::NodeHandle node_handle = {
_prismtech_opensplice_identifier,
participant
};
return node_handle;
}
struct CustomPublisherInfo {
DDS::DataWriter * topic_writer_;
ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks_;
};
ros_middleware_interface::PublisherHandle create_publisher(const ros_middleware_interface::NodeHandle& node_handle, const rosidl_generator_cpp::MessageTypeSupportHandle & type_support_handle, const char * topic_name)
{
std::cout << "create_publisher()" << std::endl;
if (node_handle._implementation_identifier != _prismtech_opensplice_identifier)
{
printf("node handle not from this implementation\n");
printf("but from: %s\n", node_handle._implementation_identifier);
throw std::runtime_error("node handle not from this implementation");
}
std::cout << "create_publisher() " << node_handle._implementation_identifier << std::endl;
std::cout << " create_publisher() extract participant from opaque node handle" << std::endl;
DDS::DomainParticipant * participant = (DDS::DomainParticipant *)node_handle._data;
ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks = (ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks*)type_support_handle._data;
std::string type_name = std::string(callbacks->_package_name) + "::dds_::" + callbacks->_message_name + "_";
std::cout << " create_publisher() invoke register callback" << std::endl;
callbacks->_register_type(participant, type_name.c_str());
DDS::PublisherQos publisher_qos;
DDS::ReturnCode_t status = participant->get_default_publisher_qos(publisher_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_publisher_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default publisher qos failed");
};
std::cout << " create_publisher() create dds publisher" << std::endl;
DDS::Publisher * dds_publisher = participant->create_publisher(
publisher_qos, NULL, DDS::STATUS_MASK_NONE);
if (!dds_publisher) {
printf(" create_publisher() could not create publisher\n");
throw std::runtime_error("could not create publisher");
};
DDS::TopicQos default_topic_qos;
status = participant->get_default_topic_qos(default_topic_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_topic_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default topic qos failed");
};
std::cout << " create_publisher() create topic" << std::endl;
DDS::Topic * topic = participant->create_topic(
topic_name, type_name.c_str(), default_topic_qos, NULL,
DDS::STATUS_MASK_NONE
);
if (!topic) {
printf(" create_topic() could not create topic\n");
throw std::runtime_error("could not create topic");
};
DDS::DataWriterQos default_datawriter_qos;
status = dds_publisher->get_default_datawriter_qos(default_datawriter_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_datawriter_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default datawriter qos failed");
};
std::cout << " create_publisher() create data writer" << std::endl;
DDS::DataWriter * topic_writer = dds_publisher->create_datawriter(
topic, default_datawriter_qos,
NULL, DDS::STATUS_MASK_NONE);
std::cout << " create_publisher() build opaque publisher handle" << std::endl;
CustomPublisherInfo* custom_publisher_info = new CustomPublisherInfo();
custom_publisher_info->topic_writer_ = topic_writer;
custom_publisher_info->callbacks_ = callbacks;
ros_middleware_interface::PublisherHandle publisher_handle = {
_prismtech_opensplice_identifier,
custom_publisher_info
};
return publisher_handle;
}
void publish(const ros_middleware_interface::PublisherHandle& publisher_handle, const void * ros_message)
{
//std::cout << "publish()" << std::endl;
if (publisher_handle._implementation_identifier != _prismtech_opensplice_identifier)
{
printf("publisher handle not from this implementation\n");
printf("but from: %s\n", publisher_handle._implementation_identifier);
throw std::runtime_error("publisher handle not from this implementation");
}
//std::cout << " publish() extract data writer and type code from opaque publisher handle" << std::endl;
CustomPublisherInfo * custom_publisher_info = (CustomPublisherInfo*)publisher_handle._data;
DDS::DataWriter * topic_writer = custom_publisher_info->topic_writer_;
const ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks = custom_publisher_info->callbacks_;
//std::cout << " publish() invoke publish callback" << std::endl;
callbacks->_publish(topic_writer, ros_message);
}
struct CustomSubscriberInfo {
DDS::DataReader * topic_reader_;
ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks_;
};
ros_middleware_interface::SubscriberHandle create_subscriber(const NodeHandle& node_handle, const rosidl_generator_cpp::MessageTypeSupportHandle & type_support_handle, const char * topic_name)
{
std::cout << "create_subscriber()" << std::endl;
if (node_handle._implementation_identifier != _prismtech_opensplice_identifier)
{
printf("node handle not from this implementation\n");
printf("but from: %s\n", node_handle._implementation_identifier);
throw std::runtime_error("node handle not from this implementation");
}
std::cout << "create_subscriber() " << node_handle._implementation_identifier << std::endl;
std::cout << " create_subscriber() extract participant from opaque node handle" << std::endl;
DDS::DomainParticipant * participant = (DDS::DomainParticipant *)node_handle._data;
ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks = (ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks*)type_support_handle._data;
std::string type_name = std::string(callbacks->_package_name) + "::dds_::" + callbacks->_message_name + "_";
std::cout << " create_subscriber() invoke register callback" << std::endl;
callbacks->_register_type(participant, type_name.c_str());
DDS::SubscriberQos subscriber_qos;
DDS::ReturnCode_t status = participant->get_default_subscriber_qos(subscriber_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_subscriber_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default subscriber qos failed");
};
std::cout << " create_subscriber() create dds subscriber" << std::endl;
DDS::Subscriber * dds_subscriber = participant->create_subscriber(
subscriber_qos, NULL, DDS::STATUS_MASK_NONE);
if (!dds_subscriber) {
printf(" create_subscriber() could not create subscriber\n");
throw std::runtime_error("could not create subscriber");
};
DDS::TopicQos default_topic_qos;
status = participant->get_default_topic_qos(default_topic_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_topic_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default topic qos failed");
};
std::cout << " create_subscriber() create topic" << std::endl;
DDS::Topic * topic = participant->create_topic(
topic_name, type_name.c_str(), default_topic_qos, NULL,
DDS::STATUS_MASK_NONE
);
if (!topic) {
printf(" create_topic() could not create topic\n");
throw std::runtime_error("could not create topic");
};
DDS::DataReaderQos default_datareader_qos;
status = dds_subscriber->get_default_datareader_qos(default_datareader_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_datareader_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default datareader qos failed");
};
std::cout << " create_subscriber() create data reader" << std::endl;
DDS::DataReader * topic_reader = dds_subscriber->create_datareader(
topic, default_datareader_qos,
NULL, DDS::STATUS_MASK_NONE);
std::cout << " topic reader" << topic_reader << std::endl;
std::cout << " create_subscriber() build opaque subscriber handle" << std::endl;
CustomSubscriberInfo* custom_subscriber_info = new CustomSubscriberInfo();
custom_subscriber_info->topic_reader_ = topic_reader;
custom_subscriber_info->callbacks_ = callbacks;
ros_middleware_interface::SubscriberHandle subscriber_handle = {
_prismtech_opensplice_identifier,
custom_subscriber_info
};
return subscriber_handle;
}
bool take(const ros_middleware_interface::SubscriberHandle& subscriber_handle, void * ros_message)
{
if (subscriber_handle.implementation_identifier_ != _prismtech_opensplice_identifier)
{
printf("subscriber handle not from this implementation\n");
printf("but from: %s\n", subscriber_handle.implementation_identifier_);
throw std::runtime_error("subscriber handle not from this implementation");
}
//std::cout << " take() extract data writer and type code from opaque subscriber handle" << std::endl;
CustomSubscriberInfo * custom_subscriber_info = (CustomSubscriberInfo*)subscriber_handle.data_;
DDS::DataReader * topic_reader = custom_subscriber_info->topic_reader_;
const ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks = custom_subscriber_info->callbacks_;
return callbacks->_take(topic_reader, ros_message);
}
ros_middleware_interface::GuardConditionHandle create_guard_condition()
{
ros_middleware_interface::GuardConditionHandle guard_condition_handle;
guard_condition_handle.implementation_identifier_ = _prismtech_opensplice_identifier;
guard_condition_handle.data_ = new DDS::GuardCondition();
return guard_condition_handle;
}
void trigger_guard_condition(const ros_middleware_interface::GuardConditionHandle& guard_condition_handle)
{
if (guard_condition_handle.implementation_identifier_ != _prismtech_opensplice_identifier)
{
printf("guard condition handle not from this implementation\n");
printf("but from: %s\n", guard_condition_handle.implementation_identifier_);
throw std::runtime_error("guard condition handle not from this implementation");
}
DDS::GuardCondition * guard_condition = (DDS::GuardCondition*)guard_condition_handle.data_;
guard_condition->set_trigger_value(true);
}
void wait(ros_middleware_interface::SubscriberHandles& subscriber_handles, ros_middleware_interface::GuardConditionHandles& guard_condition_handles)
{
DDS::WaitSet waitset;
// add a condition for each subscriber
for (unsigned long i = 0; i < subscriber_handles.subscriber_count_; ++i)
{
void * data = subscriber_handles.subscribers_[i];
CustomSubscriberInfo * custom_subscriber_info = (CustomSubscriberInfo*)data;
DDS::DataReader * topic_reader = custom_subscriber_info->topic_reader_;
DDS::StatusCondition * condition = topic_reader->get_statuscondition();
condition->set_enabled_statuses(DDS::DATA_AVAILABLE_STATUS);
waitset.attach_condition(condition);
}
// add a condition for each guard condition
for (unsigned long i = 0; i < guard_condition_handles.guard_condition_count_; ++i)
{
void * data = guard_condition_handles.guard_conditions_[i];
DDS::GuardCondition * guard_condition = (DDS::GuardCondition*)data;
waitset.attach_condition(guard_condition);
}
// invoke wait until one of the conditions triggers
DDS::ConditionSeq active_conditions;
DDS::Duration_t timeout;
timeout.sec = 1;
DDS::ReturnCode_t status = DDS::RETCODE_TIMEOUT;
while (DDS::RETCODE_TIMEOUT == status)
{
status = waitset.wait(active_conditions, timeout);
if (DDS::RETCODE_TIMEOUT == status) {
continue;
};
if (status != DDS::RETCODE_OK) {
printf("wait() failed. Status = %d\n", status);
throw std::runtime_error("wait failed");
};
}
// set subscriber handles to zero for all not triggered conditions
for (unsigned long i = 0; i < subscriber_handles.subscriber_count_; ++i)
{
void * data = subscriber_handles.subscribers_[i];
CustomSubscriberInfo * custom_subscriber_info = (CustomSubscriberInfo*)data;
DDS::DataReader* topic_reader = custom_subscriber_info->topic_reader_;
DDS::StatusCondition * condition = topic_reader->get_statuscondition();
// search for subscriber condition in active set
unsigned long j = 0;
for (; j < active_conditions.length(); ++j)
{
if (active_conditions[j] == condition)
{
break;
}
}
// if subscriber condition is not found in the active set
// reset the subscriber handle
if (!(j < active_conditions.length()))
{
subscriber_handles.subscribers_[i] = 0;
}
}
// set subscriber handles to zero for all not triggered conditions
for (unsigned long i = 0; i < guard_condition_handles.guard_condition_count_; ++i)
{
void * data = guard_condition_handles.guard_conditions_[i];
DDS::Condition * condition = (DDS::Condition*)data;
// search for guard condition in active set
unsigned long j = 0;
for (; j < active_conditions.length(); ++j)
{
if (active_conditions[j] == condition)
{
break;
}
}
// if guard condition is not found in the active set
// reset the guard handle
if (!(j < active_conditions.length()))
{
guard_condition_handles.guard_conditions_[i] = 0;
}
}
}
}
<commit_msg>add non-blocking flag to wait<commit_after>#include <iostream>
#include <stdexcept>
#include <ccpp_dds_dcps.h>
#include "rosidl_generator_cpp/MessageTypeSupport.h"
#include "ros_middleware_interface/handles.h"
#include "ros_middleware_opensplice_cpp/MessageTypeSupport.h"
namespace ros_middleware_interface
{
const char * _prismtech_opensplice_identifier = "opensplice_static";
ros_middleware_interface::NodeHandle create_node()
{
std::cout << "create_node()" << std::endl;
std::cout << " create_node() get_instance" << std::endl;
DDS::DomainParticipantFactory_var dpf_ = DDS::DomainParticipantFactory::get_instance();
if (!dpf_) {
printf(" create_node() could not get participant factory\n");
throw std::runtime_error("could not get participant factory");
};
DDS::DomainId_t domain = 0;
std::cout << " create_node() create_participant in domain " << domain << std::endl;
DDS::DomainParticipant * participant = dpf_->create_participant(
domain, PARTICIPANT_QOS_DEFAULT, NULL,
DDS::STATUS_MASK_NONE);
if (!participant) {
printf(" create_node() could not create participant\n");
throw std::runtime_error("could not create participant");
};
std::cout << " create_node() pass opaque node handle" << std::endl;
ros_middleware_interface::NodeHandle node_handle = {
_prismtech_opensplice_identifier,
participant
};
return node_handle;
}
struct CustomPublisherInfo {
DDS::DataWriter * topic_writer_;
ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks_;
};
ros_middleware_interface::PublisherHandle create_publisher(const ros_middleware_interface::NodeHandle& node_handle, const rosidl_generator_cpp::MessageTypeSupportHandle & type_support_handle, const char * topic_name)
{
std::cout << "create_publisher()" << std::endl;
if (node_handle._implementation_identifier != _prismtech_opensplice_identifier)
{
printf("node handle not from this implementation\n");
printf("but from: %s\n", node_handle._implementation_identifier);
throw std::runtime_error("node handle not from this implementation");
}
std::cout << "create_publisher() " << node_handle._implementation_identifier << std::endl;
std::cout << " create_publisher() extract participant from opaque node handle" << std::endl;
DDS::DomainParticipant * participant = (DDS::DomainParticipant *)node_handle._data;
ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks = (ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks*)type_support_handle._data;
std::string type_name = std::string(callbacks->_package_name) + "::dds_::" + callbacks->_message_name + "_";
std::cout << " create_publisher() invoke register callback" << std::endl;
callbacks->_register_type(participant, type_name.c_str());
DDS::PublisherQos publisher_qos;
DDS::ReturnCode_t status = participant->get_default_publisher_qos(publisher_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_publisher_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default publisher qos failed");
};
std::cout << " create_publisher() create dds publisher" << std::endl;
DDS::Publisher * dds_publisher = participant->create_publisher(
publisher_qos, NULL, DDS::STATUS_MASK_NONE);
if (!dds_publisher) {
printf(" create_publisher() could not create publisher\n");
throw std::runtime_error("could not create publisher");
};
DDS::TopicQos default_topic_qos;
status = participant->get_default_topic_qos(default_topic_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_topic_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default topic qos failed");
};
std::cout << " create_publisher() create topic" << std::endl;
DDS::Topic * topic = participant->create_topic(
topic_name, type_name.c_str(), default_topic_qos, NULL,
DDS::STATUS_MASK_NONE
);
if (!topic) {
printf(" create_topic() could not create topic\n");
throw std::runtime_error("could not create topic");
};
DDS::DataWriterQos default_datawriter_qos;
status = dds_publisher->get_default_datawriter_qos(default_datawriter_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_datawriter_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default datawriter qos failed");
};
std::cout << " create_publisher() create data writer" << std::endl;
DDS::DataWriter * topic_writer = dds_publisher->create_datawriter(
topic, default_datawriter_qos,
NULL, DDS::STATUS_MASK_NONE);
std::cout << " create_publisher() build opaque publisher handle" << std::endl;
CustomPublisherInfo* custom_publisher_info = new CustomPublisherInfo();
custom_publisher_info->topic_writer_ = topic_writer;
custom_publisher_info->callbacks_ = callbacks;
ros_middleware_interface::PublisherHandle publisher_handle = {
_prismtech_opensplice_identifier,
custom_publisher_info
};
return publisher_handle;
}
void publish(const ros_middleware_interface::PublisherHandle& publisher_handle, const void * ros_message)
{
//std::cout << "publish()" << std::endl;
if (publisher_handle._implementation_identifier != _prismtech_opensplice_identifier)
{
printf("publisher handle not from this implementation\n");
printf("but from: %s\n", publisher_handle._implementation_identifier);
throw std::runtime_error("publisher handle not from this implementation");
}
//std::cout << " publish() extract data writer and type code from opaque publisher handle" << std::endl;
CustomPublisherInfo * custom_publisher_info = (CustomPublisherInfo*)publisher_handle._data;
DDS::DataWriter * topic_writer = custom_publisher_info->topic_writer_;
const ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks = custom_publisher_info->callbacks_;
//std::cout << " publish() invoke publish callback" << std::endl;
callbacks->_publish(topic_writer, ros_message);
}
struct CustomSubscriberInfo {
DDS::DataReader * topic_reader_;
ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks_;
};
ros_middleware_interface::SubscriberHandle create_subscriber(const NodeHandle& node_handle, const rosidl_generator_cpp::MessageTypeSupportHandle & type_support_handle, const char * topic_name)
{
std::cout << "create_subscriber()" << std::endl;
if (node_handle._implementation_identifier != _prismtech_opensplice_identifier)
{
printf("node handle not from this implementation\n");
printf("but from: %s\n", node_handle._implementation_identifier);
throw std::runtime_error("node handle not from this implementation");
}
std::cout << "create_subscriber() " << node_handle._implementation_identifier << std::endl;
std::cout << " create_subscriber() extract participant from opaque node handle" << std::endl;
DDS::DomainParticipant * participant = (DDS::DomainParticipant *)node_handle._data;
ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks = (ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks*)type_support_handle._data;
std::string type_name = std::string(callbacks->_package_name) + "::dds_::" + callbacks->_message_name + "_";
std::cout << " create_subscriber() invoke register callback" << std::endl;
callbacks->_register_type(participant, type_name.c_str());
DDS::SubscriberQos subscriber_qos;
DDS::ReturnCode_t status = participant->get_default_subscriber_qos(subscriber_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_subscriber_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default subscriber qos failed");
};
std::cout << " create_subscriber() create dds subscriber" << std::endl;
DDS::Subscriber * dds_subscriber = participant->create_subscriber(
subscriber_qos, NULL, DDS::STATUS_MASK_NONE);
if (!dds_subscriber) {
printf(" create_subscriber() could not create subscriber\n");
throw std::runtime_error("could not create subscriber");
};
DDS::TopicQos default_topic_qos;
status = participant->get_default_topic_qos(default_topic_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_topic_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default topic qos failed");
};
std::cout << " create_subscriber() create topic" << std::endl;
DDS::Topic * topic = participant->create_topic(
topic_name, type_name.c_str(), default_topic_qos, NULL,
DDS::STATUS_MASK_NONE
);
if (!topic) {
printf(" create_topic() could not create topic\n");
throw std::runtime_error("could not create topic");
};
DDS::DataReaderQos default_datareader_qos;
status = dds_subscriber->get_default_datareader_qos(default_datareader_qos);
if (status != DDS::RETCODE_OK) {
printf("get_default_datareader_qos() failed. Status = %d\n", status);
throw std::runtime_error("get default datareader qos failed");
};
std::cout << " create_subscriber() create data reader" << std::endl;
DDS::DataReader * topic_reader = dds_subscriber->create_datareader(
topic, default_datareader_qos,
NULL, DDS::STATUS_MASK_NONE);
std::cout << " topic reader" << topic_reader << std::endl;
std::cout << " create_subscriber() build opaque subscriber handle" << std::endl;
CustomSubscriberInfo* custom_subscriber_info = new CustomSubscriberInfo();
custom_subscriber_info->topic_reader_ = topic_reader;
custom_subscriber_info->callbacks_ = callbacks;
ros_middleware_interface::SubscriberHandle subscriber_handle = {
_prismtech_opensplice_identifier,
custom_subscriber_info
};
return subscriber_handle;
}
bool take(const ros_middleware_interface::SubscriberHandle& subscriber_handle, void * ros_message)
{
if (subscriber_handle.implementation_identifier_ != _prismtech_opensplice_identifier)
{
printf("subscriber handle not from this implementation\n");
printf("but from: %s\n", subscriber_handle.implementation_identifier_);
throw std::runtime_error("subscriber handle not from this implementation");
}
//std::cout << " take() extract data writer and type code from opaque subscriber handle" << std::endl;
CustomSubscriberInfo * custom_subscriber_info = (CustomSubscriberInfo*)subscriber_handle.data_;
DDS::DataReader * topic_reader = custom_subscriber_info->topic_reader_;
const ros_middleware_opensplice_cpp::MessageTypeSupportCallbacks * callbacks = custom_subscriber_info->callbacks_;
return callbacks->_take(topic_reader, ros_message);
}
ros_middleware_interface::GuardConditionHandle create_guard_condition()
{
ros_middleware_interface::GuardConditionHandle guard_condition_handle;
guard_condition_handle.implementation_identifier_ = _prismtech_opensplice_identifier;
guard_condition_handle.data_ = new DDS::GuardCondition();
return guard_condition_handle;
}
void trigger_guard_condition(const ros_middleware_interface::GuardConditionHandle& guard_condition_handle)
{
if (guard_condition_handle.implementation_identifier_ != _prismtech_opensplice_identifier)
{
printf("guard condition handle not from this implementation\n");
printf("but from: %s\n", guard_condition_handle.implementation_identifier_);
throw std::runtime_error("guard condition handle not from this implementation");
}
DDS::GuardCondition * guard_condition = (DDS::GuardCondition*)guard_condition_handle.data_;
guard_condition->set_trigger_value(true);
}
void wait(ros_middleware_interface::SubscriberHandles& subscriber_handles, ros_middleware_interface::GuardConditionHandles& guard_condition_handles, bool non_blocking)
{
DDS::WaitSet waitset;
// add a condition for each subscriber
for (unsigned long i = 0; i < subscriber_handles.subscriber_count_; ++i)
{
void * data = subscriber_handles.subscribers_[i];
CustomSubscriberInfo * custom_subscriber_info = (CustomSubscriberInfo*)data;
DDS::DataReader * topic_reader = custom_subscriber_info->topic_reader_;
DDS::StatusCondition * condition = topic_reader->get_statuscondition();
condition->set_enabled_statuses(DDS::DATA_AVAILABLE_STATUS);
waitset.attach_condition(condition);
}
// add a condition for each guard condition
for (unsigned long i = 0; i < guard_condition_handles.guard_condition_count_; ++i)
{
void * data = guard_condition_handles.guard_conditions_[i];
DDS::GuardCondition * guard_condition = (DDS::GuardCondition*)data;
waitset.attach_condition(guard_condition);
}
// invoke wait until one of the conditions triggers
DDS::ConditionSeq active_conditions;
DDS::Duration_t timeout;
timeout.sec = non_blocking ? 0 : 1;
DDS::ReturnCode_t status = DDS::RETCODE_TIMEOUT;
while (DDS::RETCODE_TIMEOUT == status)
{
status = waitset.wait(active_conditions, timeout);
if (DDS::RETCODE_TIMEOUT == status) {
if (non_blocking)
{
break;
}
continue;
};
if (status != DDS::RETCODE_OK) {
printf("wait() failed. Status = %d\n", status);
throw std::runtime_error("wait failed");
};
}
// set subscriber handles to zero for all not triggered conditions
for (unsigned long i = 0; i < subscriber_handles.subscriber_count_; ++i)
{
void * data = subscriber_handles.subscribers_[i];
CustomSubscriberInfo * custom_subscriber_info = (CustomSubscriberInfo*)data;
DDS::DataReader* topic_reader = custom_subscriber_info->topic_reader_;
DDS::StatusCondition * condition = topic_reader->get_statuscondition();
// search for subscriber condition in active set
unsigned long j = 0;
for (; j < active_conditions.length(); ++j)
{
if (active_conditions[j] == condition)
{
break;
}
}
// if subscriber condition is not found in the active set
// reset the subscriber handle
if (!(j < active_conditions.length()))
{
subscriber_handles.subscribers_[i] = 0;
}
}
// set subscriber handles to zero for all not triggered conditions
for (unsigned long i = 0; i < guard_condition_handles.guard_condition_count_; ++i)
{
void * data = guard_condition_handles.guard_conditions_[i];
DDS::Condition * condition = (DDS::Condition*)data;
// search for guard condition in active set
unsigned long j = 0;
for (; j < active_conditions.length(); ++j)
{
if (active_conditions[j] == condition)
{
break;
}
}
// if guard condition is not found in the active set
// reset the guard handle
if (!(j < active_conditions.length()))
{
guard_condition_handles.guard_conditions_[i] = 0;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2019 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 "perfetto/ext/base/subprocess.h"
#if PERFETTO_HAS_SUBPROCESS()
#include <thread>
#include <signal.h>
#include <sys/stat.h>
#include <unistd.h>
#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/temp_file.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace base {
namespace {
std::string GenLargeString() {
std::string contents;
for (int i = 0; i < 4096; i++) {
contents += "very long text " + std::to_string(i) + "\n";
}
// Make sure that |contents| is > the default pipe buffer on Linux (4 pages).
PERFETTO_DCHECK(contents.size() > 4096 * 4);
return contents;
}
TEST(SubprocessTest, InvalidPath) {
Subprocess p({"/usr/bin/invalid_1337"});
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 128);
EXPECT_EQ(p.output(), "execve() failed\n");
}
TEST(SubprocessTest, StdoutOnly) {
Subprocess p({"sh", "-c", "(echo skip_err >&2); echo out_only"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.stderr_mode = Subprocess::kDevNull;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.output(), "out_only\n");
}
TEST(SubprocessTest, StderrOnly) {
Subprocess p({"sh", "-c", "(echo err_only >&2); echo skip_out"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), "err_only\n");
}
TEST(SubprocessTest, BothStdoutAndStderr) {
Subprocess p({"sh", "-c", "echo out; (echo err >&2); echo out2"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.stderr_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), "out\nerr\nout2\n");
}
TEST(SubprocessTest, BinTrue) {
Subprocess p({"true"});
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
TEST(SubprocessTest, BinFalse) {
Subprocess p({"false"});
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 1);
}
TEST(SubprocessTest, Echo) {
Subprocess p({"echo", "-n", "foobar"});
p.args.stdout_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
EXPECT_EQ(p.output(), "foobar");
}
TEST(SubprocessTest, FeedbackLongInput) {
std::string contents = GenLargeString();
Subprocess p({"cat", "-"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.input = contents;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
EXPECT_EQ(p.output(), contents);
}
TEST(SubprocessTest, CatLargeFile) {
std::string contents = GenLargeString();
TempFile tf = TempFile::Create();
WriteAll(tf.fd(), contents.data(), contents.size());
FlushFile(tf.fd());
Subprocess p({"cat", tf.path().c_str()});
p.args.stdout_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), contents);
}
TEST(SubprocessTest, Timeout) {
Subprocess p({"sleep", "60"});
EXPECT_FALSE(p.Call(/*timeout_ms=*/1));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, TimeoutNotHit) {
Subprocess p({"sleep", "0.01"});
EXPECT_TRUE(p.Call(/*timeout_ms=*/100000));
}
TEST(SubprocessTest, TimeoutStopOutput) {
Subprocess p({"sh", "-c", "while true; do echo stuff; done"});
p.args.stdout_mode = Subprocess::kDevNull;
EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, ExitBeforeReadingStdin) {
// 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
Subprocess p({"sh", "-c", "sleep 0.01"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kDevNull;
p.args.input = GenLargeString();
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
TEST(SubprocessTest, StdinWriteStall) {
// 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
// This causes a situation where the write on the stdin will stall because
// nobody reads it and the pipe buffer fills up. In this situation we should
// still handle the timeout properly.
Subprocess p({"sh", "-c", "sleep 10"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kDevNull;
p.args.input = GenLargeString();
EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, StartAndWait) {
Subprocess p({"sleep", "1000"});
p.Start();
EXPECT_EQ(p.Poll(), Subprocess::kRunning);
p.KillAndWaitForTermination();
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.Poll(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.returncode(), 128 + SIGKILL);
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) && defined(ADDRESS_SANITIZER)
#define MAYBE_PollBehavesProperly DISABLED_PollBehavesProperly
#else
#define MAYBE_PollBehavesProperly PollBehavesProperly
#endif
// TODO(b/158484911): Re-enable once problem is fixed.
TEST(SubprocessTest, MAYBE_PollBehavesProperly) {
Subprocess p({"sh", "-c", "echo foobar"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.input = "ignored";
p.Start();
// Here we use kill() as a way to tell if the process is still running.
// SIGWINCH is ignored by default.
while (kill(p.pid(), SIGWINCH) == 0) {
usleep(1000);
}
// At this point Poll() must detect the termination.
EXPECT_EQ(p.Poll(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
// Test the case of passing a lambda in |entrypoint| but no cmd.c
TEST(SubprocessTest, Entrypoint) {
Subprocess p;
p.args.input = "ping\n";
p.args.stdout_mode = Subprocess::kBuffer;
p.args.entrypoint_for_testing = [] {
char buf[32]{};
PERFETTO_CHECK(fgets(buf, sizeof(buf), stdin));
PERFETTO_CHECK(strcmp(buf, "ping\n") == 0);
printf("pong\n");
fflush(stdout);
_exit(42);
};
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.returncode(), 42);
EXPECT_EQ(p.output(), "pong\n");
}
// Test the case of passing both a lambda entrypoint and a process to exec.
TEST(SubprocessTest, EntrypointAndExec) {
base::Pipe pipe1 = base::Pipe::Create();
base::Pipe pipe2 = base::Pipe::Create();
int pipe1_wr = *pipe1.wr;
int pipe2_wr = *pipe2.wr;
Subprocess p({"echo", "123"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.preserve_fds.push_back(pipe2_wr);
p.args.entrypoint_for_testing = [pipe1_wr, pipe2_wr] {
base::ignore_result(write(pipe1_wr, "fail", 4));
base::ignore_result(write(pipe2_wr, "pass", 4));
};
p.Start();
pipe1.wr.reset();
pipe2.wr.reset();
char buf[8];
EXPECT_LE(read(*pipe1.rd, buf, sizeof(buf)), 0);
EXPECT_EQ(read(*pipe2.rd, buf, sizeof(buf)), 4);
buf[4] = '\0';
EXPECT_STREQ(buf, "pass");
EXPECT_TRUE(p.Wait());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.output(), "123\n");
}
TEST(SubprocessTest, Wait) {
Subprocess p({"sleep", "10000"});
p.Start();
for (int i = 0; i < 3; i++) {
EXPECT_FALSE(p.Wait(1 /*ms*/));
EXPECT_EQ(p.status(), Subprocess::kRunning);
}
kill(p.pid(), SIGBUS);
EXPECT_TRUE(p.Wait(30000 /*ms*/));
EXPECT_TRUE(p.Wait()); // Should be a no-op.
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.returncode(), 128 + SIGBUS);
}
TEST(SubprocessTest, KillOnDtor) {
// Here we use kill(SIGWINCH) as a way to tell if the process is still alive.
// SIGWINCH is one of the few signals that has default ignore disposition.
int pid;
{
Subprocess p({"sleep", "10000"});
p.Start();
pid = p.pid();
EXPECT_EQ(kill(pid, SIGWINCH), 0);
}
EXPECT_EQ(kill(pid, SIGWINCH), -1);
}
// Regression test for b/162505491.
TEST(SubprocessTest, MoveOperators) {
{
Subprocess initial = Subprocess({"sleep", "10000"});
initial.Start();
Subprocess moved(std::move(initial));
EXPECT_EQ(moved.Poll(), Subprocess::kRunning);
EXPECT_EQ(initial.Poll(), Subprocess::kNotStarted);
// Check that reuse works
initial = Subprocess({"echo", "-n", "hello"});
initial.args.stdout_mode = Subprocess::OutputMode::kBuffer;
initial.Start();
initial.Wait(/*timeout=*/5000);
EXPECT_EQ(initial.status(), Subprocess::kExited);
EXPECT_EQ(initial.returncode(), 0);
EXPECT_EQ(initial.output(), "hello");
}
std::vector<Subprocess> v;
for (int i = 0; i < 10; i++) {
v.emplace_back(Subprocess({"sleep", "10"}));
v.back().Start();
}
for (auto& p : v)
EXPECT_EQ(p.Poll(), Subprocess::kRunning);
}
} // namespace
} // namespace base
} // namespace perfetto
#endif // PERFETTO_HAS_SUBPROCESS()
<commit_msg>Disable PollBehavesProperly without ASAN. am: cc15f34289 am: 70d007ec85 am: 34de5564c1<commit_after>/*
* Copyright (C) 2019 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 "perfetto/ext/base/subprocess.h"
#if PERFETTO_HAS_SUBPROCESS()
#include <thread>
#include <signal.h>
#include <sys/stat.h>
#include <unistd.h>
#include "perfetto/ext/base/file_utils.h"
#include "perfetto/ext/base/temp_file.h"
#include "test/gtest_and_gmock.h"
namespace perfetto {
namespace base {
namespace {
std::string GenLargeString() {
std::string contents;
for (int i = 0; i < 4096; i++) {
contents += "very long text " + std::to_string(i) + "\n";
}
// Make sure that |contents| is > the default pipe buffer on Linux (4 pages).
PERFETTO_DCHECK(contents.size() > 4096 * 4);
return contents;
}
TEST(SubprocessTest, InvalidPath) {
Subprocess p({"/usr/bin/invalid_1337"});
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 128);
EXPECT_EQ(p.output(), "execve() failed\n");
}
TEST(SubprocessTest, StdoutOnly) {
Subprocess p({"sh", "-c", "(echo skip_err >&2); echo out_only"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.stderr_mode = Subprocess::kDevNull;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.output(), "out_only\n");
}
TEST(SubprocessTest, StderrOnly) {
Subprocess p({"sh", "-c", "(echo err_only >&2); echo skip_out"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), "err_only\n");
}
TEST(SubprocessTest, BothStdoutAndStderr) {
Subprocess p({"sh", "-c", "echo out; (echo err >&2); echo out2"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.stderr_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), "out\nerr\nout2\n");
}
TEST(SubprocessTest, BinTrue) {
Subprocess p({"true"});
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
TEST(SubprocessTest, BinFalse) {
Subprocess p({"false"});
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 1);
}
TEST(SubprocessTest, Echo) {
Subprocess p({"echo", "-n", "foobar"});
p.args.stdout_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
EXPECT_EQ(p.output(), "foobar");
}
TEST(SubprocessTest, FeedbackLongInput) {
std::string contents = GenLargeString();
Subprocess p({"cat", "-"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.input = contents;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
EXPECT_EQ(p.output(), contents);
}
TEST(SubprocessTest, CatLargeFile) {
std::string contents = GenLargeString();
TempFile tf = TempFile::Create();
WriteAll(tf.fd(), contents.data(), contents.size());
FlushFile(tf.fd());
Subprocess p({"cat", tf.path().c_str()});
p.args.stdout_mode = Subprocess::kBuffer;
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.output(), contents);
}
TEST(SubprocessTest, Timeout) {
Subprocess p({"sleep", "60"});
EXPECT_FALSE(p.Call(/*timeout_ms=*/1));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, TimeoutNotHit) {
Subprocess p({"sleep", "0.01"});
EXPECT_TRUE(p.Call(/*timeout_ms=*/100000));
}
TEST(SubprocessTest, TimeoutStopOutput) {
Subprocess p({"sh", "-c", "while true; do echo stuff; done"});
p.args.stdout_mode = Subprocess::kDevNull;
EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, ExitBeforeReadingStdin) {
// 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
Subprocess p({"sh", "-c", "sleep 0.01"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kDevNull;
p.args.input = GenLargeString();
EXPECT_TRUE(p.Call());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
TEST(SubprocessTest, StdinWriteStall) {
// 'sh -c' is to avoid closing stdin (sleep closes it before sleeping).
// This causes a situation where the write on the stdin will stall because
// nobody reads it and the pipe buffer fills up. In this situation we should
// still handle the timeout properly.
Subprocess p({"sh", "-c", "sleep 10"});
p.args.stdout_mode = Subprocess::kDevNull;
p.args.stderr_mode = Subprocess::kDevNull;
p.args.input = GenLargeString();
EXPECT_FALSE(p.Call(/*timeout_ms=*/10));
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
}
TEST(SubprocessTest, StartAndWait) {
Subprocess p({"sleep", "1000"});
p.Start();
EXPECT_EQ(p.Poll(), Subprocess::kRunning);
p.KillAndWaitForTermination();
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.Poll(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.returncode(), 128 + SIGKILL);
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_PollBehavesProperly DISABLED_PollBehavesProperly
#else
#define MAYBE_PollBehavesProperly PollBehavesProperly
#endif
// TODO(b/158484911): Re-enable once problem is fixed.
TEST(SubprocessTest, MAYBE_PollBehavesProperly) {
Subprocess p({"sh", "-c", "echo foobar"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.input = "ignored";
p.Start();
// Here we use kill() as a way to tell if the process is still running.
// SIGWINCH is ignored by default.
while (kill(p.pid(), SIGWINCH) == 0) {
usleep(1000);
}
// At this point Poll() must detect the termination.
EXPECT_EQ(p.Poll(), Subprocess::kExited);
EXPECT_EQ(p.returncode(), 0);
}
// Test the case of passing a lambda in |entrypoint| but no cmd.c
TEST(SubprocessTest, Entrypoint) {
Subprocess p;
p.args.input = "ping\n";
p.args.stdout_mode = Subprocess::kBuffer;
p.args.entrypoint_for_testing = [] {
char buf[32]{};
PERFETTO_CHECK(fgets(buf, sizeof(buf), stdin));
PERFETTO_CHECK(strcmp(buf, "ping\n") == 0);
printf("pong\n");
fflush(stdout);
_exit(42);
};
EXPECT_FALSE(p.Call());
EXPECT_EQ(p.returncode(), 42);
EXPECT_EQ(p.output(), "pong\n");
}
// Test the case of passing both a lambda entrypoint and a process to exec.
TEST(SubprocessTest, EntrypointAndExec) {
base::Pipe pipe1 = base::Pipe::Create();
base::Pipe pipe2 = base::Pipe::Create();
int pipe1_wr = *pipe1.wr;
int pipe2_wr = *pipe2.wr;
Subprocess p({"echo", "123"});
p.args.stdout_mode = Subprocess::kBuffer;
p.args.preserve_fds.push_back(pipe2_wr);
p.args.entrypoint_for_testing = [pipe1_wr, pipe2_wr] {
base::ignore_result(write(pipe1_wr, "fail", 4));
base::ignore_result(write(pipe2_wr, "pass", 4));
};
p.Start();
pipe1.wr.reset();
pipe2.wr.reset();
char buf[8];
EXPECT_LE(read(*pipe1.rd, buf, sizeof(buf)), 0);
EXPECT_EQ(read(*pipe2.rd, buf, sizeof(buf)), 4);
buf[4] = '\0';
EXPECT_STREQ(buf, "pass");
EXPECT_TRUE(p.Wait());
EXPECT_EQ(p.status(), Subprocess::kExited);
EXPECT_EQ(p.output(), "123\n");
}
TEST(SubprocessTest, Wait) {
Subprocess p({"sleep", "10000"});
p.Start();
for (int i = 0; i < 3; i++) {
EXPECT_FALSE(p.Wait(1 /*ms*/));
EXPECT_EQ(p.status(), Subprocess::kRunning);
}
kill(p.pid(), SIGBUS);
EXPECT_TRUE(p.Wait(30000 /*ms*/));
EXPECT_TRUE(p.Wait()); // Should be a no-op.
EXPECT_EQ(p.status(), Subprocess::kKilledBySignal);
EXPECT_EQ(p.returncode(), 128 + SIGBUS);
}
TEST(SubprocessTest, KillOnDtor) {
// Here we use kill(SIGWINCH) as a way to tell if the process is still alive.
// SIGWINCH is one of the few signals that has default ignore disposition.
int pid;
{
Subprocess p({"sleep", "10000"});
p.Start();
pid = p.pid();
EXPECT_EQ(kill(pid, SIGWINCH), 0);
}
EXPECT_EQ(kill(pid, SIGWINCH), -1);
}
// Regression test for b/162505491.
TEST(SubprocessTest, MoveOperators) {
{
Subprocess initial = Subprocess({"sleep", "10000"});
initial.Start();
Subprocess moved(std::move(initial));
EXPECT_EQ(moved.Poll(), Subprocess::kRunning);
EXPECT_EQ(initial.Poll(), Subprocess::kNotStarted);
// Check that reuse works
initial = Subprocess({"echo", "-n", "hello"});
initial.args.stdout_mode = Subprocess::OutputMode::kBuffer;
initial.Start();
initial.Wait(/*timeout=*/5000);
EXPECT_EQ(initial.status(), Subprocess::kExited);
EXPECT_EQ(initial.returncode(), 0);
EXPECT_EQ(initial.output(), "hello");
}
std::vector<Subprocess> v;
for (int i = 0; i < 10; i++) {
v.emplace_back(Subprocess({"sleep", "10"}));
v.back().Start();
}
for (auto& p : v)
EXPECT_EQ(p.Poll(), Subprocess::kRunning);
}
} // namespace
} // namespace base
} // namespace perfetto
#endif // PERFETTO_HAS_SUBPROCESS()
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <sal/types.h>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "rtl/strbuf.hxx"
#include "rtl/string.h"
#include "rtl/string.hxx"
#include "rtl/textenc.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include <sal/macros.h>
namespace test { namespace oustring {
class StartsWith: public CppUnit::TestFixture
{
private:
void startsWith();
CPPUNIT_TEST_SUITE(StartsWith);
CPPUNIT_TEST(startsWith);
CPPUNIT_TEST_SUITE_END();
};
} }
CPPUNIT_TEST_SUITE_REGISTRATION(test::oustring::StartsWith);
void test::oustring::StartsWith::startsWith()
{
CPPUNIT_ASSERT( rtl::OUString( "foobar" ).startsWith( "foo" ));
CPPUNIT_ASSERT( !rtl::OUString( "foo" ).startsWith( "foobar" ));
CPPUNIT_ASSERT( !rtl::OUString( "foobar" ).startsWith( "oo" ));
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>use new file header, this is actually a new file<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/.
*/
#include <sal/types.h>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include "rtl/ustring.hxx"
namespace test { namespace oustring {
class StartsWith: public CppUnit::TestFixture
{
private:
void startsWith();
CPPUNIT_TEST_SUITE(StartsWith);
CPPUNIT_TEST(startsWith);
CPPUNIT_TEST_SUITE_END();
};
} }
CPPUNIT_TEST_SUITE_REGISTRATION(test::oustring::StartsWith);
void test::oustring::StartsWith::startsWith()
{
CPPUNIT_ASSERT( rtl::OUString( "foobar" ).startsWith( "foo" ));
CPPUNIT_ASSERT( !rtl::OUString( "foo" ).startsWith( "foobar" ));
CPPUNIT_ASSERT( !rtl::OUString( "foobar" ).startsWith( "oo" ));
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>// Copyright 2014 Vinzenz Feenstra
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GUARD_PYPA_PARSER_PARSER_HH_INCLUDED
#define GUARD_PYPA_PARSER_PARSER_HH_INCLUDED
#include <pypa/lexer/lexer.hh>
#include <pypa/ast/ast.hh>
namespace pypa {
struct ParserOptions {
ParserOptions()
: python3only(false)
, python3allowed(false)
{}
bool python3only;
bool python3allowed;
};
class Parser {
public:
bool parse(Lexer & lexer, AstModulePtr & ast, ParserOptions options = ParserOptions());
};
}
#endif // GUARD_PYPA_PARSER_PARSER_HH_INCLUDED
<commit_msg>Added an option for controlling whether or not docstrings should be an own ast element<commit_after>// Copyright 2014 Vinzenz Feenstra
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GUARD_PYPA_PARSER_PARSER_HH_INCLUDED
#define GUARD_PYPA_PARSER_PARSER_HH_INCLUDED
#include <pypa/lexer/lexer.hh>
#include <pypa/ast/ast.hh>
namespace pypa {
struct ParserOptions {
ParserOptions()
: python3only(false)
, python3allowed(false)
, docstrings(true)
{}
bool python3only;
bool python3allowed;
bool docstrings;
};
class Parser {
public:
bool parse(Lexer & lexer, AstModulePtr & ast, ParserOptions options = ParserOptions());
};
}
#endif // GUARD_PYPA_PARSER_PARSER_HH_INCLUDED
<|endoftext|>
|
<commit_before>/*
Imports blocks from bootstrap.dat
bootstrap.dat is the raw blocks in the format
[magic bytes] [block length] [serialized block]
*/
#include <future>
#include <bitcoin/bitcoin.hpp>
using namespace bc;
using std::placeholders::_1;
using std::placeholders::_2;
bool stopped = false;
void signal_handler(int sig)
{
log_info("bootstrap") << "Caught signal: " << sig;
stopped = true;
}
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cout << "usage: bootstrap <blockchain directory> <bootstrap.dat file>" << std::endl;
return 1;
}
const std::string dbpath = argv[1];
const std::string bootstrapfile = argv[2];
// Threadpool context containing 1 thread.
threadpool pool(1);
// leveldb_blockchain operations execute in pool's thread.
leveldb_blockchain chain(pool);
// Completion handler for starting the leveldb_blockchain.
// Does nothing.
auto blockchain_start = [](const std::error_code& ec) {};
// Start blockchain with a database path.
chain.start(dbpath, blockchain_start);
// First block is the genesis block.
block_type first_block = genesis_block();
// Total number of blocks parsed from the bootstrap.dat
int blocks_parsed = 0;
// position of the pointer in the buffer
int buffer_position = 0;
std::promise<std::error_code> ec_promise;
std::promise<block_header_type> blk_header_promise;
auto genesis_block_fetched_handler =
[&ec_promise, &blk_header_promise](const std::error_code& ec,
const block_header_type& header)
{
ec_promise.set_value(ec);
blk_header_promise.set_value(header);
};
// See if we can fetch the genesis block from the leveldb database
chain.fetch_block_header(0, genesis_block_fetched_handler);
std::error_code ec = ec_promise.get_future().get();
block_header_type blk_header = blk_header_promise.get_future().get();
if (ec)
{
//Import the genesis_block() if it does not yet exist in the leveldb
std::promise<std::error_code> ec_promise;
auto genesis_block_imported_handler =
[&ec_promise](const std::error_code& ec)
{
ec_promise.set_value(ec);
};
chain.import(first_block, 0, genesis_block_imported_handler);
ec = ec_promise.get_future().get();
if (ec)
{
log_error() << "Importing genesis block failed: " << ec.message();
return -1;
}
else
log_info() << "Imported genesis block";
}
// If we already have a block stored in the leveldb, check its hash
// matches the one coded into genesis_block()
else
BITCOIN_ASSERT(hash_block_header(blk_header) ==
hash_block_header(first_block.header));
std::ifstream fin(bootstrapfile, std::ios::in | std::ios::binary);
if (!fin)
{
log_error() << "Could not open bootstrap.dat file";
fin.close();
pool.stop();
pool.join();
chain.stop();
return -1;
}
constexpr size_t max_block_size = 1000000;
// Allocate a 2 * max_block_size buffer, so we are sure to read at least
// one full block into the buffer, or many smaller ones.
constexpr size_t buffer_size = 2 * max_block_size;
int block_size;
data_chunk buffer(buffer_size);
// The total size of the block is endian reversed
// This lambda function will read the chunk from its
// first byte at position pos in the buffer and return
// the integer representation of the block size in bytes.
auto get_block_size =
[](const data_chunk& buffer, const int pos)
{
return (int) (buffer[pos + 3] << 24) +
(int) (buffer[pos + 2] << 16) +
(int) (buffer[pos + 1] << 8) +
(int) (buffer[pos]);
};
// This will return false when there are not enough bytes left
// in the file to fill the buffer, meaning we may miss the last block
std::cout << "entering loop" << std::endl;
while(!stopped)
{
std::cout << "started1" << std::endl;
fin.read((char*) &buffer[0], buffer_size);
buffer_position = 0;
std::cout << "started" << std::endl;
while(buffer_position < buffer_size - 8 && !stopped)
{
// Assert we have the magic bytes.
BITCOIN_ASSERT( buffer[buffer_position] == 0xf9 &&
buffer[buffer_position + 1] == 0xbe &&
buffer[buffer_position + 2] == 0xb4 &&
buffer[buffer_position + 3] == 0xd9 );
// Get the block size from the reversed endain field.
block_size = get_block_size(buffer, buffer_position + 4);
// If the rest of the block isn't inside the buffer break out
if (buffer_position + block_size + 8 > buffer_size)
break;
std::promise<std::error_code> ec_promise;
std::promise<block_info> info_promise;
block_type blk;
satoshi_load(buffer.begin() + buffer_position + 8,
buffer.begin() + buffer_position + 8 + block_size,
blk);
// Assert we match the genesis block hash
if (blocks_parsed == 0)
BITCOIN_ASSERT(hash_block_header(blk.header) ==
hash_block_header(first_block.header));
auto block_imported =
[&ec_promise, &info_promise](const std::error_code& ec,
const block_info info)
{
// handle_store(ec, info, block_hash);
ec_promise.set_value(ec);
info_promise.set_value(info);
};
chain.store(blk, std::bind(block_imported, _1, _2));
hash_digest block_hash = hash_block_header(blk.header);
std::error_code ec = ec_promise.get_future().get();
block_info info = info_promise.get_future().get();
// We need orphan blocks so we can do the next getblocks round
if (ec && info.status != block_status::orphan)
{
log_error("bootstrap")
<< "Storing block " << encode_hex(block_hash)
<< ": " << ec.message();
}
else
switch (info.status)
{
// There should be no orphans
case block_status::orphan:
log_error("bootstrap")
<< "Orphan block " << encode_hex(block_hash);
break;
case block_status::rejected:
log_error("bootstrap")
<< "Rejected block " << encode_hex(block_hash);
break;
case block_status::confirmed:
log_info("bootstrap")
<< "Block #" << info.height << " " << encode_hex(block_hash);
break;
}
// Fixes segmentation fault, maybe this is an issue with ec_promise and .get_future()
usleep(1000);
buffer_position += block_size + 8;
blocks_parsed++;
}
// Rewind to the last good magic bytes, which didn't have enough space
// left in the buffer for the block
fin.seekg(buffer_position - buffer_size, std::ios::cur);
}
fin.close();
// All threadpools stopping in parallel...
pool.stop();
// ... Make them all join main thread and wait until they finish.
pool.join();
// Now safely close leveldb_blockchain.
chain.stop();
return 0;
}
<commit_msg>replace main std promise with a spinlock.<commit_after>/*
Imports blocks from bootstrap.dat
bootstrap.dat is the raw blocks in the format
[magic bytes] [block length] [serialized block]
*/
#include <future>
#include <bitcoin/bitcoin.hpp>
#define LOG_BOOTSTRAP "bootstrap"
using namespace bc;
using std::placeholders::_1;
using std::placeholders::_2;
bool stopped = false;
void signal_handler(int signal)
{
log_info(LOG_BOOTSTRAP) << "Caught signal: " << signal;
stopped = true;
}
int main(int argc, char** argv)
{
if (argc != 3)
{
std::cout << "Usage: "
"bootstrap BLOCKCHAIN_DIR BOOTSTRAP_DATFILE" << std::endl;
return 1;
}
const std::string dbpath = argv[1];
const std::string bootstrapfile = argv[2];
// Threadpool context containing 1 thread.
threadpool pool(1);
// leveldb_blockchain operations execute in pool's thread.
leveldb_blockchain chain(pool);
// Completion handler for starting the leveldb_blockchain.
// Does nothing.
auto blockchain_start = [](const std::error_code& ec) {};
// Start blockchain with a database path.
chain.start(dbpath, blockchain_start);
// First block is the genesis block.
block_type first_block = genesis_block();
const hash_digest genesis_hash = hash_block_header(first_block.header);
// Total number of blocks parsed from the bootstrap.dat
int blocks_parsed = 0;
// position of the pointer in the buffer
int buffer_position = 0;
block_header_type blk_header;
std::promise<std::error_code> ec_fetch_promise;
auto genesis_block_fetched_handler =
[&ec_fetch_promise, &blk_header](
const std::error_code& ec, const block_header_type& header)
{
blk_header = header;
ec_fetch_promise.set_value(ec);
};
// See if we can fetch the genesis block from the leveldb database
chain.fetch_block_header(0, genesis_block_fetched_handler);
std::error_code ec = ec_fetch_promise.get_future().get();
if (ec)
{
BITCOIN_ASSERT(ec == error::not_found);
//Import the genesis_block() if it does not yet exist in the leveldb
std::promise<std::error_code> ec_import_promise;
auto genesis_block_imported_handler =
[&ec_import_promise](const std::error_code& ec)
{
ec_import_promise.set_value(ec);
};
chain.import(first_block, 0, genesis_block_imported_handler);
ec = ec_import_promise.get_future().get();
if (ec)
{
log_error(LOG_BOOTSTRAP)
<< "Importing genesis block failed: " << ec.message();
return -1;
}
log_info(LOG_BOOTSTRAP) << "Imported genesis block";
}
else
{
// If we already have a block stored in the leveldb, check its hash
// matches the one coded into genesis_block()
BITCOIN_ASSERT(hash_block_header(blk_header) == genesis_hash);
}
std::ifstream fin(bootstrapfile, std::ios::in | std::ios::binary);
if (!fin)
{
log_error(LOG_BOOTSTRAP) << "Could not open bootstrap.dat file";
fin.close();
pool.stop();
pool.join();
chain.stop();
return -1;
}
constexpr size_t max_block_size = 1000000;
// Allocate a 2 * max_block_size buffer, so we are sure to read at least
// one full block into the buffer, or many smaller ones.
constexpr size_t buffer_size = 2 * max_block_size;
int block_size;
data_chunk buffer(buffer_size);
// The total size of the block is endian reversed
// This lambda function will read the chunk from its
// first byte at position pos in the buffer and return
// the integer representation of the block size in bytes.
auto get_block_size =
[](const data_chunk& buffer, const int pos)
{
return (int) (buffer[pos + 3] << 24) +
(int) (buffer[pos + 2] << 16) +
(int) (buffer[pos + 1] << 8) +
(int) (buffer[pos]);
};
// This will return false when there are not enough bytes left
// in the file to fill the buffer, meaning we may miss the last block
std::cout << "entering loop" << std::endl;
while(!stopped)
{
std::cout << "started1" << std::endl;
fin.read((char*) &buffer[0], buffer_size);
buffer_position = 0;
std::cout << "started" << std::endl;
while(buffer_position < buffer_size - 8 && !stopped)
{
// Assert we have the magic bytes.
BITCOIN_ASSERT(
buffer[buffer_position] == 0xf9 &&
buffer[buffer_position + 1] == 0xbe &&
buffer[buffer_position + 2] == 0xb4 &&
buffer[buffer_position + 3] == 0xd9);
// Get the block size from the reversed endain field.
block_size = get_block_size(buffer, buffer_position + 4);
// If the rest of the block isn't inside the buffer break out
if (buffer_position + block_size + 8 > buffer_size)
break;
auto begin_iter = buffer.begin() + buffer_position + 8;
auto end_iter = begin_iter + block_size;
block_type blk;
satoshi_load(begin_iter, end_iter, blk);
// Assert we match the genesis block hash
BITCOIN_ASSERT(blocks_parsed != 0 ||
hash_block_header(blk.header) == genesis_hash);
std::error_code ec;
block_info info;
bool finished = false;
auto block_imported = [&ec, &info, &finished](
const std::error_code& cec, const block_info blk_info)
{
log_debug(LOG_BOOTSTRAP) << "Block imported.";
info = blk_info;
ec = cec;
finished = true;
};
log_debug(LOG_BOOTSTRAP) << "Storing block. Parse count = "
<< blocks_parsed;
chain.store(blk, block_imported);
while (!finished)
usleep(1000);
hash_digest block_hash = hash_block_header(blk.header);
// We need orphan blocks so we can do the next getblocks round
if (ec && info.status != block_status::orphan)
{
log_error(LOG_BOOTSTRAP)
<< "Storing block " << encode_hex(block_hash)
<< ": " << ec.message();
}
else
{
switch (info.status)
{
// There should be no orphans
case block_status::orphan:
log_error(LOG_BOOTSTRAP)
<< "Orphan block " << block_hash;
break;
case block_status::rejected:
log_error(LOG_BOOTSTRAP)
<< "Rejected block " << block_hash;
break;
case block_status::confirmed:
log_info(LOG_BOOTSTRAP)
<< "Block #" << info.height << " " << block_hash;
break;
}
}
buffer_position += block_size + 8;
blocks_parsed++;
}
// Rewind to the last good magic bytes, which didn't have enough space
// left in the buffer for the block
fin.seekg(buffer_position - buffer_size, std::ios::cur);
}
fin.close();
// All threadpools stopping in parallel...
pool.stop();
// ... Make them all join main thread and wait until they finish.
pool.join();
// Now safely close leveldb_blockchain.
chain.stop();
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: adtabdlg.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: rt $ $Date: 2004-09-08 16:29:30 $
*
* 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 DBAUI_QYDLGTAB_HXX
#include "adtabdlg.hxx"
#endif
#ifndef DBAUI_ADTABDLG_HRC
#include "adtabdlg.hrc"
#endif
#ifndef _DBAUI_SQLMESSAGE_HXX_
#include "sqlmessage.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include "dbaccess_helpid.hrc"
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SFXSIDS_HRC
#include <sfx2/sfxsids.hrc>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef DBAUI_QUERYTABLEVIEW_HXX
#include "QueryTableView.hxx"
#endif
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XVIEWSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#include <algorithm>
// slot ids
using namespace dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace dbtools;
DBG_NAME(OAddTableDlg)
//------------------------------------------------------------------------------
OAddTableDlg::OAddTableDlg( Window* pParent,OJoinTableView* _pTableView)
:ModelessDialog( pParent, ModuleRes(DLG_JOIN_TABADD) )
,aFTTable( this, ResId( FT_TABLE ) )
,aTableList( this,NULL, ResId( LB_TABLE ),sal_False,sal_False )
,aAddButton( this, ResId( PB_ADDTABLE ) )
,aCloseButton( this, ResId( PB_CLOSE ) )
,aHelpButton( this, ResId( PB_HELP ) )
,aFixedLineTable( this, ResId( FL_TABLE ) )
,aDefaultString( ResId( STR_DEFAULT ) )
,m_pTableView(_pTableView)
,m_bInitialized(sal_False)
{
DBG_CTOR(OAddTableDlg,NULL);
OSL_ENSURE(_pTableView,"Must be a valid pointer!");
// der Close-Button hat schon einen Standard-Help-Text, den ich aber hier nicht haben moechte, also den Text ruecksetzen
// und eine neue ID verteilen
aCloseButton.SetHelpText(String());
aCloseButton.SetHelpId(HID_JOINSH_ADDTAB_CLOSE);
aTableList.SetHelpId(HID_JOINSH_ADDTAB_TABLELIST);
//////////////////////////////////////////////////////////////////////
// Handler setzen
aAddButton.SetClickHdl( LINK(this,OAddTableDlg, AddClickHdl) );
aCloseButton.SetClickHdl( LINK(this,OAddTableDlg, CloseClickHdl) );
aTableList.SetDoubleClickHdl( LINK(this,OAddTableDlg, TableListDoubleClickHdl) );
aTableList.SetSelectHdl( LINK(this,OAddTableDlg, TableListSelectHdl) );
aTableList.EnableInplaceEditing( FALSE );
aTableList.SetWindowBits(WB_BORDER | WB_HASLINES |WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HASLINESATROOT | WB_SORT | WB_HSCROLL );
aTableList.EnableCheckButton( NULL ); // do not show any buttons
aTableList.SetSelectionMode( SINGLE_SELECTION );
aTableList.notifyHiContrastChanged();
FreeResource();
}
//------------------------------------------------------------------------------
OAddTableDlg::~OAddTableDlg()
{
DBG_DTOR(OAddTableDlg,NULL);
}
//------------------------------------------------------------------------------
void OAddTableDlg::Update()
{
if(!m_bInitialized)
{
UpdateTableList(m_pTableView->getDesignView()->getController()->isViewAllowed());
m_bInitialized = sal_True;
}
}
//------------------------------------------------------------------------------
void OAddTableDlg::AddTable()
{
//////////////////////////////////////////////////////////////////
// Tabelle hinzufuegen
SvLBoxEntry* pEntry = aTableList.FirstSelected();
if( pEntry && !aTableList.GetModel()->HasChilds(pEntry))
{
::rtl::OUString aCatalog,aSchema,aTableName;
SvLBoxEntry* pSchema = aTableList.GetParent(pEntry);
if(pSchema && pSchema != aTableList.getAllObjectsEntry())
{
SvLBoxEntry* pCatalog = aTableList.GetParent(pSchema);
if(pCatalog && pCatalog != aTableList.getAllObjectsEntry())
aCatalog = aTableList.GetEntryText(pCatalog);
aSchema = aTableList.GetEntryText(pSchema);
}
aTableName = aTableList.GetEntryText(pEntry);
::rtl::OUString aComposedName;
try
{
Reference<XDatabaseMetaData> xMeta = m_pTableView->getDesignView()->getController()->getConnection()->getMetaData();
// den Datenbank-Namen besorgen
if ( !aCatalog.getLength()
&& aSchema.getLength()
&& xMeta->supportsCatalogsInDataManipulation()
&& !xMeta->supportsSchemasInDataManipulation() )
{
aCatalog = aSchema;
aSchema = ::rtl::OUString();
}
::dbtools::composeTableName(xMeta,
aCatalog,
aSchema,
aTableName,
aComposedName,
sal_False,
::dbtools::eInDataManipulation);
}
catch(const Exception&)
{
OSL_ENSURE(0,"Exception catched!");
}
// aOrigTableName is used because AddTabWin would like to have this
// und das Ganze dem Container uebergeben
m_pTableView->AddTabWin( aComposedName,aTableName, TRUE );
}
}
//------------------------------------------------------------------------------
IMPL_LINK( OAddTableDlg, AddClickHdl, Button*, pButton )
{
TableListDoubleClickHdl(NULL);
return 0;
}
//------------------------------------------------------------------------------
IMPL_LINK( OAddTableDlg, TableListDoubleClickHdl, ListBox *, EMPTY_ARG )
{
if (IsAddAllowed())
AddTable();
if (!IsAddAllowed())
Close();
return 0;
}
//------------------------------------------------------------------------------
IMPL_LINK( OAddTableDlg, TableListSelectHdl, ListBox *, EMPTY_ARG )
{
SvLBoxEntry* pEntry = aTableList.FirstSelected();
aAddButton.Enable( pEntry && !aTableList.GetModel()->HasChilds(pEntry) );
return 0;
}
//------------------------------------------------------------------------------
IMPL_LINK( OAddTableDlg, CloseClickHdl, Button*, pButton )
{
return Close();
}
//------------------------------------------------------------------------------
BOOL OAddTableDlg::Close()
{
m_pTableView->getDesignView()->getController()->InvalidateFeature(ID_BROWSER_ADDTABLE);
m_pTableView->getDesignView()->getController()->getView()->GrabFocus();
return ModelessDialog::Close();
}
//------------------------------------------------------------------------------
BOOL OAddTableDlg::IsAddAllowed()
{
return m_pTableView && m_pTableView->IsAddAllowed();
}
//------------------------------------------------------------------------------
void OAddTableDlg::UpdateTableList(BOOL bViewsAllowed)
{
//////////////////////////////////////////////////////////////////////
// Datenbank- und Tabellennamen setzen
Reference< XTablesSupplier > xTableSupp(m_pTableView->getDesignView()->getController()->getConnection(),UNO_QUERY);
Reference< XViewsSupplier > xViewSupp;
Reference< XNameAccess > xTables, xViews;
xTables = xTableSupp->getTables();
// get the views supplier and the views
Sequence< ::rtl::OUString> sTables,sViews;
if (xTables.is())
sTables = xTables->getElementNames();
xViewSupp.set(xTableSupp,UNO_QUERY);
if (xViewSupp.is())
{
xViews = xViewSupp->getViews();
if (xViews.is())
sViews = xViews->getElementNames();
}
// if no views are allowed remove the views also out the table name filter
if ( !bViewsAllowed )
{
const ::rtl::OUString* pTableBegin = sTables.getConstArray();
const ::rtl::OUString* pTableEnd = pTableBegin + sTables.getLength();
::std::vector< ::rtl::OUString > aTables(pTableBegin,pTableEnd);
const ::rtl::OUString* pViewBegin = sViews.getConstArray();
const ::rtl::OUString* pViewEnd = pViewBegin + sViews.getLength();
::comphelper::TStringMixEqualFunctor aEqualFunctor;
for(;pViewBegin != pViewEnd;++pViewBegin)
aTables.erase(::std::remove_if(aTables.begin(),aTables.end(),::std::bind2nd(aEqualFunctor,*pViewBegin)));
::rtl::OUString* pTables = aTables.empty() ? 0 : &aTables[0];
sTables = Sequence< ::rtl::OUString>(pTables, aTables.size());
sViews = Sequence< ::rtl::OUString>();
}
aTableList.UpdateTableList(Reference< XConnection>(xTableSupp,UNO_QUERY)->getMetaData(),sTables,sViews);
SvLBoxEntry* pEntry = aTableList.First();
while( pEntry && aTableList.GetModel()->HasChilds(pEntry))
{
aTableList.Expand(pEntry);
pEntry = aTableList.Next(pEntry);
}
if ( pEntry )
aTableList.Select(pEntry);
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS ooo19126 (1.19.194); FILE MERGED 2005/09/05 17:33:40 rt 1.19.194.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: adtabdlg.cxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: rt $ $Date: 2005-09-08 14:52:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBAUI_QYDLGTAB_HXX
#include "adtabdlg.hxx"
#endif
#ifndef DBAUI_ADTABDLG_HRC
#include "adtabdlg.hrc"
#endif
#ifndef _DBAUI_SQLMESSAGE_HXX_
#include "sqlmessage.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#include "dbaccess_helpid.hrc"
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SFXSIDS_HRC
#include <sfx2/sfxsids.hrc>
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef DBAUI_QUERYTABLEVIEW_HXX
#include "QueryTableView.hxx"
#endif
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef DBACCESS_UI_BROWSER_ID_HXX
#include "browserids.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XVIEWSSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#include <algorithm>
// slot ids
using namespace dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace dbtools;
DBG_NAME(OAddTableDlg)
//------------------------------------------------------------------------------
OAddTableDlg::OAddTableDlg( Window* pParent,OJoinTableView* _pTableView)
:ModelessDialog( pParent, ModuleRes(DLG_JOIN_TABADD) )
,aFTTable( this, ResId( FT_TABLE ) )
,aTableList( this,NULL, ResId( LB_TABLE ),sal_False,sal_False )
,aAddButton( this, ResId( PB_ADDTABLE ) )
,aCloseButton( this, ResId( PB_CLOSE ) )
,aHelpButton( this, ResId( PB_HELP ) )
,aFixedLineTable( this, ResId( FL_TABLE ) )
,aDefaultString( ResId( STR_DEFAULT ) )
,m_pTableView(_pTableView)
,m_bInitialized(sal_False)
{
DBG_CTOR(OAddTableDlg,NULL);
OSL_ENSURE(_pTableView,"Must be a valid pointer!");
// der Close-Button hat schon einen Standard-Help-Text, den ich aber hier nicht haben moechte, also den Text ruecksetzen
// und eine neue ID verteilen
aCloseButton.SetHelpText(String());
aCloseButton.SetHelpId(HID_JOINSH_ADDTAB_CLOSE);
aTableList.SetHelpId(HID_JOINSH_ADDTAB_TABLELIST);
//////////////////////////////////////////////////////////////////////
// Handler setzen
aAddButton.SetClickHdl( LINK(this,OAddTableDlg, AddClickHdl) );
aCloseButton.SetClickHdl( LINK(this,OAddTableDlg, CloseClickHdl) );
aTableList.SetDoubleClickHdl( LINK(this,OAddTableDlg, TableListDoubleClickHdl) );
aTableList.SetSelectHdl( LINK(this,OAddTableDlg, TableListSelectHdl) );
aTableList.EnableInplaceEditing( FALSE );
aTableList.SetWindowBits(WB_BORDER | WB_HASLINES |WB_HASBUTTONS | WB_HASBUTTONSATROOT | WB_HASLINESATROOT | WB_SORT | WB_HSCROLL );
aTableList.EnableCheckButton( NULL ); // do not show any buttons
aTableList.SetSelectionMode( SINGLE_SELECTION );
aTableList.notifyHiContrastChanged();
FreeResource();
}
//------------------------------------------------------------------------------
OAddTableDlg::~OAddTableDlg()
{
DBG_DTOR(OAddTableDlg,NULL);
}
//------------------------------------------------------------------------------
void OAddTableDlg::Update()
{
if(!m_bInitialized)
{
UpdateTableList(m_pTableView->getDesignView()->getController()->isViewAllowed());
m_bInitialized = sal_True;
}
}
//------------------------------------------------------------------------------
void OAddTableDlg::AddTable()
{
//////////////////////////////////////////////////////////////////
// Tabelle hinzufuegen
SvLBoxEntry* pEntry = aTableList.FirstSelected();
if( pEntry && !aTableList.GetModel()->HasChilds(pEntry))
{
::rtl::OUString aCatalog,aSchema,aTableName;
SvLBoxEntry* pSchema = aTableList.GetParent(pEntry);
if(pSchema && pSchema != aTableList.getAllObjectsEntry())
{
SvLBoxEntry* pCatalog = aTableList.GetParent(pSchema);
if(pCatalog && pCatalog != aTableList.getAllObjectsEntry())
aCatalog = aTableList.GetEntryText(pCatalog);
aSchema = aTableList.GetEntryText(pSchema);
}
aTableName = aTableList.GetEntryText(pEntry);
::rtl::OUString aComposedName;
try
{
Reference<XDatabaseMetaData> xMeta = m_pTableView->getDesignView()->getController()->getConnection()->getMetaData();
// den Datenbank-Namen besorgen
if ( !aCatalog.getLength()
&& aSchema.getLength()
&& xMeta->supportsCatalogsInDataManipulation()
&& !xMeta->supportsSchemasInDataManipulation() )
{
aCatalog = aSchema;
aSchema = ::rtl::OUString();
}
::dbtools::composeTableName(xMeta,
aCatalog,
aSchema,
aTableName,
aComposedName,
sal_False,
::dbtools::eInDataManipulation);
}
catch(const Exception&)
{
OSL_ENSURE(0,"Exception catched!");
}
// aOrigTableName is used because AddTabWin would like to have this
// und das Ganze dem Container uebergeben
m_pTableView->AddTabWin( aComposedName,aTableName, TRUE );
}
}
//------------------------------------------------------------------------------
IMPL_LINK( OAddTableDlg, AddClickHdl, Button*, pButton )
{
TableListDoubleClickHdl(NULL);
return 0;
}
//------------------------------------------------------------------------------
IMPL_LINK( OAddTableDlg, TableListDoubleClickHdl, ListBox *, EMPTY_ARG )
{
if (IsAddAllowed())
AddTable();
if (!IsAddAllowed())
Close();
return 0;
}
//------------------------------------------------------------------------------
IMPL_LINK( OAddTableDlg, TableListSelectHdl, ListBox *, EMPTY_ARG )
{
SvLBoxEntry* pEntry = aTableList.FirstSelected();
aAddButton.Enable( pEntry && !aTableList.GetModel()->HasChilds(pEntry) );
return 0;
}
//------------------------------------------------------------------------------
IMPL_LINK( OAddTableDlg, CloseClickHdl, Button*, pButton )
{
return Close();
}
//------------------------------------------------------------------------------
BOOL OAddTableDlg::Close()
{
m_pTableView->getDesignView()->getController()->InvalidateFeature(ID_BROWSER_ADDTABLE);
m_pTableView->getDesignView()->getController()->getView()->GrabFocus();
return ModelessDialog::Close();
}
//------------------------------------------------------------------------------
BOOL OAddTableDlg::IsAddAllowed()
{
return m_pTableView && m_pTableView->IsAddAllowed();
}
//------------------------------------------------------------------------------
void OAddTableDlg::UpdateTableList(BOOL bViewsAllowed)
{
//////////////////////////////////////////////////////////////////////
// Datenbank- und Tabellennamen setzen
Reference< XTablesSupplier > xTableSupp(m_pTableView->getDesignView()->getController()->getConnection(),UNO_QUERY);
Reference< XViewsSupplier > xViewSupp;
Reference< XNameAccess > xTables, xViews;
xTables = xTableSupp->getTables();
// get the views supplier and the views
Sequence< ::rtl::OUString> sTables,sViews;
if (xTables.is())
sTables = xTables->getElementNames();
xViewSupp.set(xTableSupp,UNO_QUERY);
if (xViewSupp.is())
{
xViews = xViewSupp->getViews();
if (xViews.is())
sViews = xViews->getElementNames();
}
// if no views are allowed remove the views also out the table name filter
if ( !bViewsAllowed )
{
const ::rtl::OUString* pTableBegin = sTables.getConstArray();
const ::rtl::OUString* pTableEnd = pTableBegin + sTables.getLength();
::std::vector< ::rtl::OUString > aTables(pTableBegin,pTableEnd);
const ::rtl::OUString* pViewBegin = sViews.getConstArray();
const ::rtl::OUString* pViewEnd = pViewBegin + sViews.getLength();
::comphelper::TStringMixEqualFunctor aEqualFunctor;
for(;pViewBegin != pViewEnd;++pViewBegin)
aTables.erase(::std::remove_if(aTables.begin(),aTables.end(),::std::bind2nd(aEqualFunctor,*pViewBegin)));
::rtl::OUString* pTables = aTables.empty() ? 0 : &aTables[0];
sTables = Sequence< ::rtl::OUString>(pTables, aTables.size());
sViews = Sequence< ::rtl::OUString>();
}
aTableList.UpdateTableList(Reference< XConnection>(xTableSupp,UNO_QUERY)->getMetaData(),sTables,sViews);
SvLBoxEntry* pEntry = aTableList.First();
while( pEntry && aTableList.GetModel()->HasChilds(pEntry))
{
aTableList.Expand(pEntry);
pEntry = aTableList.Next(pEntry);
}
if ( pEntry )
aTableList.Select(pEntry);
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* fIcy - HTTP/1.0-ICY stream extractor/separator
* Copyright(c) 2003-2007 of wave++ (Yuri D'Elia)
* Distributed under GNU LGPL without ANY warranty.
*/
#ifndef fIcy_hh
#define fIcy_hh
// system headers (for size_t)
#include <cstddef>
// some defines
#define FICY_VERSION "1.0.16"
// some constants
namespace fIcy
{
// common strings
const char version[] = FICY_VERSION;
const char copyright[] =
"Copyright(c) 2003-2006 of wave++ (Yuri D'Elia) <wavexx@users.sf.net>\n"
"Distributed under GNU LGPL (v2 or above) without ANY warranty.\n";
// fIcy defaults
const char userAgent[] = "User-agent: fIcy " FICY_VERSION;
const size_t bufSz = 1024;
const char coproc[] = "sed";
const size_t maxFollow = 1;
const char fIcyHelp[] =
" [-dposqmEtxXIfFailMcnrv] <server [port [path]]|url>\n\n"
" -d\t\tDo not dump the output to stdout\n"
" -p\t\tWhen dumping to stdout consider writing errors as transient\n"
" -o file\tDump the output to file (or use file as a prefix with -mE)\n"
" -s sfx\tUse sfx as a suffix for new files\n"
" -q file\tAppend \"file name\" sequence to file (only when saving)\n"
" -m\t\tUse song title when writing filenames. file used as prefix\n"
" -E num\tEnumerate written files, starting at num (0 autodetects).\n"
" -t\t\tDisplay titles while downloading\n"
" -x regex\tDump only titles matching regex\n"
" -X regex\tDo NOT dump titles matching regex\n"
" -I file\tLoad include/exclude regexs from file\n"
" -f expr\tRewrite titles using the specified expression\n"
" -F file\tRewrite titles using the specified script\n"
" -C path\tRewrite coprocessor (default: sed)\n"
" -a file\tProvide HTTP credentials (user:pass file)\n"
" -i time\tMaximum network idle time\n"
" -l num\tRedirect follow limit\n"
" -M time\tMaximum playing time\n"
" -c\t\tDo not clobber files (implicit with -n)\n"
" -n\t\tIf the file exists create a new file with .n appended\n"
" -r\t\tRemove partials. Keep only complete sequences\n"
" -v\t\tVerbose\n\n";
// fResync defaults
const size_t frameLen = 1597; // (114 * 448000 / 32000 + 1)
const size_t maxFrames = 6;
const char fResyncHelp[] =
" [-bsv] [-n frames] [-m len] file\n\n"
" -b\t\tBuffered I/O mode (implicit with -s)\n"
" -s\t\tSimulate only (print frame sync offsets: start and size)\n"
" -v\t\tIncrement verbosity level\n"
" -n frames\tNumber of frames to check\n"
" -m len\tMaximum frame length\n\n";
// fPls defaults
const size_t maxRetries = 1;
const size_t maxLoops = 1;
const size_t waitSecs = 15;
const char fPlsHelp[] =
" [-LMPRTadilv] <file|url> [fIcy options]\n\n"
" -L max\tMaximum playlist loops\n"
" -M time\tMaximum cumulative playing time\n"
" -P path\tSpecify fIcy executable name/path\n"
" -R max\tMaximum per-stream retries\n"
" -T time\tWait the specified time after each failure\n"
" -a file\tProvide HTTP credentials (user:pass file)\n"
" -d file\tRun as a daemon, redirecting messages to file\n"
" -i time\tMaximum network idle time\n"
" -l num\tRedirect follow limit\n"
" -v\t\tVerbose\n\n";
}
namespace Exit
{
const int success = 0;
const int fail = 1;
const int args = 2;
}
#endif
<commit_msg>More copyright date fixes.<commit_after>/*
* fIcy - HTTP/1.0-ICY stream extractor/separator
* Copyright(c) 2003-2007 of wave++ (Yuri D'Elia)
* Distributed under GNU LGPL without ANY warranty.
*/
#ifndef fIcy_hh
#define fIcy_hh
// system headers (for size_t)
#include <cstddef>
// some defines
#define FICY_VERSION "1.0.16"
// some constants
namespace fIcy
{
// common strings
const char version[] = FICY_VERSION;
const char copyright[] =
"Copyright(c) 2003-2007 of wave++ (Yuri D'Elia) <wavexx@users.sf.net>\n"
"Distributed under GNU LGPL (v2 or above) without ANY warranty.\n";
// fIcy defaults
const char userAgent[] = "User-agent: fIcy " FICY_VERSION;
const size_t bufSz = 1024;
const char coproc[] = "sed";
const size_t maxFollow = 1;
const char fIcyHelp[] =
" [-dposqmEtxXIfFCailMcnrv] <server [port [path]]|url>\n\n"
" -d\t\tDo not dump the output to stdout\n"
" -p\t\tWhen dumping to stdout consider writing errors as transient\n"
" -o file\tDump the output to file (or use file as a prefix with -mE)\n"
" -s sfx\tUse sfx as a suffix for new files\n"
" -q file\tAppend \"file name\" sequence to file (only when saving)\n"
" -m\t\tUse song title when writing filenames. file used as prefix\n"
" -E num\tEnumerate written files, starting at num (0 autodetects).\n"
" -t\t\tDisplay titles while downloading\n"
" -x regex\tDump only titles matching regex\n"
" -X regex\tDo NOT dump titles matching regex\n"
" -I file\tLoad include/exclude regexs from file\n"
" -f expr\tRewrite titles using the specified expression\n"
" -F file\tRewrite titles using the specified script\n"
" -C path\tRewrite coprocessor (default: sed)\n"
" -a file\tProvide HTTP credentials (user:pass file)\n"
" -i time\tMaximum network idle time\n"
" -l num\tRedirect follow limit\n"
" -M time\tMaximum playing time\n"
" -c\t\tDo not clobber files (implicit with -n)\n"
" -n\t\tIf the file exists create a new file with .n appended\n"
" -r\t\tRemove partials. Keep only complete sequences\n"
" -v\t\tVerbose\n\n";
// fResync defaults
const size_t frameLen = 1597; // (114 * 448000 / 32000 + 1)
const size_t maxFrames = 6;
const char fResyncHelp[] =
" [-bsv] [-n frames] [-m len] file\n\n"
" -b\t\tBuffered I/O mode (implicit with -s)\n"
" -s\t\tSimulate only (print frame sync offsets: start and size)\n"
" -v\t\tIncrement verbosity level\n"
" -n frames\tNumber of frames to check\n"
" -m len\tMaximum frame length\n\n";
// fPls defaults
const size_t maxRetries = 1;
const size_t maxLoops = 1;
const size_t waitSecs = 15;
const char fPlsHelp[] =
" [-LMPRTadilv] <file|url> [fIcy options]\n\n"
" -L max\tMaximum playlist loops\n"
" -M time\tMaximum cumulative playing time\n"
" -P path\tSpecify fIcy executable name/path\n"
" -R max\tMaximum per-stream retries\n"
" -T time\tWait the specified time after each failure\n"
" -a file\tProvide HTTP credentials (user:pass file)\n"
" -d file\tRun as a daemon, redirecting messages to file\n"
" -i time\tMaximum network idle time\n"
" -l num\tRedirect follow limit\n"
" -v\t\tVerbose\n\n";
}
namespace Exit
{
const int success = 0;
const int fail = 1;
const int args = 2;
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charsets.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:45:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBAUI_CHARSETS_HXX_
#define _DBAUI_CHARSETS_HXX_
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _TOOLS_RC_HXX
#include <tools/rc.hxx>
#endif
#ifndef _DBHELPER_DBCHARSET_HXX_
#include <connectivity/dbcharset.hxx>
#endif
#ifndef _SVX_TXENCTAB_HXX
#include <svx/txenctab.hxx>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
//=========================================================================
//= OCharsetDisplay
//=========================================================================
typedef ::dbtools::OCharsetMap OCharsetDisplay_Base;
class OCharsetDisplay
:protected OCharsetDisplay_Base
,protected SvxTextEncodingTable
{
protected:
::rtl::OUString m_aSystemDisplayName;
public:
class ExtendedCharsetIterator;
friend class OCharsetDisplay::ExtendedCharsetIterator;
typedef ExtendedCharsetIterator iterator;
typedef ExtendedCharsetIterator const_iterator;
OCharsetDisplay();
struct IANA { };
struct Display { };
// various find operations
const_iterator find(const rtl_TextEncoding _eEncoding) const;
const_iterator find(const ::rtl::OUString& _rIanaName, const IANA&) const;
const_iterator find(const ::rtl::OUString& _rDisplayName, const Display&) const;
/// get access to the first element of the charset collection
const_iterator begin() const;
/// get access to the (last + 1st) element of the charset collection
const_iterator end() const;
// size of the map
sal_Int32 size() const { return OCharsetDisplay_Base::size(); }
protected:
virtual sal_Bool approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const;
};
//-------------------------------------------------------------------------
//- CharsetDisplayDerefHelper
//-------------------------------------------------------------------------
typedef ::dbtools::CharsetIteratorDerefHelper CharsetDisplayDerefHelper_Base;
class CharsetDisplayDerefHelper : protected CharsetDisplayDerefHelper_Base
{
friend class OCharsetDisplay::ExtendedCharsetIterator;
::rtl::OUString m_sDisplayName;
public:
CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource);
rtl_TextEncoding getEncoding() const { return CharsetDisplayDerefHelper_Base::getEncoding(); }
::rtl::OUString getIanaName() const { return CharsetDisplayDerefHelper_Base::getIanaName(); }
::rtl::OUString getDisplayName() const { return m_sDisplayName; }
protected:
CharsetDisplayDerefHelper();
CharsetDisplayDerefHelper(const ::dbtools::CharsetIteratorDerefHelper& _rBase, const ::rtl::OUString& _rDisplayName);
};
//-------------------------------------------------------------------------
//- OCharsetDisplay::ExtendedCharsetIterator
//-------------------------------------------------------------------------
class OCharsetDisplay::ExtendedCharsetIterator
{
friend class OCharsetDisplay;
friend bool operator==(const ExtendedCharsetIterator& lhs, const ExtendedCharsetIterator& rhs);
friend bool operator!=(const ExtendedCharsetIterator& lhs, const ExtendedCharsetIterator& rhs) { return !(lhs == rhs); }
typedef ::dbtools::OCharsetMap container;
typedef container::CharsetIterator base_iterator;
protected:
const OCharsetDisplay* m_pContainer;
base_iterator m_aPosition;
public:
ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource);
CharsetDisplayDerefHelper operator*() const;
/// prefix increment
const ExtendedCharsetIterator& operator++();
/// postfix increment
const ExtendedCharsetIterator operator++(int) { ExtendedCharsetIterator hold(*this); ++*this; return hold; }
/// prefix decrement
const ExtendedCharsetIterator& operator--();
/// postfix decrement
const ExtendedCharsetIterator operator--(int) { ExtendedCharsetIterator hold(*this); --*this; return hold; }
protected:
ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition );
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // _DBAUI_CHARSETS_HXX_
<commit_msg>INTEGRATION: CWS warnings01 (1.6.50); FILE MERGED 2006/06/01 07:21:16 fs 1.6.50.2: #i10000# renamed the find methods to findFoo, removed using Base::find 2006/03/24 15:36:18 fs 1.6.50.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charsets.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-20 03:16:33 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBAUI_CHARSETS_HXX_
#define _DBAUI_CHARSETS_HXX_
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _TOOLS_RC_HXX
#include <tools/rc.hxx>
#endif
#ifndef _DBHELPER_DBCHARSET_HXX_
#include <connectivity/dbcharset.hxx>
#endif
#ifndef _SVX_TXENCTAB_HXX
#include <svx/txenctab.hxx>
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
//=========================================================================
//= OCharsetDisplay
//=========================================================================
typedef ::dbtools::OCharsetMap OCharsetDisplay_Base;
class OCharsetDisplay
:protected OCharsetDisplay_Base
,protected SvxTextEncodingTable
{
protected:
::rtl::OUString m_aSystemDisplayName;
public:
class ExtendedCharsetIterator;
friend class OCharsetDisplay::ExtendedCharsetIterator;
typedef ExtendedCharsetIterator iterator;
typedef ExtendedCharsetIterator const_iterator;
OCharsetDisplay();
// various find operations
const_iterator findEncoding(const rtl_TextEncoding _eEncoding) const;
const_iterator findIanaName(const ::rtl::OUString& _rIanaName) const;
const_iterator findDisplayName(const ::rtl::OUString& _rDisplayName) const;
/// get access to the first element of the charset collection
const_iterator begin() const;
/// get access to the (last + 1st) element of the charset collection
const_iterator end() const;
// size of the map
sal_Int32 size() const { return OCharsetDisplay_Base::size(); }
protected:
virtual sal_Bool approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const;
private:
using OCharsetDisplay_Base::find;
};
//-------------------------------------------------------------------------
//- CharsetDisplayDerefHelper
//-------------------------------------------------------------------------
typedef ::dbtools::CharsetIteratorDerefHelper CharsetDisplayDerefHelper_Base;
class CharsetDisplayDerefHelper : protected CharsetDisplayDerefHelper_Base
{
friend class OCharsetDisplay::ExtendedCharsetIterator;
::rtl::OUString m_sDisplayName;
public:
CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource);
rtl_TextEncoding getEncoding() const { return CharsetDisplayDerefHelper_Base::getEncoding(); }
::rtl::OUString getIanaName() const { return CharsetDisplayDerefHelper_Base::getIanaName(); }
::rtl::OUString getDisplayName() const { return m_sDisplayName; }
protected:
CharsetDisplayDerefHelper();
CharsetDisplayDerefHelper(const ::dbtools::CharsetIteratorDerefHelper& _rBase, const ::rtl::OUString& _rDisplayName);
};
//-------------------------------------------------------------------------
//- OCharsetDisplay::ExtendedCharsetIterator
//-------------------------------------------------------------------------
class OCharsetDisplay::ExtendedCharsetIterator
{
friend class OCharsetDisplay;
friend bool operator==(const ExtendedCharsetIterator& lhs, const ExtendedCharsetIterator& rhs);
friend bool operator!=(const ExtendedCharsetIterator& lhs, const ExtendedCharsetIterator& rhs) { return !(lhs == rhs); }
typedef ::dbtools::OCharsetMap container;
typedef container::CharsetIterator base_iterator;
protected:
const OCharsetDisplay* m_pContainer;
base_iterator m_aPosition;
public:
ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource);
CharsetDisplayDerefHelper operator*() const;
/// prefix increment
const ExtendedCharsetIterator& operator++();
/// postfix increment
const ExtendedCharsetIterator operator++(int) { ExtendedCharsetIterator hold(*this); ++*this; return hold; }
/// prefix decrement
const ExtendedCharsetIterator& operator--();
/// postfix decrement
const ExtendedCharsetIterator operator--(int) { ExtendedCharsetIterator hold(*this); --*this; return hold; }
protected:
ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition );
};
//.........................................................................
} // namespace dbaui
//.........................................................................
#endif // _DBAUI_CHARSETS_HXX_
<|endoftext|>
|
<commit_before>/**
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "base/util/utils.h"
#include "base/util/Wstring.h"
#include "vocl/VObject.h"
#include "string.h"
VObject::VObject() {
productID = NULL;
version = NULL;
properties = new ArrayList();
}
VObject::~VObject() {
if (productID) {
delete [] productID; productID = NULL;
}
if (version) {
delete [] version; version = NULL;
}
if (properties) {
delete properties; properties = NULL;
}
}
void VObject::set(wchar_t** p, wchar_t* v) {
if (*p) {
delete [] *p;
}
*p = (v) ? wstrdup(v) : NULL;
}
void VObject::setVersion(wchar_t* ver) {
set(&version, ver);
}
void VObject::setProdID(wchar_t* prodID) {
set(&productID, prodID);
}
wchar_t* VObject::getVersion() {
return version;
}
wchar_t* VObject::getProdID() {
return productID;
}
void VObject::addProperty(VProperty* vProp) {
properties->add((ArrayElement&) *vProp);
}
int VObject::propertiesCount() {
return properties->size();
}
bool VObject::removeProperty(int index) {
if(index < 0 || index >= propertiesCount())
return false;
properties->remove(index);
return true;
}
void VObject::removeProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
properties->remove(i);
break;
}
}
}
bool VObject::containsProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
return true;
}
}
return false;
}
VProperty* VObject::getProperty(int index) {
return (VProperty*)properties->get(index);
}
VProperty* VObject::getProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
return property;
}
}
return NULL;
}
wchar_t* VObject::toString() {
wchar_t* strVObject = new wchar_t[VOBJECT_BUFFER];
wcscpy(strVObject,TEXT(""));
wchar_t* eof = new wchar_t[EOF_LENGHT];
if(version && !wcscmp(version,TEXT("3.0")))
wcscpy(eof, TEXT("\n"));
else
wcscpy(eof, TEXT("\r\n"));
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty*)properties->get(i);
if(property->containsParameter(TEXT("GROUP"))) {
wcscat(strVObject,property->getParameterValue(TEXT("GROUP")));
wcscat(strVObject,TEXT("."));
property->removeParameter(TEXT("GROUP"));
}
wcscat(strVObject,property->getName());
for(int k=0; k<property->parameterCount(); k++) {
wcscat(strVObject,TEXT(";"));
wchar_t* paramName = new wchar_t[wcslen(property->getParameter(k))+1];
wcscpy(paramName, property->getParameter(k));
wcscat(strVObject,paramName);
const wchar_t *value = property->getParameterValue(k);
if(value) {
wcscat(strVObject,TEXT("="));
wcscat(strVObject,value);
}
delete [] paramName; paramName = NULL;
}
wcscat(strVObject,TEXT(":"));
if(property->getValue()) {
if(property->equalsEncoding(TEXT("BASE64"))) {
wchar_t delim[] = TEXT("\r\n ");
int fold = 76;
int sizeOfValue = int(wcslen(property->getValue()));
int size = sizeOfValue + (int)(sizeOfValue/fold + 2)*int(wcslen(delim));
int index = 0;
wchar_t* output = new wchar_t[size + 1];
wcscpy(output, TEXT("\0"));
wcscat(output, delim);
while (index<sizeOfValue)
{
wcsncat(output,property->getValue()+index,fold);
wcscat(output,delim);
index+=fold;
}
wcscat(strVObject,output);
delete [] output;
}
else
wcscat(strVObject,property->getValue());
}
wcscat(strVObject,eof);
//if(property->equalsEncoding(TEXT("BASE64")) && !wcscmp(version,TEXT("2.1")))
// wcscat(strVObject, eof);
}
if (wcschr(strVObject, '&') || wcschr(strVObject, '&')) {
WString tmp = strVObject;
tmp.replaceAll(TEXT("&"), TEXT("&"));
tmp.replaceAll(TEXT("<"), TEXT("<"));
wcscpy(strVObject,tmp.c_str());
}
return strVObject;
}
void VObject::insertProperty(VProperty* property) {
if (propertiesCount() == 0 || wcscmp(getProperty(propertiesCount()-1)->getName(),TEXT("END")))
addProperty(property);
else {
VProperty* lastProperty = getProperty(TEXT("END"));
removeProperty(TEXT("END"));
addProperty(property);
addProperty(lastProperty);
}
}
void VObject::addFirstProperty(VProperty* property) {
properties->add(0,(ArrayElement&)*property);
}
void VObject::removeAllProperies(wchar_t* propName) {
for(int i = 0, m = propertiesCount(); i < m ; i++)
if(!wcscmp(getProperty(i)->getName(), propName)) {
removeProperty(i);
--i;
--m;
}
}
// Patrick Ohly: hack below, see header file
static int hex2int( wchar_t x )
{
return (x >= '0' && x <= '9') ? x - '0' :
(x >= 'A' && x <= 'F') ? x - 'A' + 10 :
(x >= 'a' && x <= 'f') ? x - 'a' + 10 :
0;
}
#define SEMICOLON_REPLACEMENT '\a'
void VObject::toNativeEncoding()
{
BOOL is_30 = !wcscmp(getVersion(), TEXT("3.0"));
// line break is encoded with either one or two
// characters on different platforms
const int linebreaklen = wcslen(SYNC4J_LINEBREAK);
for (int index = propertiesCount() - 1; index >= 0; index--) {
VProperty *vprop = getProperty(index);
wchar_t *foreign = vprop->getValue();
// the native encoding is always shorter than the foreign one
wchar_t *native = new wchar_t[wcslen(foreign) + 1];
if (vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
int in = 0, out = 0;
wchar_t curr;
// this is a very crude quoted-printable decoder,
// based on Wikipedia's explanation of quoted-printable
while ((curr = foreign[in]) != 0) {
in++;
if (curr == '=') {
wchar_t values[2];
values[0] = foreign[in];
in++;
if (!values[0]) {
// incomplete?!
break;
}
values[1] = foreign[in];
in++;
if (values[0] == '\r' && values[1] == '\n') {
// soft line break, ignore it
} else {
native[out] = (hex2int(values[0]) << 4) |
hex2int(values[1]);
out++;
// replace \r\n with \n?
if ( linebreaklen == 1 &&
out >= 2 &&
native[out - 2] == '\r' &&
native[out - 1] == '\n' ) {
native[out - 2] = SYNC4J_LINEBREAK[0];
out--;
}
// the conversion to wchar on Windows is
// probably missing here
}
} else {
native[out] = curr;
out++;
}
}
native[out] = 0;
out++;
} else {
wcscpy(native, foreign);
}
// decode escaped characters after backslash:
// \n is line break only in 3.0
wchar_t curr;
int in = 0, out = 0;
while ((curr = native[in]) != 0) {
in++;
switch (curr) {
case '\\':
curr = native[in];
in++;
switch (curr) {
case 'n':
if (is_30) {
// replace with line break
wcsncpy(native + out, SYNC4J_LINEBREAK, linebreaklen);
out += linebreaklen;
} else {
// normal escaped character
native[out] = curr;
out++;
}
break;
case 0:
// unexpected end of string
break;
default:
// just copy next character
native[out] = curr;
out++;
break;
}
break;
case ';':
// field separator - must replace with something special
// so that we can encode it again in fromNativeEncoding()
native[out] = SEMICOLON_REPLACEMENT;
out++;
break;
default:
native[out] = curr;
out++;
}
}
native[out] = 0;
out++;
vprop->setValue(native);
delete [] native;
}
}
void VObject::fromNativeEncoding()
{
BOOL is_30 = !wcscmp(getVersion(), TEXT("3.0"));
for (int index = propertiesCount() - 1; index >= 0; index--) {
VProperty *vprop = getProperty(index);
if (vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
// remove this, we cannot recreate it
vprop->removeParameter(TEXT("ENCODING"));
}
wchar_t *native = vprop->getValue();
// in the worst case every comma/linebreak is replaced with
// two characters and each \n with =0D=0A
wchar_t *foreign = new wchar_t[6 * wcslen(native) + 1];
wchar_t curr;
int in = 0, out = 0;
// line break is encoded with either one or two
// characters on different platforms
const int linebreaklen = wcslen(SYNC4J_LINEBREAK);
// use backslash for special characters,
// if necessary do quoted-printable encoding
bool doquoted = !is_30 &&
wcsstr(native, SYNC4J_LINEBREAK) != NULL;
while ((curr = native[in]) != 0) {
in++;
switch (curr) {
case ',':
if (!is_30) {
// normal character
foreign[out] = curr;
out++;
break;
}
// no break!
case ';':
case '\\':
foreign[out] = '\\';
out++;
foreign[out] = curr;
out++;
break;
case SEMICOLON_REPLACEMENT:
foreign[out] = ';';
out++;
break;
default:
if (doquoted &&
(curr == '=' || (unsigned char)curr >= 128)) {
// escape = and non-ASCII characters
wsprintf(foreign + out, TEXT("=%02X"), (unsigned int)(unsigned char)curr);
out += 3;
} else if (!wcsncmp(native + in - 1,
SYNC4J_LINEBREAK,
linebreaklen)) {
// line break
if (is_30) {
foreign[out] = '\\';
out++;
foreign[out] = 'n';
out++;
} else {
wcscpy(foreign + out, TEXT("=0D=0A"));
out += 6;
}
in += linebreaklen - 1;
} else {
foreign[out] = curr;
out++;
}
break;
}
}
foreign[out] = 0;
vprop->setValue(foreign);
delete [] foreign;
if (doquoted) {
// we have used quoted-printable encoding
vprop->addParameter(TEXT("ENCODING"), TEXT("QUOTED-PRINTABLE"));
}
}
}
<commit_msg>corrected a condition<commit_after>/**
* Copyright (C) 2003-2006 Funambol
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "base/util/utils.h"
#include "base/util/Wstring.h"
#include "vocl/VObject.h"
#include "string.h"
VObject::VObject() {
productID = NULL;
version = NULL;
properties = new ArrayList();
}
VObject::~VObject() {
if (productID) {
delete [] productID; productID = NULL;
}
if (version) {
delete [] version; version = NULL;
}
if (properties) {
delete properties; properties = NULL;
}
}
void VObject::set(wchar_t** p, wchar_t* v) {
if (*p) {
delete [] *p;
}
*p = (v) ? wstrdup(v) : NULL;
}
void VObject::setVersion(wchar_t* ver) {
set(&version, ver);
}
void VObject::setProdID(wchar_t* prodID) {
set(&productID, prodID);
}
wchar_t* VObject::getVersion() {
return version;
}
wchar_t* VObject::getProdID() {
return productID;
}
void VObject::addProperty(VProperty* vProp) {
properties->add((ArrayElement&) *vProp);
}
int VObject::propertiesCount() {
return properties->size();
}
bool VObject::removeProperty(int index) {
if(index < 0 || index >= propertiesCount())
return false;
properties->remove(index);
return true;
}
void VObject::removeProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
properties->remove(i);
break;
}
}
}
bool VObject::containsProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
return true;
}
}
return false;
}
VProperty* VObject::getProperty(int index) {
return (VProperty*)properties->get(index);
}
VProperty* VObject::getProperty(wchar_t* propName) {
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty* )properties->get(i);
if(!wcscmp(property->getName(), propName)) {
return property;
}
}
return NULL;
}
wchar_t* VObject::toString() {
wchar_t* strVObject = new wchar_t[VOBJECT_BUFFER];
wcscpy(strVObject,TEXT(""));
wchar_t* eof = new wchar_t[EOF_LENGHT];
if(version && !wcscmp(version,TEXT("3.0")))
wcscpy(eof, TEXT("\n"));
else
wcscpy(eof, TEXT("\r\n"));
for (int i=0; i<properties->size(); i++) {
VProperty *property;
property = (VProperty*)properties->get(i);
if(property->containsParameter(TEXT("GROUP"))) {
wcscat(strVObject,property->getParameterValue(TEXT("GROUP")));
wcscat(strVObject,TEXT("."));
property->removeParameter(TEXT("GROUP"));
}
wcscat(strVObject,property->getName());
for(int k=0; k<property->parameterCount(); k++) {
wcscat(strVObject,TEXT(";"));
wchar_t* paramName = new wchar_t[wcslen(property->getParameter(k))+1];
wcscpy(paramName, property->getParameter(k));
wcscat(strVObject,paramName);
const wchar_t *value = property->getParameterValue(k);
if(value) {
wcscat(strVObject,TEXT("="));
wcscat(strVObject,value);
}
delete [] paramName; paramName = NULL;
}
wcscat(strVObject,TEXT(":"));
if(property->getValue()) {
if(property->equalsEncoding(TEXT("BASE64"))) {
wchar_t delim[] = TEXT("\r\n ");
int fold = 76;
int sizeOfValue = int(wcslen(property->getValue()));
int size = sizeOfValue + (int)(sizeOfValue/fold + 2)*int(wcslen(delim));
int index = 0;
wchar_t* output = new wchar_t[size + 1];
wcscpy(output, TEXT("\0"));
wcscat(output, delim);
while (index<sizeOfValue)
{
wcsncat(output,property->getValue()+index,fold);
wcscat(output,delim);
index+=fold;
}
wcscat(strVObject,output);
delete [] output;
}
else
wcscat(strVObject,property->getValue());
}
wcscat(strVObject,eof);
//if(property->equalsEncoding(TEXT("BASE64")) && !wcscmp(version,TEXT("2.1")))
// wcscat(strVObject, eof);
}
if (wcschr(strVObject, '&') || wcschr(strVObject, '<')) {
WString tmp = strVObject;
tmp.replaceAll(TEXT("&"), TEXT("&"));
tmp.replaceAll(TEXT("<"), TEXT("<"));
wcscpy(strVObject,tmp.c_str());
}
return strVObject;
}
void VObject::insertProperty(VProperty* property) {
if (propertiesCount() == 0 || wcscmp(getProperty(propertiesCount()-1)->getName(),TEXT("END")))
addProperty(property);
else {
VProperty* lastProperty = getProperty(TEXT("END"));
removeProperty(TEXT("END"));
addProperty(property);
addProperty(lastProperty);
}
}
void VObject::addFirstProperty(VProperty* property) {
properties->add(0,(ArrayElement&)*property);
}
void VObject::removeAllProperies(wchar_t* propName) {
for(int i = 0, m = propertiesCount(); i < m ; i++)
if(!wcscmp(getProperty(i)->getName(), propName)) {
removeProperty(i);
--i;
--m;
}
}
// Patrick Ohly: hack below, see header file
static int hex2int( wchar_t x )
{
return (x >= '0' && x <= '9') ? x - '0' :
(x >= 'A' && x <= 'F') ? x - 'A' + 10 :
(x >= 'a' && x <= 'f') ? x - 'a' + 10 :
0;
}
#define SEMICOLON_REPLACEMENT '\a'
void VObject::toNativeEncoding()
{
BOOL is_30 = !wcscmp(getVersion(), TEXT("3.0"));
// line break is encoded with either one or two
// characters on different platforms
const int linebreaklen = wcslen(SYNC4J_LINEBREAK);
for (int index = propertiesCount() - 1; index >= 0; index--) {
VProperty *vprop = getProperty(index);
wchar_t *foreign = vprop->getValue();
// the native encoding is always shorter than the foreign one
wchar_t *native = new wchar_t[wcslen(foreign) + 1];
if (vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
int in = 0, out = 0;
wchar_t curr;
// this is a very crude quoted-printable decoder,
// based on Wikipedia's explanation of quoted-printable
while ((curr = foreign[in]) != 0) {
in++;
if (curr == '=') {
wchar_t values[2];
values[0] = foreign[in];
in++;
if (!values[0]) {
// incomplete?!
break;
}
values[1] = foreign[in];
in++;
if (values[0] == '\r' && values[1] == '\n') {
// soft line break, ignore it
} else {
native[out] = (hex2int(values[0]) << 4) |
hex2int(values[1]);
out++;
// replace \r\n with \n?
if ( linebreaklen == 1 &&
out >= 2 &&
native[out - 2] == '\r' &&
native[out - 1] == '\n' ) {
native[out - 2] = SYNC4J_LINEBREAK[0];
out--;
}
// the conversion to wchar on Windows is
// probably missing here
}
} else {
native[out] = curr;
out++;
}
}
native[out] = 0;
out++;
} else {
wcscpy(native, foreign);
}
// decode escaped characters after backslash:
// \n is line break only in 3.0
wchar_t curr;
int in = 0, out = 0;
while ((curr = native[in]) != 0) {
in++;
switch (curr) {
case '\\':
curr = native[in];
in++;
switch (curr) {
case 'n':
if (is_30) {
// replace with line break
wcsncpy(native + out, SYNC4J_LINEBREAK, linebreaklen);
out += linebreaklen;
} else {
// normal escaped character
native[out] = curr;
out++;
}
break;
case 0:
// unexpected end of string
break;
default:
// just copy next character
native[out] = curr;
out++;
break;
}
break;
case ';':
// field separator - must replace with something special
// so that we can encode it again in fromNativeEncoding()
native[out] = SEMICOLON_REPLACEMENT;
out++;
break;
default:
native[out] = curr;
out++;
}
}
native[out] = 0;
out++;
vprop->setValue(native);
delete [] native;
}
}
void VObject::fromNativeEncoding()
{
BOOL is_30 = !wcscmp(getVersion(), TEXT("3.0"));
for (int index = propertiesCount() - 1; index >= 0; index--) {
VProperty *vprop = getProperty(index);
if (vprop->equalsEncoding(TEXT("QUOTED-PRINTABLE"))) {
// remove this, we cannot recreate it
vprop->removeParameter(TEXT("ENCODING"));
}
wchar_t *native = vprop->getValue();
// in the worst case every comma/linebreak is replaced with
// two characters and each \n with =0D=0A
wchar_t *foreign = new wchar_t[6 * wcslen(native) + 1];
wchar_t curr;
int in = 0, out = 0;
// line break is encoded with either one or two
// characters on different platforms
const int linebreaklen = wcslen(SYNC4J_LINEBREAK);
// use backslash for special characters,
// if necessary do quoted-printable encoding
bool doquoted = !is_30 &&
wcsstr(native, SYNC4J_LINEBREAK) != NULL;
while ((curr = native[in]) != 0) {
in++;
switch (curr) {
case ',':
if (!is_30) {
// normal character
foreign[out] = curr;
out++;
break;
}
// no break!
case ';':
case '\\':
foreign[out] = '\\';
out++;
foreign[out] = curr;
out++;
break;
case SEMICOLON_REPLACEMENT:
foreign[out] = ';';
out++;
break;
default:
if (doquoted &&
(curr == '=' || (unsigned char)curr >= 128)) {
// escape = and non-ASCII characters
wsprintf(foreign + out, TEXT("=%02X"), (unsigned int)(unsigned char)curr);
out += 3;
} else if (!wcsncmp(native + in - 1,
SYNC4J_LINEBREAK,
linebreaklen)) {
// line break
if (is_30) {
foreign[out] = '\\';
out++;
foreign[out] = 'n';
out++;
} else {
wcscpy(foreign + out, TEXT("=0D=0A"));
out += 6;
}
in += linebreaklen - 1;
} else {
foreign[out] = curr;
out++;
}
break;
}
}
foreign[out] = 0;
vprop->setValue(foreign);
delete [] foreign;
if (doquoted) {
// we have used quoted-printable encoding
vprop->addParameter(TEXT("ENCODING"), TEXT("QUOTED-PRINTABLE"));
}
}
}
<|endoftext|>
|
<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2019 Antti Nuortimo.
//
// 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 <https://www.gnu.org/licenses/>.
#ifndef __CSV_LOADER_HPP_INCLUDED
#define __CSV_LOADER_HPP_INCLUDED
#include "code/ylikuutio/file/file_loader.hpp"
#include "code/ylikuutio/string/ylikuutio_string.hpp"
// Include standard headers
#include <cstddef> // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory> // std::make_shared, std::shared_ptr
#include <string> // std::string
#include <vector> // std::vector
namespace yli
{
namespace load
{
template<class T1>
std::shared_ptr<std::vector<T1>> load_CSV_file(
const std::string& csv_filename,
std::size_t& data_width,
std::size_t& data_height,
std::size_t& data_size)
{
// Open the file
std::shared_ptr<std::string> file_content = yli::file::slurp(csv_filename);
if (file_content == nullptr || file_content->empty())
{
std::cerr << csv_filename << " could not be opened, or the file is empty.\n";
return nullptr;
}
// Assume that all lines have equal number of elements.
// If any lines has number of elements different than the first line with elements,
// that is an error and `nullptr` will be returned and `data_width`, `data_height`,
// and `data_size` are set to 0.
// However, lines with 0 elements are allowed at any time.
// Initialize output values to 0 in case that loading fails due to an error.
data_width = 0;
data_height = 0;
data_size = 0;
std::size_t file_content_i = 0;
std::size_t n_lines = 0;
std::size_t n_elements_in_first_line = 0;
std::size_t n_elements_in_current_line = 0;
const char* const char_end_string = ", \n";
std::shared_ptr<std::vector<T1>> data_vector = std::make_shared<std::vector<T1>>();
while (file_content_i < file_content->size())
{
// All possible block identifier strings.
const std::vector<std::string> whitespace_strings = { ",", " ", "\n" };
while (yli::string::check_and_report_if_some_string_matches(*file_content, file_content_i, whitespace_strings))
{
if (file_content_i < file_content->size() && (*file_content)[file_content_i] == '\n')
{
// Newline was found.
if (n_elements_in_current_line > 0)
{
// This line was not empty.
n_lines++;
if (n_elements_in_first_line == 0)
{
// This was the first non-empty line.
n_elements_in_first_line = n_elements_in_current_line;
}
else if (n_elements_in_current_line != n_elements_in_first_line)
{
// This line has a different number of elements than the first line.
// All non-empty lines are expected to have the same number of elements,
// so that the data can be entered in a matrix.
return nullptr;
}
}
// Next line begins now.
n_elements_in_current_line = 0;
}
file_content_i++;
}
if (file_content_i >= file_content->size())
{
break;
}
T1 value = 0;
yli::string::extract_value_from_string(*file_content, file_content_i, char_end_string, nullptr, value);
data_vector->push_back(value);
n_elements_in_current_line++;
while (file_content_i < file_content->size() && !yli::string::check_and_report_if_some_string_matches(*file_content, file_content_i, whitespace_strings))
{
file_content_i++;
}
}
if (n_elements_in_current_line > 0)
{
// This last line was not an empty line.
n_lines++;
if (n_elements_in_current_line != n_elements_in_first_line)
{
// This line has a different number of elements than the first line.
// All non-empty lines are expected to have the same number of elements,
// so that the data can be entered in a matrix.
std::cout << "n_elements_in_current_line = " << n_elements_in_current_line << "\n";
std::cout << "n_elements_in_first_line = " << n_elements_in_first_line << "\n";
return nullptr;
}
}
data_width = n_elements_in_first_line;
data_height = n_lines;
data_size = n_lines * n_elements_in_first_line;
data_size = data_vector->size();
return data_vector;
}
}
}
#endif
<commit_msg>`yli::load::load_CSV_file`: `csv_filename` -> `filename`.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2019 Antti Nuortimo.
//
// 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 <https://www.gnu.org/licenses/>.
#ifndef __CSV_LOADER_HPP_INCLUDED
#define __CSV_LOADER_HPP_INCLUDED
#include "code/ylikuutio/file/file_loader.hpp"
#include "code/ylikuutio/string/ylikuutio_string.hpp"
// Include standard headers
#include <cstddef> // std::size_t
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory> // std::make_shared, std::shared_ptr
#include <string> // std::string
#include <vector> // std::vector
namespace yli
{
namespace load
{
template<class T1>
std::shared_ptr<std::vector<T1>> load_CSV_file(
const std::string& filename,
std::size_t& data_width,
std::size_t& data_height,
std::size_t& data_size)
{
// Open the file
std::shared_ptr<std::string> file_content = yli::file::slurp(filename);
if (file_content == nullptr || file_content->empty())
{
std::cerr << filename << " could not be opened, or the file is empty.\n";
return nullptr;
}
// Assume that all lines have equal number of elements.
// If any lines has number of elements different than the first line with elements,
// that is an error and `nullptr` will be returned and `data_width`, `data_height`,
// and `data_size` are set to 0.
// However, lines with 0 elements are allowed at any time.
// Initialize output values to 0 in case that loading fails due to an error.
data_width = 0;
data_height = 0;
data_size = 0;
std::size_t file_content_i = 0;
std::size_t n_lines = 0;
std::size_t n_elements_in_first_line = 0;
std::size_t n_elements_in_current_line = 0;
const char* const char_end_string = ", \n";
std::shared_ptr<std::vector<T1>> data_vector = std::make_shared<std::vector<T1>>();
while (file_content_i < file_content->size())
{
// All possible block identifier strings.
const std::vector<std::string> whitespace_strings = { ",", " ", "\n" };
while (yli::string::check_and_report_if_some_string_matches(*file_content, file_content_i, whitespace_strings))
{
if (file_content_i < file_content->size() && (*file_content)[file_content_i] == '\n')
{
// Newline was found.
if (n_elements_in_current_line > 0)
{
// This line was not empty.
n_lines++;
if (n_elements_in_first_line == 0)
{
// This was the first non-empty line.
n_elements_in_first_line = n_elements_in_current_line;
}
else if (n_elements_in_current_line != n_elements_in_first_line)
{
// This line has a different number of elements than the first line.
// All non-empty lines are expected to have the same number of elements,
// so that the data can be entered in a matrix.
return nullptr;
}
}
// Next line begins now.
n_elements_in_current_line = 0;
}
file_content_i++;
}
if (file_content_i >= file_content->size())
{
break;
}
T1 value = 0;
yli::string::extract_value_from_string(*file_content, file_content_i, char_end_string, nullptr, value);
data_vector->push_back(value);
n_elements_in_current_line++;
while (file_content_i < file_content->size() && !yli::string::check_and_report_if_some_string_matches(*file_content, file_content_i, whitespace_strings))
{
file_content_i++;
}
}
if (n_elements_in_current_line > 0)
{
// This last line was not an empty line.
n_lines++;
if (n_elements_in_current_line != n_elements_in_first_line)
{
// This line has a different number of elements than the first line.
// All non-empty lines are expected to have the same number of elements,
// so that the data can be entered in a matrix.
std::cout << "n_elements_in_current_line = " << n_elements_in_current_line << "\n";
std::cout << "n_elements_in_first_line = " << n_elements_in_first_line << "\n";
return nullptr;
}
}
data_width = n_elements_in_first_line;
data_height = n_lines;
data_size = n_lines * n_elements_in_first_line;
data_size = data_vector->size();
return data_vector;
}
}
}
#endif
<|endoftext|>
|
<commit_before>//===- AnalysisOrderChecker - Print callbacks called ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This checker prints callbacks that are called during analysis.
// This is required to ensure that callbacks are fired in order
// and do not duplicate or get lost.
// Feel free to extend this checker with any callback you need to check.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/AST/ExprCXX.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
using namespace clang;
using namespace ento;
namespace {
class AnalysisOrderChecker
: public Checker<check::PreStmt<CastExpr>,
check::PostStmt<CastExpr>,
check::PreStmt<ArraySubscriptExpr>,
check::PostStmt<ArraySubscriptExpr>,
check::PreStmt<CXXNewExpr>,
check::PostStmt<CXXNewExpr>,
check::PreStmt<OffsetOfExpr>,
check::PostStmt<OffsetOfExpr>,
check::PreCall,
check::PostCall,
check::NewAllocator,
check::Bind,
check::RegionChanges,
check::LiveSymbols> {
bool isCallbackEnabled(AnalyzerOptions &Opts, StringRef CallbackName) const {
return Opts.getBooleanOption("*", false, this) ||
Opts.getBooleanOption(CallbackName, false, this);
}
bool isCallbackEnabled(CheckerContext &C, StringRef CallbackName) const {
AnalyzerOptions &Opts = C.getAnalysisManager().getAnalyzerOptions();
return isCallbackEnabled(Opts, CallbackName);
}
bool isCallbackEnabled(ProgramStateRef State, StringRef CallbackName) const {
AnalyzerOptions &Opts = State->getStateManager().getOwningEngine()
->getAnalysisManager().getAnalyzerOptions();
return isCallbackEnabled(Opts, CallbackName);
}
public:
void checkPreStmt(const CastExpr *CE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtCastExpr"))
llvm::errs() << "PreStmt<CastExpr> (Kind : " << CE->getCastKindName()
<< ")\n";
}
void checkPostStmt(const CastExpr *CE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtCastExpr"))
llvm::errs() << "PostStmt<CastExpr> (Kind : " << CE->getCastKindName()
<< ")\n";
}
void checkPreStmt(const ArraySubscriptExpr *SubExpr,
CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtArraySubscriptExpr"))
llvm::errs() << "PreStmt<ArraySubscriptExpr>\n";
}
void checkPostStmt(const ArraySubscriptExpr *SubExpr,
CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtArraySubscriptExpr"))
llvm::errs() << "PostStmt<ArraySubscriptExpr>\n";
}
void checkPreStmt(const CXXNewExpr *NE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtCXXNewExpr"))
llvm::errs() << "PreStmt<CXXNewExpr>\n";
}
void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtCXXNewExpr"))
llvm::errs() << "PostStmt<CXXNewExpr>\n";
}
void checkPreStmt(const OffsetOfExpr *OOE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtOffsetOfExpr"))
llvm::errs() << "PreStmt<OffsetOfExpr>\n";
}
void checkPostStmt(const OffsetOfExpr *OOE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtOffsetOfExpr"))
llvm::errs() << "PostStmt<OffsetOfExpr>\n";
}
void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreCall")) {
llvm::errs() << "PreCall";
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Call.getDecl()))
llvm::errs() << " (" << ND->getQualifiedNameAsString() << ')';
llvm::errs() << '\n';
}
}
void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostCall")) {
llvm::errs() << "PostCall";
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Call.getDecl()))
llvm::errs() << " (" << ND->getQualifiedNameAsString() << ')';
llvm::errs() << '\n';
}
}
void checkNewAllocator(const CXXNewExpr *CNE, SVal Target,
CheckerContext &C) const {
if (isCallbackEnabled(C, "NewAllocator"))
llvm::errs() << "NewAllocator\n";
}
void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const {
if (isCallbackEnabled(C, "Bind"))
llvm::errs() << "Bind\n";
}
void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SymReaper) const {
if (isCallbackEnabled(State, "LiveSymbols"))
llvm::errs() << "LiveSymbols\n";
}
ProgramStateRef
checkRegionChanges(ProgramStateRef State,
const InvalidatedSymbols *Invalidated,
ArrayRef<const MemRegion *> ExplicitRegions,
ArrayRef<const MemRegion *> Regions,
const LocationContext *LCtx, const CallEvent *Call) const {
if (isCallbackEnabled(State, "RegionChanges"))
llvm::errs() << "RegionChanges\n";
return State;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Registration.
//===----------------------------------------------------------------------===//
void ento::registerAnalysisOrderChecker(CheckerManager &mgr) {
mgr.registerChecker<AnalysisOrderChecker>();
}
<commit_msg>[analyzer] operator new: Fix callback order for CXXNewExpr.<commit_after>//===- AnalysisOrderChecker - Print callbacks called ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This checker prints callbacks that are called during analysis.
// This is required to ensure that callbacks are fired in order
// and do not duplicate or get lost.
// Feel free to extend this checker with any callback you need to check.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/AST/ExprCXX.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
using namespace clang;
using namespace ento;
namespace {
class AnalysisOrderChecker
: public Checker<check::PreStmt<CastExpr>,
check::PostStmt<CastExpr>,
check::PreStmt<ArraySubscriptExpr>,
check::PostStmt<ArraySubscriptExpr>,
check::PreStmt<CXXNewExpr>,
check::PostStmt<CXXNewExpr>,
check::PreCall,
check::PostCall,
check::NewAllocator,
check::Bind,
check::RegionChanges,
check::LiveSymbols> {
bool isCallbackEnabled(AnalyzerOptions &Opts, StringRef CallbackName) const {
return Opts.getBooleanOption("*", false, this) ||
Opts.getBooleanOption(CallbackName, false, this);
}
bool isCallbackEnabled(CheckerContext &C, StringRef CallbackName) const {
AnalyzerOptions &Opts = C.getAnalysisManager().getAnalyzerOptions();
return isCallbackEnabled(Opts, CallbackName);
}
bool isCallbackEnabled(ProgramStateRef State, StringRef CallbackName) const {
AnalyzerOptions &Opts = State->getStateManager().getOwningEngine()
->getAnalysisManager().getAnalyzerOptions();
return isCallbackEnabled(Opts, CallbackName);
}
public:
void checkPreStmt(const CastExpr *CE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtCastExpr"))
llvm::errs() << "PreStmt<CastExpr> (Kind : " << CE->getCastKindName()
<< ")\n";
}
void checkPostStmt(const CastExpr *CE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtCastExpr"))
llvm::errs() << "PostStmt<CastExpr> (Kind : " << CE->getCastKindName()
<< ")\n";
}
void checkPreStmt(const ArraySubscriptExpr *SubExpr,
CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtArraySubscriptExpr"))
llvm::errs() << "PreStmt<ArraySubscriptExpr>\n";
}
void checkPostStmt(const ArraySubscriptExpr *SubExpr,
CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtArraySubscriptExpr"))
llvm::errs() << "PostStmt<ArraySubscriptExpr>\n";
}
void checkPreStmt(const CXXNewExpr *NE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreStmtCXXNewExpr"))
llvm::errs() << "PreStmt<CXXNewExpr>\n";
}
void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostStmtCXXNewExpr"))
llvm::errs() << "PostStmt<CXXNewExpr>\n";
}
void checkPreCall(const CallEvent &Call, CheckerContext &C) const {
if (isCallbackEnabled(C, "PreCall")) {
llvm::errs() << "PreCall";
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Call.getDecl()))
llvm::errs() << " (" << ND->getQualifiedNameAsString() << ')';
llvm::errs() << '\n';
}
}
void checkPostCall(const CallEvent &Call, CheckerContext &C) const {
if (isCallbackEnabled(C, "PostCall")) {
llvm::errs() << "PostCall";
if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Call.getDecl()))
llvm::errs() << " (" << ND->getQualifiedNameAsString() << ')';
llvm::errs() << '\n';
}
}
void checkNewAllocator(const CXXNewExpr *CNE, SVal Target,
CheckerContext &C) const {
if (isCallbackEnabled(C, "NewAllocator"))
llvm::errs() << "NewAllocator\n";
}
void checkBind(SVal Loc, SVal Val, const Stmt *S, CheckerContext &C) const {
if (isCallbackEnabled(C, "Bind"))
llvm::errs() << "Bind\n";
}
void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SymReaper) const {
if (isCallbackEnabled(State, "LiveSymbols"))
llvm::errs() << "LiveSymbols\n";
}
ProgramStateRef
checkRegionChanges(ProgramStateRef State,
const InvalidatedSymbols *Invalidated,
ArrayRef<const MemRegion *> ExplicitRegions,
ArrayRef<const MemRegion *> Regions,
const LocationContext *LCtx, const CallEvent *Call) const {
if (isCallbackEnabled(State, "RegionChanges"))
llvm::errs() << "RegionChanges\n";
return State;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Registration.
//===----------------------------------------------------------------------===//
void ento::registerAnalysisOrderChecker(CheckerManager &mgr) {
mgr.registerChecker<AnalysisOrderChecker>();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: interfacecontainer.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: dbo $ $Date: 2001-06-07 11:11:28 $
*
* 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 _CPPUHELPER_INTERFACECONTAINER_HXX_
#define _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.h>
#define CONT_HASHMAP ::std::hash_map< key , void* , hashImpl , equalImpl >
namespace cppu
{
template< class key , class hashImpl , class equalImpl >
inline OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::OMultiTypeInterfaceContainerHelperVar( ::osl::Mutex & rMutex_ )
SAL_THROW( () )
: rMutex( rMutex_ )
{
m_pMap = new CONT_HASHMAP;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
inline OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::~OMultiTypeInterfaceContainerHelperVar()
SAL_THROW( () )
{
CONT_HASHMAP::iterator iter = m_pMap->begin();
CONT_HASHMAP::iterator end = m_pMap->end();
while( iter != end )
{
delete (OInterfaceContainerHelper*)(*iter).second;
(*iter).second = 0;
++iter;
}
delete m_pMap;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
inline ::com::sun::star::uno::Sequence< key > OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::getContainedTypes() const
SAL_THROW( () )
{
CONT_HASHMAP::size_type nSize;
::osl::MutexGuard aGuard( rMutex );
if( nSize = m_pMap->size() )
{
::com::sun::star::uno::Sequence< key > aInterfaceTypes( nSize );
key * pArray = aInterfaceTypes.getArray();
CONT_HASHMAP::iterator iter = m_pMap->begin();
CONT_HASHMAP::iterator end = m_pMap->end();
sal_Int32 i = 0;
while( iter != end )
{
// are interfaces added to this container?
if( ((OInterfaceContainerHelper*)(*iter).second)->getLength() )
// yes, put the type in the array
pArray[i++] = (*iter).first;
iter++;
}
if( i != nSize ) {
// may be empty container, reduce the sequence to the right size
aInterfaceTypes = ::com::sun::star::uno::Sequence<key>( pArray, i );
}
return aInterfaceTypes;
}
return ::com::sun::star::uno::Sequence<key>();
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
OInterfaceContainerHelper * OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::getContainer(
const key & rKey ) const SAL_THROW( () )
{
::osl::MutexGuard aGuard( rMutex );
CONT_HASHMAP::iterator iter = m_pMap->find( rKey );
if( iter != m_pMap->end() )
return (OInterfaceContainerHelper*) (*iter).second;
return 0;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
sal_Int32 OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::addInterface(
const key & rKey,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & rListener )
SAL_THROW( () )
{
::osl::MutexGuard aGuard( rMutex );
CONT_HASHMAP::iterator
iter = m_pMap->find( rKey );
if( iter == m_pMap->end() )
{
OInterfaceContainerHelper * pLC = new OInterfaceContainerHelper( rMutex );
(*m_pMap)[rKey] = pLC;
return pLC->addInterface( rListener );
}
else
return ((OInterfaceContainerHelper*)(*iter).second)->addInterface( rListener );
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
inline sal_Int32 OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::removeInterface(
const key & rKey,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & rListener )
SAL_THROW( () )
{
::osl::MutexGuard aGuard( rMutex );
// search container with id nUik
CONT_HASHMAP::iterator iter = m_pMap->find( rKey );
// container found?
if( iter != m_pMap->end() )
return ((OInterfaceContainerHelper*)(*iter).second)->removeInterface( rListener );
// no container with this id. Always return 0
return 0;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
void OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::disposeAndClear(
const ::com::sun::star::lang::EventObject & rEvt )
SAL_THROW( () )
{
CONT_HASHMAP::size_type nSize = 0;
OInterfaceContainerHelper ** ppListenerContainers = NULL;
{
::osl::MutexGuard aGuard( rMutex );
if( nSize = m_pMap->size() )
{
typedef OInterfaceContainerHelper* ppp;
ppListenerContainers = new ppp[nSize];
//ppListenerContainers = new (ListenerContainer*)[nSize];
CONT_HASHMAP::iterator iter = m_pMap->begin();
CONT_HASHMAP::iterator end = m_pMap->end();
CONT_HASHMAP::size_type i = 0;
while( iter != end )
{
ppListenerContainers[i++] = (OInterfaceContainerHelper*)(*iter).second;
++iter;
}
}
}
// create a copy, because do not fire event in a guarded section
for( CONT_HASHMAP::size_type i = 0;
i < nSize; i++ )
{
if( ppListenerContainers[i] )
ppListenerContainers[i]->disposeAndClear( rEvt );
}
delete [] ppListenerContainers;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
void OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::clear() SAL_THROW( () )
{
::osl::MutexGuard aGuard( rMutex );
CONT_HASHMAP::iterator iter = m_pMap->begin();
CONT_HASHMAP::iterator end = m_pMap->end();
while( iter != end )
{
((OInterfaceContainerHelper*)(*iter).second)->clear();
++iter;
}
}
}
#endif
<commit_msg>INTEGRATION: CWS uno1 (1.3.44); FILE MERGED 2003/02/28 10:51:31 dbo 1.3.44.1: #i11781# fixing compiler warnings<commit_after>/*************************************************************************
*
* $RCSfile: interfacecontainer.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-03-20 12:26:08 $
*
* 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 _CPPUHELPER_INTERFACECONTAINER_HXX_
#define _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.h>
#define CONT_HASHMAP ::std::hash_map< key , void* , hashImpl , equalImpl >
namespace cppu
{
template< class key , class hashImpl , class equalImpl >
inline OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::OMultiTypeInterfaceContainerHelperVar( ::osl::Mutex & rMutex_ )
SAL_THROW( () )
: rMutex( rMutex_ )
{
m_pMap = new CONT_HASHMAP;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
inline OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::~OMultiTypeInterfaceContainerHelperVar()
SAL_THROW( () )
{
typename CONT_HASHMAP::iterator iter = m_pMap->begin();
typename CONT_HASHMAP::iterator end = m_pMap->end();
while( iter != end )
{
delete (OInterfaceContainerHelper*)(*iter).second;
(*iter).second = 0;
++iter;
}
delete m_pMap;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
inline ::com::sun::star::uno::Sequence< key > OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::getContainedTypes() const
SAL_THROW( () )
{
typename CONT_HASHMAP::size_type nSize;
::osl::MutexGuard aGuard( rMutex );
if( nSize = m_pMap->size() )
{
::com::sun::star::uno::Sequence< key > aInterfaceTypes( nSize );
key * pArray = aInterfaceTypes.getArray();
typename CONT_HASHMAP::iterator iter = m_pMap->begin();
typename CONT_HASHMAP::iterator end = m_pMap->end();
sal_Int32 i = 0;
while( iter != end )
{
// are interfaces added to this container?
if( ((OInterfaceContainerHelper*)(*iter).second)->getLength() )
// yes, put the type in the array
pArray[i++] = (*iter).first;
iter++;
}
if( i != nSize ) {
// may be empty container, reduce the sequence to the right size
aInterfaceTypes = ::com::sun::star::uno::Sequence<key>( pArray, i );
}
return aInterfaceTypes;
}
return ::com::sun::star::uno::Sequence<key>();
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
OInterfaceContainerHelper * OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::getContainer(
const key & rKey ) const SAL_THROW( () )
{
::osl::MutexGuard aGuard( rMutex );
typename CONT_HASHMAP::iterator iter = m_pMap->find( rKey );
if( iter != m_pMap->end() )
return (OInterfaceContainerHelper*) (*iter).second;
return 0;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
sal_Int32 OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::addInterface(
const key & rKey,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & rListener )
SAL_THROW( () )
{
::osl::MutexGuard aGuard( rMutex );
typename CONT_HASHMAP::iterator iter = m_pMap->find( rKey );
if( iter == m_pMap->end() )
{
OInterfaceContainerHelper * pLC = new OInterfaceContainerHelper( rMutex );
(*m_pMap)[rKey] = pLC;
return pLC->addInterface( rListener );
}
else
return ((OInterfaceContainerHelper*)(*iter).second)->addInterface( rListener );
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
inline sal_Int32 OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::removeInterface(
const key & rKey,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & rListener )
SAL_THROW( () )
{
::osl::MutexGuard aGuard( rMutex );
// search container with id nUik
typename CONT_HASHMAP::iterator iter = m_pMap->find( rKey );
// container found?
if( iter != m_pMap->end() )
return ((OInterfaceContainerHelper*)(*iter).second)->removeInterface( rListener );
// no container with this id. Always return 0
return 0;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
void OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::disposeAndClear(
const ::com::sun::star::lang::EventObject & rEvt )
SAL_THROW( () )
{
typename CONT_HASHMAP::size_type nSize = 0;
OInterfaceContainerHelper ** ppListenerContainers = NULL;
{
::osl::MutexGuard aGuard( rMutex );
if( nSize = m_pMap->size() )
{
typedef OInterfaceContainerHelper* ppp;
ppListenerContainers = new ppp[nSize];
//ppListenerContainers = new (ListenerContainer*)[nSize];
typename CONT_HASHMAP::iterator iter = m_pMap->begin();
typename CONT_HASHMAP::iterator end = m_pMap->end();
typename CONT_HASHMAP::size_type i = 0;
while( iter != end )
{
ppListenerContainers[i++] = (OInterfaceContainerHelper*)(*iter).second;
++iter;
}
}
}
// create a copy, because do not fire event in a guarded section
for( typename CONT_HASHMAP::size_type i = 0; i < nSize; i++ )
{
if( ppListenerContainers[i] )
ppListenerContainers[i]->disposeAndClear( rEvt );
}
delete [] ppListenerContainers;
}
//===================================================================
template< class key , class hashImpl , class equalImpl >
void OMultiTypeInterfaceContainerHelperVar< key , hashImpl , equalImpl >::clear() SAL_THROW( () )
{
::osl::MutexGuard aGuard( rMutex );
typename CONT_HASHMAP::iterator iter = m_pMap->begin();
typename CONT_HASHMAP::iterator end = m_pMap->end();
while( iter != end )
{
((OInterfaceContainerHelper*)(*iter).second)->clear();
++iter;
}
}
}
#endif
<|endoftext|>
|
<commit_before>/// \file ROOT/TPad.hxx
/// \ingroup Gpad ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2017-07-06
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_TPad
#define ROOT7_TPad
#include <memory>
#include <vector>
#include "ROOT/TDrawable.hxx"
#include "ROOT/TFrame.hxx"
#include "ROOT/TPadExtent.hxx"
#include "ROOT/TPadPos.hxx"
#include "ROOT/TypeTraits.hxx"
namespace ROOT {
namespace Experimental {
class TPad;
namespace Internal {
class TVirtualCanvasPainter;
}
/** \class ROOT::Experimental::TPadBase
Base class for graphic containers for `TDrawable`-s.
*/
class TPadBase {
public:
using Primitives_t = std::vector<std::unique_ptr<TDrawable>>;
private:
/// Content of the pad.
Primitives_t fPrimitives;
/// TFrame with user coordinate system, if used by this pad.
std::unique_ptr<TFrame> fFrame;
/// Disable copy construction.
TPadBase(const TPadBase &) = delete;
/// Disable assignment.
TPadBase &operator=(const TPadBase &) = delete;
/// Adds a `DRAWABLE` to `fPrimitives`, returning the drawing options as given by `DRAWABLE::Options()`.
template <class DRAWABLE>
auto &AddDrawable(std::unique_ptr<DRAWABLE> &&uPtr)
{
DRAWABLE &drw = *uPtr;
fPrimitives.emplace_back(std::move(uPtr));
return drw.GetOptions();
}
protected:
/// Allow derived classes to default construct a TPadBase.
TPadBase() = default;
public:
virtual ~TPadBase();
/// Divide this pad into a grid of subpad with padding in between.
/// \param nHoriz Number of horizontal pads.
/// \param nVert Number of vertical pads.
/// \param padding Padding between pads.
/// \returns vector of vector (ret[x][y]) of created pads.
std::vector<std::vector<TPad *>> Divide(int nHoriz, int nVert, const TPadExtent &padding = {});
/// Add something to be painted.
/// The pad observes what's lifetime through a weak pointer.
template <class T>
auto &Draw(const std::shared_ptr<T> &what)
{
// Requires GetDrawable(what) to be known!
return AddDrawable(GetDrawable(what, *this));
}
/// Add something to be painted. The pad claims ownership.
template <class T>
auto &Draw(std::unique_ptr<T> &&what)
{
// Requires GetDrawable(what) to be known!
return AddDrawable(GetDrawable(std::move(what), *this));
}
/// Add a copy of something to be painted.
template <class T, class = typename std::enable_if<!ROOT::TypeTraits::IsSmartOrDumbPtr<T>::value>::type>
auto &Draw(const T &what)
{
// Requires GetDrawable(what) to be known!
return Draw(std::make_unique<T>(what));
}
/// Remove an object from the list of primitives.
// TODO: void Wipe();
/// Get the elements contained in the canvas.
const Primitives_t &GetPrimitives() const { return fPrimitives; }
/// Convert a `Pixel` position to Canvas-normalized positions.
virtual std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const = 0;
/// Convert user coordinates to normal coordinates.
std::array<TPadCoord::Normal, 2> UserToNormal(const std::array<TPadCoord::User, 2> &pos) const
{
return fFrame->UserToNormal(pos);
}
};
} // namespace Internal
/** \class TPadDrawable
Draw a TPad, by drawing its contained graphical elements at the pad offset in the parent pad.'
*/
class TPadDrawable: public TDrawable {
private:
const std::unique_ptr<TPad> fPad; ///< The pad to be painted
TPadPos fPos; ///< Offset with respect to parent TPad.
public:
TPadDrawable() = default;
TPadDrawable(std::unique_ptr<TPad> &&pPad, const TPadPos &pos): fPad(std::move(pPad)), fPos(pos) {}
/// Paint the pad.
void Paint(Internal::TVirtualCanvasPainter & /*canv*/) final
{
// FIXME: and then what? Something with fPad.GetListOfPrimitives()?
}
TPad *Get() const { return fPad.get(); }
/// No options here.
void GetOptions() const {}
};
/** \class ROOT::Experimental::TPad
Graphic container for `TDrawable`-s.
*/
class TPad: public Internal::TPadBase {
private:
/// Pad containing this pad as a sub-pad.
const TPadBase *fParent = nullptr;
/// Size of the pad in the parent's (!) coordinate system.
TPadExtent fSize;
public:
friend std::unique_ptr<TPadDrawable> GetDrawable(std::unique_ptr<TPad> &&pad, const TPadPos &pos)
{
return std::make_unique<TPadDrawable>(std::move(pad), pos);
}
/// Create a child pad.
TPad(const TPadBase &parent, const TPadExtent &size): fParent(&parent), fSize(size) {}
/// Destructor to have a vtable.
virtual ~TPad();
/// Get the size of the pad in parent (!) coordinates.
const TPadExtent &GetSize() const { return fSize; }
/// Convert a `Pixel` position to Canvas-normalized positions.
std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const override
{
std::array<TPadCoord::Normal, 2> posInParentNormal = fParent->PixelsToNormal(pos);
std::array<TPadCoord::Normal, 2> myPixelInNormal =
fParent->PixelsToNormal({{fSize.fHoriz.fPixel, fSize.fVert.fPixel}});
std::array<TPadCoord::Normal, 2> myUserInNormal =
fParent->UserToNormal({{fSize.fHoriz.fUser, fSize.fVert.fUser}});
// If the parent says pos is at 0.6 in normal coords, and our size converted to normal is 0.2, then pos in our
// coord system is 3.0!
return {{posInParentNormal[0] / (fSize.fHoriz.fNormal + myPixelInNormal[0] + myUserInNormal[0]),
posInParentNormal[1] / (fSize.fVert.fNormal + myPixelInNormal[1] + myUserInNormal[1])}};
}
/// Convert a TPadPos to [x, y] of normalized coordinates.
std::array<TPadCoord::Normal, 2> ToNormal(const Internal::TPadHorizVert &pos) const
{
std::array<TPadCoord::Normal, 2> pixelsInNormal = PixelsToNormal({{pos.fHoriz.fPixel, pos.fVert.fPixel}});
std::array<TPadCoord::Normal, 2> userInNormal = UserToNormal({{pos.fHoriz.fUser, pos.fVert.fUser}});
return {{pos.fHoriz.fNormal + pixelsInNormal[0] + userInNormal[0],
pos.fVert.fNormal + pixelsInNormal[1] + userInNormal[1]}};
}
};
} // namespace Experimental
} // namespace ROOT
#endif
<commit_msg>Add GetCanvas(), GetParent().<commit_after>/// \file ROOT/TPad.hxx
/// \ingroup Gpad ROOT7
/// \author Axel Naumann <axel@cern.ch>
/// \date 2017-07-06
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT7_TPad
#define ROOT7_TPad
#include <memory>
#include <vector>
#include "ROOT/TDrawable.hxx"
#include "ROOT/TFrame.hxx"
#include "ROOT/TPadExtent.hxx"
#include "ROOT/TPadPos.hxx"
#include "ROOT/TypeTraits.hxx"
namespace ROOT {
namespace Experimental {
class TPad;
namespace Internal {
class TVirtualCanvasPainter;
}
/** \class ROOT::Experimental::TPadBase
Base class for graphic containers for `TDrawable`-s.
*/
class TPadBase {
public:
using Primitives_t = std::vector<std::unique_ptr<TDrawable>>;
private:
/// Content of the pad.
Primitives_t fPrimitives;
/// TFrame with user coordinate system, if used by this pad.
std::unique_ptr<TFrame> fFrame;
/// Disable copy construction.
TPadBase(const TPadBase &) = delete;
/// Disable assignment.
TPadBase &operator=(const TPadBase &) = delete;
/// Adds a `DRAWABLE` to `fPrimitives`, returning the drawing options as given by `DRAWABLE::Options()`.
template <class DRAWABLE>
auto &AddDrawable(std::unique_ptr<DRAWABLE> &&uPtr)
{
DRAWABLE &drw = *uPtr;
fPrimitives.emplace_back(std::move(uPtr));
return drw.GetOptions();
}
protected:
/// Allow derived classes to default construct a TPadBase.
TPadBase() = default;
public:
virtual ~TPadBase();
/// Divide this pad into a grid of subpad with padding in between.
/// \param nHoriz Number of horizontal pads.
/// \param nVert Number of vertical pads.
/// \param padding Padding between pads.
/// \returns vector of vector (ret[x][y]) of created pads.
std::vector<std::vector<TPad *>> Divide(int nHoriz, int nVert, const TPadExtent &padding = {});
/// Add something to be painted.
/// The pad observes what's lifetime through a weak pointer.
template <class T>
auto &Draw(const std::shared_ptr<T> &what)
{
// Requires GetDrawable(what) to be known!
return AddDrawable(GetDrawable(what, *this));
}
/// Add something to be painted. The pad claims ownership.
template <class T>
auto &Draw(std::unique_ptr<T> &&what)
{
// Requires GetDrawable(what) to be known!
return AddDrawable(GetDrawable(std::move(what), *this));
}
/// Add a copy of something to be painted.
template <class T, class = typename std::enable_if<!ROOT::TypeTraits::IsSmartOrDumbPtr<T>::value>::type>
auto &Draw(const T &what)
{
// Requires GetDrawable(what) to be known!
return Draw(std::make_unique<T>(what));
}
/// Remove an object from the list of primitives.
// TODO: void Wipe();
/// Get the elements contained in the canvas.
const Primitives_t &GetPrimitives() const { return fPrimitives; }
/// Convert a `Pixel` position to Canvas-normalized positions.
virtual std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const = 0;
/// Access to the top-most canvas, if any (const version).
virtual const TCanvas &GetCanvas() const = 0;
/// Access to the top-most canvas, if any (non-const version).
virtual TCanvas &GetCanvas() = 0;
/// Convert user coordinates to normal coordinates.
std::array<TPadCoord::Normal, 2> UserToNormal(const std::array<TPadCoord::User, 2> &pos) const
{
return fFrame->UserToNormal(pos);
}
};
} // namespace Internal
/** \class TPadDrawable
Draw a TPad, by drawing its contained graphical elements at the pad offset in the parent pad.'
*/
class TPadDrawable: public TDrawable {
private:
const std::unique_ptr<TPad> fPad; ///< The pad to be painted
TPadPos fPos; ///< Offset with respect to parent TPad.
public:
TPadDrawable() = default;
TPadDrawable(std::unique_ptr<TPad> &&pPad, const TPadPos &pos): fPad(std::move(pPad)), fPos(pos) {}
/// Paint the pad.
void Paint(Internal::TVirtualCanvasPainter & /*canv*/) final
{
// FIXME: and then what? Something with fPad.GetListOfPrimitives()?
}
TPad *Get() const { return fPad.get(); }
/// No options here.
void GetOptions() const {}
};
/** \class ROOT::Experimental::TPad
Graphic container for `TDrawable`-s.
*/
class TPad: public Internal::TPadBase {
private:
/// Pad containing this pad as a sub-pad.
const TPadBase *fParent = nullptr;
/// Size of the pad in the parent's (!) coordinate system.
TPadExtent fSize;
public:
friend std::unique_ptr<TPadDrawable> GetDrawable(std::unique_ptr<TPad> &&pad, const TPadPos &pos)
{
return std::make_unique<TPadDrawable>(std::move(pad), pos);
}
/// Create a child pad.
TPad(const TPadBase &parent, const TPadExtent &size): fParent(&parent), fSize(size) {}
/// Destructor to have a vtable.
virtual ~TPad();
/// Access to the parent pad (const version).
const TPadBase &GetParent() const { return *fParent; }
/// Access to the parent pad (non-const version).
TPadBase &GetParent() { return *fParent; }
/// Access to the top-most canvas (const version).
const TCanvas &GetCanvas() const override { return fParent->GetCanvas(); }
/// Access to the top-most canvas (non-const version).
TCanvas &GetCanvas() override { return fParent->GetCanvas(); }
/// Get the size of the pad in parent (!) coordinates.
const TPadExtent &GetSize() const { return fSize; }
/// Convert a `Pixel` position to Canvas-normalized positions.
std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const override
{
std::array<TPadCoord::Normal, 2> posInParentNormal = fParent->PixelsToNormal(pos);
std::array<TPadCoord::Normal, 2> myPixelInNormal =
fParent->PixelsToNormal({{fSize.fHoriz.fPixel, fSize.fVert.fPixel}});
std::array<TPadCoord::Normal, 2> myUserInNormal =
fParent->UserToNormal({{fSize.fHoriz.fUser, fSize.fVert.fUser}});
// If the parent says pos is at 0.6 in normal coords, and our size converted to normal is 0.2, then pos in our
// coord system is 3.0!
return {{posInParentNormal[0] / (fSize.fHoriz.fNormal + myPixelInNormal[0] + myUserInNormal[0]),
posInParentNormal[1] / (fSize.fVert.fNormal + myPixelInNormal[1] + myUserInNormal[1])}};
}
/// Convert a TPadPos to [x, y] of normalized coordinates.
std::array<TPadCoord::Normal, 2> ToNormal(const Internal::TPadHorizVert &pos) const
{
std::array<TPadCoord::Normal, 2> pixelsInNormal = PixelsToNormal({{pos.fHoriz.fPixel, pos.fVert.fPixel}});
std::array<TPadCoord::Normal, 2> userInNormal = UserToNormal({{pos.fHoriz.fUser, pos.fVert.fUser}});
return {{pos.fHoriz.fNormal + pixelsInNormal[0] + userInNormal[0],
pos.fVert.fNormal + pixelsInNormal[1] + userInNormal[1]}};
}
};
} // namespace Experimental
} // namespace ROOT
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "gromacsformat.h"
#include <avogadro/core/avogadrocore.h>
#include <avogadro/core/atom.h>
#include <avogadro/core/matrix.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/unitcell.h>
#include <avogadro/core/utilities.h>
#include <iostream>
#include <string>
#include <utility>
namespace Avogadro {
namespace Io {
using Core::Atom;
using Core::Molecule;
using Core::UnitCell;
using Core::lexicalCast;
using Core::trimmed;
using Core::split;
using std::string;
using std::getline;
using std::map;
using std::vector;
GromacsFormat::GromacsFormat()
{
}
GromacsFormat::~GromacsFormat()
{
}
std::vector<std::string> GromacsFormat::fileExtensions() const
{
return std::vector<std::string>(1, std::string("gro"));
}
std::vector<std::string> GromacsFormat::mimeTypes() const
{
return std::vector<std::string>(1, std::string("chemical/x-gro"));
}
bool GromacsFormat::read(std::istream& in, Molecule& molecule)
{
string buffer;
string value;
// Title
getline(in, buffer);
if (!buffer.empty())
molecule.setData("name", trimmed(buffer));
// Atom count
getline(in, buffer);
buffer = trimmed(buffer);
bool ok;
size_t numAtoms = lexicalCast<size_t>(buffer, ok);
if (buffer.empty() || !ok) {
appendError("Number of atoms (line 2) invalid.");
return false;
}
// read atom info:
typedef map<string, unsigned char> AtomTypeMap;
AtomTypeMap atomTypes;
unsigned char customElementCounter = CustomElementMin;
Vector3 pos;
while (numAtoms-- > 0) {
getline(in, buffer);
// Figure out the distance between decimal points, implement support for
// variable precision as specified:
// "any number of decimal places, the format will then be n+5 positions with
// n decimal places (n+1 for velocities) in stead of 8 with 3 (with 4 for
// velocities)".
size_t decimal1 = buffer.find(".", 20);
size_t decimal2 = string::npos;
int decimalSep = 0;
if (decimal1 != string::npos)
decimal2 = buffer.find(".", decimal1 + 1);
if (decimal2 != string::npos)
decimalSep = decimal2 - decimal1;
if (decimalSep == 0) {
appendError("Decimal separation of 0 found in atom positions: " + buffer);
return false;
}
if (buffer.size() < static_cast<size_t>(20 + 3 * decimalSep)) {
appendError("Error reading atom specification -- line too short: " +
buffer);
return false;
}
// Format of buffer is: (all indices start at 1, variable dp throws this).
// Offset: 0 format: %5i value: Residue number
// Offset: 5 format: %-5s value: Residue name
// Offset: 10 format: %5s value: Atom name
// Offset: 15 format: %5i value: Atom number
// Offset: 20 format: %8.3f value: x coordinate (nm)
// Offset: 28 format: %8.3f value: y coordinate (nm)
// Offset: 36 format: %8.3f value: z coordinate (nm)
// Offset: 44 format: %8.4f value: x velocity (nm/ps, a.k.a. km/s)
// Offset: 52 format: %8.4f value: y velocity (nm/ps, a.k.a. km/s)
// Offset: 60 format: %8.4f value: z velocity (nm/ps, a.k.a. km/s)
// Atom name:
value = trimmed(buffer.substr(10, 5));
AtomTypeMap::const_iterator it = atomTypes.find(value);
if (it == atomTypes.end()) {
atomTypes.insert(std::make_pair(value, customElementCounter++));
it = atomTypes.find(value);
if (customElementCounter > CustomElementMax) {
appendError("Custom element type limit exceeded.");
return false;
}
}
Atom atom = molecule.addAtom(it->second);
// Coords
for (int i = 0; i < 3; ++i) {
value = trimmed(buffer.substr(20 + i * decimalSep, decimalSep));
pos[i] = lexicalCast<Real>(value, ok);
if (!ok || value.empty()) {
appendError(
"Error reading atom specification -- invalid coordinate: '" + buffer +
"' (bad coord: '" + value + "')");
return false;
}
}
atom.setPosition3d(pos * static_cast<Real>(10.0)); // nm --> Angstrom
}
// Set the custom element map if needed:
if (!atomTypes.empty()) {
Molecule::CustomElementMap elementMap;
for (AtomTypeMap::const_iterator it = atomTypes.begin(),
itEnd = atomTypes.end();
it != itEnd; ++it) {
elementMap.insert(std::make_pair(it->second, it->first));
}
molecule.setCustomElementMap(elementMap);
}
// Box description:
// v1(x) v2(y) v3(z) [v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)]
// The last six values may be omitted, set all non-specified values to 0.
// v1(y) == v1(z) == v2(z) == 0 always.
getline(in, buffer);
vector<string> tokens(split(buffer, ' ', true));
if (tokens.size() > 0) {
if (tokens.size() != 3 && tokens.size() != 9) {
appendError("Invalid box specification -- need either 3 or 9 values: '" +
buffer + "'");
return false;
}
// Index arrays for parsing loop:
const int rows[] = { 0, 1, 2, 1, 2, 0, 2, 0, 1 };
const int cols[] = { 0, 1, 2, 0, 0, 1, 1, 2, 2 };
Matrix3 cellMatrix = Matrix3::Zero();
for (size_t i = 0; i < tokens.size(); ++i) {
cellMatrix(rows[i], cols[i]) = lexicalCast<Real>(tokens[i], ok);
if (!ok || tokens[i].empty()) {
appendError("Invalid box specification -- bad value: '" + tokens[i] +
"'");
return false;
}
}
UnitCell* cell = new UnitCell;
cell->setCellMatrix(cellMatrix * static_cast<Real>(10)); // nm --> Angstrom
molecule.setUnitCell(cell);
}
return true;
}
bool GromacsFormat::write(std::ostream&, const Core::Molecule&)
{
return false;
}
} // namespace Io
} // namespace Avogadro
<commit_msg>Assigning atoms based on residue data<commit_after>/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "gromacsformat.h"
#include <avogadro/core/avogadrocore.h>
#include <avogadro/core/atom.h>
#include <avogadro/core/elements.h>
#include <avogadro/core/matrix.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/residue.h>
#include <avogadro/core/unitcell.h>
#include <avogadro/core/utilities.h>
#include <iostream>
#include <string>
#include <utility>
namespace Avogadro {
namespace Io {
using Core::Atom;
using Core::Elements;
using Core::lexicalCast;
using Core::Molecule;
using Core::Residue;
using Core::split;
using Core::trimmed;
using Core::UnitCell;
using std::getline;
using std::map;
using std::string;
using std::vector;
GromacsFormat::GromacsFormat() {}
GromacsFormat::~GromacsFormat() {}
std::vector<std::string> GromacsFormat::fileExtensions() const
{
return std::vector<std::string>(1, std::string("gro"));
}
std::vector<std::string> GromacsFormat::mimeTypes() const
{
return std::vector<std::string>(1, std::string("chemical/x-gro"));
}
bool GromacsFormat::read(std::istream& in, Molecule& molecule)
{
string buffer;
string value;
Residue* r;
size_t currentResidueId = 0;
// Title
getline(in, buffer);
if (!buffer.empty())
molecule.setData("name", trimmed(buffer));
// Atom count
getline(in, buffer);
buffer = trimmed(buffer);
bool ok;
size_t numAtoms = lexicalCast<size_t>(buffer, ok);
if (buffer.empty() || !ok) {
appendError("Number of atoms (line 2) invalid.");
return false;
}
// read atom info:
typedef map<string, unsigned char> AtomTypeMap;
AtomTypeMap atomTypes;
unsigned char customElementCounter = CustomElementMin;
Vector3 pos;
while (numAtoms-- > 0) {
getline(in, buffer);
// Figure out the distance between decimal points, implement support for
// variable precision as specified:
// "any number of decimal places, the format will then be n+5 positions with
// n decimal places (n+1 for velocities) in stead of 8 with 3 (with 4 for
// velocities)".
size_t decimal1 = buffer.find(".", 20);
size_t decimal2 = string::npos;
int decimalSep = 0;
if (decimal1 != string::npos)
decimal2 = buffer.find(".", decimal1 + 1);
if (decimal2 != string::npos)
decimalSep = decimal2 - decimal1;
if (decimalSep == 0) {
appendError("Decimal separation of 0 found in atom positions: " + buffer);
return false;
}
if (buffer.size() < static_cast<size_t>(20 + 3 * decimalSep)) {
appendError("Error reading atom specification -- line too short: " +
buffer);
return false;
}
// Format of buffer is: (all indices start at 1, variable dp throws this).
// Offset: 0 format: %5i value: Residue number
// Offset: 5 format: %-5s value: Residue name
// Offset: 10 format: %5s value: Atom name
// Offset: 15 format: %5i value: Atom number
// Offset: 20 format: %8.3f value: x coordinate (nm)
// Offset: 28 format: %8.3f value: y coordinate (nm)
// Offset: 36 format: %8.3f value: z coordinate (nm)
// Offset: 44 format: %8.4f value: x velocity (nm/ps, a.k.a. km/s)
// Offset: 52 format: %8.4f value: y velocity (nm/ps, a.k.a. km/s)
// Offset: 60 format: %8.4f value: z velocity (nm/ps, a.k.a. km/s)
size_t residueId = lexicalCast<size_t>(buffer.substr(0, 5), ok);
if (!ok) {
appendError("Failed to parse residue sequence number: " +
buffer.substr(0, 5));
return false;
}
if (residueId != currentResidueId) {
currentResidueId = residueId;
string residueName = lexicalCast<string>(buffer.substr(5, 5), ok);
if (!ok) {
appendError("Failed to parse residue name: " + buffer.substr(5, 5));
return false;
}
// gro files do not have a chain ID. So we use a makeshift dummy ID
char dummyChainId = '0';
r = &molecule.addResidue(residueName, currentResidueId, dummyChainId);
}
// Atom name:
value = trimmed(buffer.substr(10, 5));
Atom atom;
int atomicNum = r->getAtomicNumber(value);
if (atomicNum) {
atom = molecule.addAtom(atomicNum);
} else {
unsigned char atomicNumFromSymbol =
Elements::atomicNumberFromSymbol(value);
if (atomicNumFromSymbol != 255) {
atom = molecule.addAtom(atomicNumFromSymbol);
} else {
AtomTypeMap::const_iterator it = atomTypes.find(value);
if (it == atomTypes.end()) {
atomTypes.insert(std::make_pair(value, customElementCounter++));
it = atomTypes.find(value);
if (customElementCounter > CustomElementMax) {
appendError("Custom element type limit exceeded.");
return false;
}
}
atom = molecule.addAtom(it->second);
}
}
// Coords
for (int i = 0; i < 3; ++i) {
value = trimmed(buffer.substr(20 + i * decimalSep, decimalSep));
pos[i] = lexicalCast<Real>(value, ok);
if (!ok || value.empty()) {
appendError(
"Error reading atom specification -- invalid coordinate: '" + buffer +
"' (bad coord: '" + value + "')");
return false;
}
}
atom.setPosition3d(pos * static_cast<Real>(10.0)); // nm --> Angstrom
if (r) {
r->addResidueAtom(value, atom);
}
}
// Set the custom element map if needed:
if (!atomTypes.empty()) {
Molecule::CustomElementMap elementMap;
for (AtomTypeMap::const_iterator it = atomTypes.begin(),
itEnd = atomTypes.end();
it != itEnd; ++it) {
elementMap.insert(std::make_pair(it->second, it->first));
}
molecule.setCustomElementMap(elementMap);
}
// Box description:
// v1(x) v2(y) v3(z) [v1(y) v1(z) v2(x) v2(z) v3(x) v3(y)]
// The last six values may be omitted, set all non-specified values to 0.
// v1(y) == v1(z) == v2(z) == 0 always.
getline(in, buffer);
vector<string> tokens(split(buffer, ' ', true));
if (tokens.size() > 0) {
if (tokens.size() != 3 && tokens.size() != 9) {
appendError("Invalid box specification -- need either 3 or 9 values: '" +
buffer + "'");
return false;
}
// Index arrays for parsing loop:
const int rows[] = { 0, 1, 2, 1, 2, 0, 2, 0, 1 };
const int cols[] = { 0, 1, 2, 0, 0, 1, 1, 2, 2 };
Matrix3 cellMatrix = Matrix3::Zero();
for (size_t i = 0; i < tokens.size(); ++i) {
cellMatrix(rows[i], cols[i]) = lexicalCast<Real>(tokens[i], ok);
if (!ok || tokens[i].empty()) {
appendError("Invalid box specification -- bad value: '" + tokens[i] +
"'");
return false;
}
}
UnitCell* cell = new UnitCell;
cell->setCellMatrix(cellMatrix * static_cast<Real>(10)); // nm --> Angstrom
molecule.setUnitCell(cell);
}
return true;
}
bool GromacsFormat::write(std::ostream&, const Core::Molecule&)
{
return false;
}
} // namespace Io
} // namespace Avogadro
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "ReplicaThread.h"
#include "LogDB.h"
#include "RaftManager.h"
#include "Nebula.h"
#include "NebulaLog.h"
#include "FedReplicaManager.h"
#include <errno.h>
#include <string>
using namespace std;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Replication thread class & pool
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
const time_t ReplicaThread::max_retry_timeout = 2.5e9;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
extern "C" void * replication_thread(void *arg)
{
ReplicaThread * rt;
int oldstate;
if ( arg == 0 )
{
return 0;
}
rt = static_cast<ReplicaThread *>(arg);
rt->_thread_id = pthread_self();
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldstate);
rt->do_replication();
NebulaLog::log("RCM", Log::INFO, "Replication thread stopped");
delete rt;
return 0;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
static void set_timeout(struct timespec& timeout, time_t nsec )
{
clock_gettime(CLOCK_REALTIME, &timeout);
timeout.tv_nsec += nsec;
while ( timeout.tv_nsec >= 1000000000 )
{
timeout.tv_sec += 1;
timeout.tv_nsec -= 1000000000;
}
}
void ReplicaThread::do_replication()
{
int rc;
bool retry_request = false;
while ( _finalize == false )
{
pthread_mutex_lock(&mutex);
while ( _pending_requests == false )
{
struct timespec timeout;
set_timeout(timeout, retry_timeout);
if ( pthread_cond_timedwait(&cond, &mutex, &timeout) == ETIMEDOUT )
{
_pending_requests = retry_request || _pending_requests;
}
if ( _finalize )
{
return;
}
}
_pending_requests = false;
pthread_mutex_unlock(&mutex);
rc = replicate();
if ( rc == -1 )
{
if ( retry_timeout < max_retry_timeout )
{
retry_timeout = 2 * retry_timeout;
}
retry_request = true;
}
else
{
retry_timeout = 1e8;
retry_request = false;
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ReplicaThread::finalize()
{
pthread_mutex_lock(&mutex);
_finalize = true;
_pending_requests = false;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ReplicaThread::add_request()
{
pthread_mutex_lock(&mutex);
_pending_requests = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
RaftReplicaThread::RaftReplicaThread(int fid):ReplicaThread(fid)
{
Nebula& nd = Nebula::instance();
logdb = nd.get_logdb();
raftm = nd.get_raftm();
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
int RaftReplicaThread::replicate()
{
std::string error;
LogDBRecord lr;
bool success = false;
unsigned int follower_term = -1;
unsigned int term = raftm->get_term();
uint64_t next_index = raftm->get_next_index(follower_id);
if ( next_index == UINT64_MAX )
{
ostringstream ess;
ess << "Failed to get next replica index for follower: " << follower_id;
NebulaLog::log("RCM", Log::ERROR, ess);
return -1;
}
if ( logdb->get_log_record(next_index, next_index - 1, lr) != 0 )
{
ostringstream ess;
ess << "Failed to load log record at index: " << next_index;
NebulaLog::log("RCM", Log::ERROR, ess);
return -1;
}
if ( raftm->xmlrpc_replicate_log(follower_id, &lr, success, follower_term,
error) != 0 )
{
std::ostringstream oss;
oss << "Faild to replicate log record at index: " << next_index
<< " on follower: " << follower_id << ", error: " << error;
NebulaLog::log("RCM", Log::DEBUG, oss);
return -1;
}
if ( success )
{
raftm->replicate_success(follower_id);
}
else
{
if ( follower_term > term )
{
ostringstream ess;
ess << "Follower " << follower_id << " term (" << follower_term
<< ") is higher than current (" << term << ")";
NebulaLog::log("RCM", Log::INFO, ess);
raftm->follower(follower_term);
}
else
{
raftm->replicate_failure(follower_id);
}
}
return 0;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
FedReplicaThread::FedReplicaThread(int zone_id):ReplicaThread(zone_id)
{
Nebula& nd = Nebula::instance();
frm = nd.get_frm();
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
int FedReplicaThread::replicate()
{
std::string error;
bool success = false;
uint64_t last;
int rc = frm->xmlrpc_replicate_log(follower_id, success, last, error);
if ( rc == -1 )
{
NebulaLog::log("FRM", Log::ERROR, error);
return -1;
}
else if ( rc == -2 )
{
return 0;
}
if ( success )
{
frm->replicate_success(follower_id);
}
else
{
frm->replicate_failure(follower_id, last);
}
return 0;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
HeartBeatThread::HeartBeatThread(int fid):ReplicaThread(fid), last_error(0),
num_errors(0)
{
Nebula& nd = Nebula::instance();
raftm = nd.get_raftm();
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
int HeartBeatThread::replicate()
{
int rc;
bool success;
std::string error;
unsigned int fterm;
unsigned int term = raftm->get_term();
LogDBRecord lr;
lr.index = 0;
lr.prev_index = 0;
lr.term = 0;
lr.prev_term = 0;
lr.sql = "";
lr.timestamp = 0;
lr.fed_index = UINT64_MAX;
rc = raftm->xmlrpc_replicate_log(follower_id, &lr, success, fterm, error);
if ( rc == -1 )
{
num_errors++;
if ( last_error == 0 )
{
last_error = time(0);
num_errors = 1;
}
else if ( last_error + 60 < time(0) )
{
if ( num_errors > 10 )
{
std::ostringstream oss;
oss << "Detetected error condition on follower "
<< follower_id <<". Last error was: " << error;
NebulaLog::log("RCM", Log::INFO, oss);
}
last_error = 0;
}
}
else if ( success == false && fterm > term )
{
std::ostringstream oss;
oss << "Follower " << follower_id << " term (" << fterm
<< ") is higher than current (" << term << ")";
NebulaLog::log("RCM", Log::INFO, oss);
raftm->follower(fterm);
}
return 0;
}
<commit_msg>M #-: Typo<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "ReplicaThread.h"
#include "LogDB.h"
#include "RaftManager.h"
#include "Nebula.h"
#include "NebulaLog.h"
#include "FedReplicaManager.h"
#include <errno.h>
#include <string>
using namespace std;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Replication thread class & pool
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
const time_t ReplicaThread::max_retry_timeout = 2.5e9;
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
extern "C" void * replication_thread(void *arg)
{
ReplicaThread * rt;
int oldstate;
if ( arg == 0 )
{
return 0;
}
rt = static_cast<ReplicaThread *>(arg);
rt->_thread_id = pthread_self();
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldstate);
rt->do_replication();
NebulaLog::log("RCM", Log::INFO, "Replication thread stopped");
delete rt;
return 0;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
static void set_timeout(struct timespec& timeout, time_t nsec )
{
clock_gettime(CLOCK_REALTIME, &timeout);
timeout.tv_nsec += nsec;
while ( timeout.tv_nsec >= 1000000000 )
{
timeout.tv_sec += 1;
timeout.tv_nsec -= 1000000000;
}
}
void ReplicaThread::do_replication()
{
int rc;
bool retry_request = false;
while ( _finalize == false )
{
pthread_mutex_lock(&mutex);
while ( _pending_requests == false )
{
struct timespec timeout;
set_timeout(timeout, retry_timeout);
if ( pthread_cond_timedwait(&cond, &mutex, &timeout) == ETIMEDOUT )
{
_pending_requests = retry_request || _pending_requests;
}
if ( _finalize )
{
return;
}
}
_pending_requests = false;
pthread_mutex_unlock(&mutex);
rc = replicate();
if ( rc == -1 )
{
if ( retry_timeout < max_retry_timeout )
{
retry_timeout = 2 * retry_timeout;
}
retry_request = true;
}
else
{
retry_timeout = 1e8;
retry_request = false;
}
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ReplicaThread::finalize()
{
pthread_mutex_lock(&mutex);
_finalize = true;
_pending_requests = false;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
void ReplicaThread::add_request()
{
pthread_mutex_lock(&mutex);
_pending_requests = true;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
RaftReplicaThread::RaftReplicaThread(int fid):ReplicaThread(fid)
{
Nebula& nd = Nebula::instance();
logdb = nd.get_logdb();
raftm = nd.get_raftm();
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
int RaftReplicaThread::replicate()
{
std::string error;
LogDBRecord lr;
bool success = false;
unsigned int follower_term = -1;
unsigned int term = raftm->get_term();
uint64_t next_index = raftm->get_next_index(follower_id);
if ( next_index == UINT64_MAX )
{
ostringstream ess;
ess << "Failed to get next replica index for follower: " << follower_id;
NebulaLog::log("RCM", Log::ERROR, ess);
return -1;
}
if ( logdb->get_log_record(next_index, next_index - 1, lr) != 0 )
{
ostringstream ess;
ess << "Failed to load log record at index: " << next_index;
NebulaLog::log("RCM", Log::ERROR, ess);
return -1;
}
if ( raftm->xmlrpc_replicate_log(follower_id, &lr, success, follower_term,
error) != 0 )
{
std::ostringstream oss;
oss << "Failed to replicate log record at index: " << next_index
<< " on follower: " << follower_id << ", error: " << error;
NebulaLog::log("RCM", Log::DEBUG, oss);
return -1;
}
if ( success )
{
raftm->replicate_success(follower_id);
}
else
{
if ( follower_term > term )
{
ostringstream ess;
ess << "Follower " << follower_id << " term (" << follower_term
<< ") is higher than current (" << term << ")";
NebulaLog::log("RCM", Log::INFO, ess);
raftm->follower(follower_term);
}
else
{
raftm->replicate_failure(follower_id);
}
}
return 0;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
FedReplicaThread::FedReplicaThread(int zone_id):ReplicaThread(zone_id)
{
Nebula& nd = Nebula::instance();
frm = nd.get_frm();
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
int FedReplicaThread::replicate()
{
std::string error;
bool success = false;
uint64_t last;
int rc = frm->xmlrpc_replicate_log(follower_id, success, last, error);
if ( rc == -1 )
{
NebulaLog::log("FRM", Log::ERROR, error);
return -1;
}
else if ( rc == -2 )
{
return 0;
}
if ( success )
{
frm->replicate_success(follower_id);
}
else
{
frm->replicate_failure(follower_id, last);
}
return 0;
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
HeartBeatThread::HeartBeatThread(int fid):ReplicaThread(fid), last_error(0),
num_errors(0)
{
Nebula& nd = Nebula::instance();
raftm = nd.get_raftm();
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
int HeartBeatThread::replicate()
{
int rc;
bool success;
std::string error;
unsigned int fterm;
unsigned int term = raftm->get_term();
LogDBRecord lr;
lr.index = 0;
lr.prev_index = 0;
lr.term = 0;
lr.prev_term = 0;
lr.sql = "";
lr.timestamp = 0;
lr.fed_index = UINT64_MAX;
rc = raftm->xmlrpc_replicate_log(follower_id, &lr, success, fterm, error);
if ( rc == -1 )
{
num_errors++;
if ( last_error == 0 )
{
last_error = time(0);
num_errors = 1;
}
else if ( last_error + 60 < time(0) )
{
if ( num_errors > 10 )
{
std::ostringstream oss;
oss << "Detetected error condition on follower "
<< follower_id <<". Last error was: " << error;
NebulaLog::log("RCM", Log::INFO, oss);
}
last_error = 0;
}
}
else if ( success == false && fterm > term )
{
std::ostringstream oss;
oss << "Follower " << follower_id << " term (" << fterm
<< ") is higher than current (" << term << ")";
NebulaLog::log("RCM", Log::INFO, oss);
raftm->follower(fterm);
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/scoped_ptr.h"
#include "media/base/data_buffer.h"
#include "media/base/mock_ffmpeg.h"
#include "media/base/mock_task.h"
#include "media/filters/ffmpeg_video_decode_engine.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::DoAll;
using ::testing::Return;
using ::testing::ReturnNull;
using ::testing::SetArgumentPointee;
using ::testing::StrictMock;
namespace media {
static const int kWidth = 320;
static const int kHeight = 240;
static const AVRational kTimeBase = { 1, 100 };
ACTION_P(SaveInitializeResult, engine) {
engine->info_ = arg0;
}
class FFmpegVideoDecodeEngineTest : public testing::Test,
public VideoDecodeEngine::EventHandler {
protected:
FFmpegVideoDecodeEngineTest() {
// Setup FFmpeg structures.
frame_buffer_.reset(new uint8[kWidth * kHeight]);
memset(&yuv_frame_, 0, sizeof(yuv_frame_));
// DecodeFrame will check these pointers as non-NULL value.
yuv_frame_.data[0] = yuv_frame_.data[1] = yuv_frame_.data[2]
= frame_buffer_.get();
yuv_frame_.linesize[0] = kWidth;
yuv_frame_.linesize[1] = yuv_frame_.linesize[2] = kWidth >> 1;
memset(&codec_context_, 0, sizeof(codec_context_));
codec_context_.width = kWidth;
codec_context_.height = kHeight;
codec_context_.time_base = kTimeBase;
memset(&codec_, 0, sizeof(codec_));
memset(&stream_, 0, sizeof(stream_));
stream_.codec = &codec_context_;
stream_.r_frame_rate.num = kTimeBase.den;
stream_.r_frame_rate.den = kTimeBase.num;
buffer_ = new DataBuffer(1);
// Initialize MockFFmpeg.
MockFFmpeg::set(&mock_ffmpeg_);
test_engine_ = new FFmpegVideoDecodeEngine();
test_engine_->SetCodecContextForTest(&codec_context_);
VideoFrame::CreateFrame(VideoFrame::YV12,
kWidth,
kHeight,
StreamSample::kInvalidTimestamp,
StreamSample::kInvalidTimestamp,
&video_frame_);
}
~FFmpegVideoDecodeEngineTest() {
test_engine_ = NULL;
MockFFmpeg::set(NULL);
}
void Initialize() {
EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))
.WillOnce(Return(&codec_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())
.WillOnce(Return(&yuv_frame_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))
.WillOnce(Return(0));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecOpen(&codec_context_, &codec_))
.WillOnce(Return(0));
EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))
.Times(1);
config_.codec_ = kCodecH264;
config_.opaque_context_ = &stream_;
config_.width_ = kWidth;
config_.height_ = kHeight;
EXPECT_CALL(*this, OnInitializeComplete(_))
.WillOnce(SaveInitializeResult(this));
test_engine_->Initialize(MessageLoop::current(), this, config_);
EXPECT_TRUE(info_.success_);
}
public:
MOCK_METHOD1(OnFillBufferCallback,
void(scoped_refptr<VideoFrame> video_frame));
MOCK_METHOD1(OnEmptyBufferCallback,
void(scoped_refptr<Buffer> buffer));
MOCK_METHOD1(OnInitializeComplete,
void(const VideoCodecInfo& info));
MOCK_METHOD0(OnUninitializeComplete, void());
MOCK_METHOD0(OnFlushComplete, void());
MOCK_METHOD0(OnSeekComplete, void());
MOCK_METHOD0(OnError, void());
MOCK_METHOD1(OnFormatChange, void(VideoStreamInfo stream_info));
scoped_refptr<VideoFrame> video_frame_;
VideoCodecConfig config_;
VideoCodecInfo info_;
protected:
scoped_refptr<FFmpegVideoDecodeEngine> test_engine_;
scoped_array<uint8_t> frame_buffer_;
StrictMock<MockFFmpeg> mock_ffmpeg_;
AVFrame yuv_frame_;
AVCodecContext codec_context_;
AVStream stream_;
AVCodec codec_;
scoped_refptr<DataBuffer> buffer_;
};
TEST_F(FFmpegVideoDecodeEngineTest, Initialize_Normal) {
Initialize();
}
TEST_F(FFmpegVideoDecodeEngineTest, Initialize_FindDecoderFails) {
// Test avcodec_find_decoder() returning NULL.
EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))
.WillOnce(ReturnNull());
EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())
.WillOnce(Return(&yuv_frame_));
EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))
.Times(1);
config_.codec_ = kCodecH264;
config_.opaque_context_ = &stream_;
config_.width_ = kWidth;
config_.height_ = kHeight;
EXPECT_CALL(*this, OnInitializeComplete(_))
.WillOnce(SaveInitializeResult(this));
test_engine_->Initialize(MessageLoop::current(), this, config_);
EXPECT_FALSE(info_.success_);
}
TEST_F(FFmpegVideoDecodeEngineTest, Initialize_InitThreadFails) {
// Test avcodec_thread_init() failing.
EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))
.WillOnce(Return(&codec_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())
.WillOnce(Return(&yuv_frame_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))
.WillOnce(Return(-1));
EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))
.Times(1);
config_.codec_ = kCodecH264;
config_.opaque_context_ = &stream_;
config_.width_ = kWidth;
config_.height_ = kHeight;
EXPECT_CALL(*this, OnInitializeComplete(_))
.WillOnce(SaveInitializeResult(this));
test_engine_->Initialize(MessageLoop::current(), this, config_);
EXPECT_FALSE(info_.success_);
}
TEST_F(FFmpegVideoDecodeEngineTest, Initialize_OpenDecoderFails) {
// Test avcodec_open() failing.
EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))
.WillOnce(Return(&codec_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())
.WillOnce(Return(&yuv_frame_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 3))
.WillOnce(Return(0));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecOpen(&codec_context_, &codec_))
.WillOnce(Return(-1));
EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))
.Times(1);
config_.codec_ = kCodecH264;
config_.opaque_context_ = &stream_;
config_.width_ = kWidth;
config_.height_ = kHeight;
EXPECT_CALL(*this, OnInitializeComplete(_))
.WillOnce(SaveInitializeResult(this));
test_engine_->Initialize(MessageLoop::current(), this, config_);
EXPECT_FALSE(info_.success_);
}
ACTION_P2(DemuxComplete, engine, buffer) {
engine->EmptyThisBuffer(buffer);
}
ACTION_P(DecodeComplete, decoder) {
decoder->video_frame_ = arg0;
}
TEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_Normal) {
Initialize();
// We rely on FFmpeg for timestamp and duration reporting. The one tricky
// bit is calculating the duration when |repeat_pict| > 0.
const base::TimeDelta kTimestamp = base::TimeDelta::FromMicroseconds(123);
const base::TimeDelta kDuration = base::TimeDelta::FromMicroseconds(15000);
yuv_frame_.repeat_pict = 1;
yuv_frame_.reordered_opaque = kTimestamp.InMicroseconds();
// Expect a bunch of avcodec calls.
EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_));
EXPECT_CALL(mock_ffmpeg_,
AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))
.WillOnce(DoAll(SetArgumentPointee<2>(1), // Simulate 1 byte frame.
Return(0)));
EXPECT_CALL(*this, OnEmptyBufferCallback(_))
.WillOnce(DemuxComplete(test_engine_.get(), buffer_));
EXPECT_CALL(*this, OnFillBufferCallback(_))
.WillOnce(DecodeComplete(this));
test_engine_->FillThisBuffer(video_frame_);
// |video_frame_| timestamp is 0 because we set the timestamp based off
// the buffer timestamp.
EXPECT_EQ(0, video_frame_->GetTimestamp().ToInternalValue());
EXPECT_EQ(kDuration.ToInternalValue(),
video_frame_->GetDuration().ToInternalValue());
}
TEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_0ByteFrame) {
Initialize();
// Expect a bunch of avcodec calls.
EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_))
.Times(2);
EXPECT_CALL(mock_ffmpeg_,
AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))
.WillOnce(DoAll(SetArgumentPointee<2>(0), // Simulate 0 byte frame.
Return(0)))
.WillOnce(DoAll(SetArgumentPointee<2>(1), // Simulate 1 byte frame.
Return(0)));
EXPECT_CALL(*this, OnEmptyBufferCallback(_))
.WillOnce(DemuxComplete(test_engine_.get(), buffer_))
.WillOnce(DemuxComplete(test_engine_.get(), buffer_));
EXPECT_CALL(*this, OnFillBufferCallback(_))
.WillOnce(DecodeComplete(this));
test_engine_->FillThisBuffer(video_frame_);
EXPECT_TRUE(video_frame_.get());
}
TEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_DecodeError) {
Initialize();
// Expect a bunch of avcodec calls.
EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_));
EXPECT_CALL(mock_ffmpeg_,
AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))
.WillOnce(Return(-1));
EXPECT_CALL(*this, OnEmptyBufferCallback(_))
.WillOnce(DemuxComplete(test_engine_.get(), buffer_));
EXPECT_CALL(*this, OnFillBufferCallback(_))
.WillOnce(DecodeComplete(this));
test_engine_->FillThisBuffer(video_frame_);
EXPECT_FALSE(video_frame_.get());
}
TEST_F(FFmpegVideoDecodeEngineTest, GetSurfaceFormat) {
// YV12 formats.
codec_context_.pix_fmt = PIX_FMT_YUV420P;
EXPECT_EQ(VideoFrame::YV12, test_engine_->GetSurfaceFormat());
codec_context_.pix_fmt = PIX_FMT_YUVJ420P;
EXPECT_EQ(VideoFrame::YV12, test_engine_->GetSurfaceFormat());
// YV16 formats.
codec_context_.pix_fmt = PIX_FMT_YUV422P;
EXPECT_EQ(VideoFrame::YV16, test_engine_->GetSurfaceFormat());
codec_context_.pix_fmt = PIX_FMT_YUVJ422P;
EXPECT_EQ(VideoFrame::YV16, test_engine_->GetSurfaceFormat());
// Invalid value.
codec_context_.pix_fmt = PIX_FMT_NONE;
EXPECT_EQ(VideoFrame::INVALID, test_engine_->GetSurfaceFormat());
}
} // namespace media
<commit_msg>another mock failure BUG=none TEST=none<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/scoped_ptr.h"
#include "media/base/data_buffer.h"
#include "media/base/mock_ffmpeg.h"
#include "media/base/mock_task.h"
#include "media/filters/ffmpeg_video_decode_engine.h"
#include "media/filters/ffmpeg_video_decoder.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::DoAll;
using ::testing::Return;
using ::testing::ReturnNull;
using ::testing::SetArgumentPointee;
using ::testing::StrictMock;
namespace media {
static const int kWidth = 320;
static const int kHeight = 240;
static const AVRational kTimeBase = { 1, 100 };
ACTION_P(SaveInitializeResult, engine) {
engine->info_ = arg0;
}
class FFmpegVideoDecodeEngineTest : public testing::Test,
public VideoDecodeEngine::EventHandler {
protected:
FFmpegVideoDecodeEngineTest() {
// Setup FFmpeg structures.
frame_buffer_.reset(new uint8[kWidth * kHeight]);
memset(&yuv_frame_, 0, sizeof(yuv_frame_));
// DecodeFrame will check these pointers as non-NULL value.
yuv_frame_.data[0] = yuv_frame_.data[1] = yuv_frame_.data[2]
= frame_buffer_.get();
yuv_frame_.linesize[0] = kWidth;
yuv_frame_.linesize[1] = yuv_frame_.linesize[2] = kWidth >> 1;
memset(&codec_context_, 0, sizeof(codec_context_));
codec_context_.width = kWidth;
codec_context_.height = kHeight;
codec_context_.time_base = kTimeBase;
memset(&codec_, 0, sizeof(codec_));
memset(&stream_, 0, sizeof(stream_));
stream_.codec = &codec_context_;
stream_.r_frame_rate.num = kTimeBase.den;
stream_.r_frame_rate.den = kTimeBase.num;
buffer_ = new DataBuffer(1);
// Initialize MockFFmpeg.
MockFFmpeg::set(&mock_ffmpeg_);
test_engine_ = new FFmpegVideoDecodeEngine();
test_engine_->SetCodecContextForTest(&codec_context_);
VideoFrame::CreateFrame(VideoFrame::YV12,
kWidth,
kHeight,
StreamSample::kInvalidTimestamp,
StreamSample::kInvalidTimestamp,
&video_frame_);
}
~FFmpegVideoDecodeEngineTest() {
test_engine_ = NULL;
MockFFmpeg::set(NULL);
}
void Initialize() {
EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))
.WillOnce(Return(&codec_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())
.WillOnce(Return(&yuv_frame_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))
.WillOnce(Return(0));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecOpen(&codec_context_, &codec_))
.WillOnce(Return(0));
EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))
.Times(1);
config_.codec_ = kCodecH264;
config_.opaque_context_ = &stream_;
config_.width_ = kWidth;
config_.height_ = kHeight;
EXPECT_CALL(*this, OnInitializeComplete(_))
.WillOnce(SaveInitializeResult(this));
test_engine_->Initialize(MessageLoop::current(), this, config_);
EXPECT_TRUE(info_.success_);
}
public:
MOCK_METHOD1(OnFillBufferCallback,
void(scoped_refptr<VideoFrame> video_frame));
MOCK_METHOD1(OnEmptyBufferCallback,
void(scoped_refptr<Buffer> buffer));
MOCK_METHOD1(OnInitializeComplete,
void(const VideoCodecInfo& info));
MOCK_METHOD0(OnUninitializeComplete, void());
MOCK_METHOD0(OnFlushComplete, void());
MOCK_METHOD0(OnSeekComplete, void());
MOCK_METHOD0(OnError, void());
MOCK_METHOD1(OnFormatChange, void(VideoStreamInfo stream_info));
scoped_refptr<VideoFrame> video_frame_;
VideoCodecConfig config_;
VideoCodecInfo info_;
protected:
scoped_refptr<FFmpegVideoDecodeEngine> test_engine_;
scoped_array<uint8_t> frame_buffer_;
StrictMock<MockFFmpeg> mock_ffmpeg_;
AVFrame yuv_frame_;
AVCodecContext codec_context_;
AVStream stream_;
AVCodec codec_;
scoped_refptr<DataBuffer> buffer_;
};
TEST_F(FFmpegVideoDecodeEngineTest, Initialize_Normal) {
Initialize();
}
TEST_F(FFmpegVideoDecodeEngineTest, Initialize_FindDecoderFails) {
// Test avcodec_find_decoder() returning NULL.
EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))
.WillOnce(ReturnNull());
EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())
.WillOnce(Return(&yuv_frame_));
EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))
.Times(1);
config_.codec_ = kCodecH264;
config_.opaque_context_ = &stream_;
config_.width_ = kWidth;
config_.height_ = kHeight;
EXPECT_CALL(*this, OnInitializeComplete(_))
.WillOnce(SaveInitializeResult(this));
test_engine_->Initialize(MessageLoop::current(), this, config_);
EXPECT_FALSE(info_.success_);
}
TEST_F(FFmpegVideoDecodeEngineTest, Initialize_InitThreadFails) {
// Test avcodec_thread_init() failing.
EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))
.WillOnce(Return(&codec_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())
.WillOnce(Return(&yuv_frame_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))
.WillOnce(Return(-1));
EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))
.Times(1);
config_.codec_ = kCodecH264;
config_.opaque_context_ = &stream_;
config_.width_ = kWidth;
config_.height_ = kHeight;
EXPECT_CALL(*this, OnInitializeComplete(_))
.WillOnce(SaveInitializeResult(this));
test_engine_->Initialize(MessageLoop::current(), this, config_);
EXPECT_FALSE(info_.success_);
}
TEST_F(FFmpegVideoDecodeEngineTest, Initialize_OpenDecoderFails) {
// Test avcodec_open() failing.
EXPECT_CALL(*MockFFmpeg::get(), AVCodecFindDecoder(CODEC_ID_NONE))
.WillOnce(Return(&codec_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecAllocFrame())
.WillOnce(Return(&yuv_frame_));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecThreadInit(&codec_context_, 2))
.WillOnce(Return(0));
EXPECT_CALL(*MockFFmpeg::get(), AVCodecOpen(&codec_context_, &codec_))
.WillOnce(Return(-1));
EXPECT_CALL(*MockFFmpeg::get(), AVFree(&yuv_frame_))
.Times(1);
config_.codec_ = kCodecH264;
config_.opaque_context_ = &stream_;
config_.width_ = kWidth;
config_.height_ = kHeight;
EXPECT_CALL(*this, OnInitializeComplete(_))
.WillOnce(SaveInitializeResult(this));
test_engine_->Initialize(MessageLoop::current(), this, config_);
EXPECT_FALSE(info_.success_);
}
ACTION_P2(DemuxComplete, engine, buffer) {
engine->EmptyThisBuffer(buffer);
}
ACTION_P(DecodeComplete, decoder) {
decoder->video_frame_ = arg0;
}
TEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_Normal) {
Initialize();
// We rely on FFmpeg for timestamp and duration reporting. The one tricky
// bit is calculating the duration when |repeat_pict| > 0.
const base::TimeDelta kTimestamp = base::TimeDelta::FromMicroseconds(123);
const base::TimeDelta kDuration = base::TimeDelta::FromMicroseconds(15000);
yuv_frame_.repeat_pict = 1;
yuv_frame_.reordered_opaque = kTimestamp.InMicroseconds();
// Expect a bunch of avcodec calls.
EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_));
EXPECT_CALL(mock_ffmpeg_,
AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))
.WillOnce(DoAll(SetArgumentPointee<2>(1), // Simulate 1 byte frame.
Return(0)));
EXPECT_CALL(*this, OnEmptyBufferCallback(_))
.WillOnce(DemuxComplete(test_engine_.get(), buffer_));
EXPECT_CALL(*this, OnFillBufferCallback(_))
.WillOnce(DecodeComplete(this));
test_engine_->FillThisBuffer(video_frame_);
// |video_frame_| timestamp is 0 because we set the timestamp based off
// the buffer timestamp.
EXPECT_EQ(0, video_frame_->GetTimestamp().ToInternalValue());
EXPECT_EQ(kDuration.ToInternalValue(),
video_frame_->GetDuration().ToInternalValue());
}
TEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_0ByteFrame) {
Initialize();
// Expect a bunch of avcodec calls.
EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_))
.Times(2);
EXPECT_CALL(mock_ffmpeg_,
AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))
.WillOnce(DoAll(SetArgumentPointee<2>(0), // Simulate 0 byte frame.
Return(0)))
.WillOnce(DoAll(SetArgumentPointee<2>(1), // Simulate 1 byte frame.
Return(0)));
EXPECT_CALL(*this, OnEmptyBufferCallback(_))
.WillOnce(DemuxComplete(test_engine_.get(), buffer_))
.WillOnce(DemuxComplete(test_engine_.get(), buffer_));
EXPECT_CALL(*this, OnFillBufferCallback(_))
.WillOnce(DecodeComplete(this));
test_engine_->FillThisBuffer(video_frame_);
EXPECT_TRUE(video_frame_.get());
}
TEST_F(FFmpegVideoDecodeEngineTest, DecodeFrame_DecodeError) {
Initialize();
// Expect a bunch of avcodec calls.
EXPECT_CALL(mock_ffmpeg_, AVInitPacket(_));
EXPECT_CALL(mock_ffmpeg_,
AVCodecDecodeVideo2(&codec_context_, &yuv_frame_, _, _))
.WillOnce(Return(-1));
EXPECT_CALL(*this, OnEmptyBufferCallback(_))
.WillOnce(DemuxComplete(test_engine_.get(), buffer_));
EXPECT_CALL(*this, OnFillBufferCallback(_))
.WillOnce(DecodeComplete(this));
test_engine_->FillThisBuffer(video_frame_);
EXPECT_FALSE(video_frame_.get());
}
TEST_F(FFmpegVideoDecodeEngineTest, GetSurfaceFormat) {
// YV12 formats.
codec_context_.pix_fmt = PIX_FMT_YUV420P;
EXPECT_EQ(VideoFrame::YV12, test_engine_->GetSurfaceFormat());
codec_context_.pix_fmt = PIX_FMT_YUVJ420P;
EXPECT_EQ(VideoFrame::YV12, test_engine_->GetSurfaceFormat());
// YV16 formats.
codec_context_.pix_fmt = PIX_FMT_YUV422P;
EXPECT_EQ(VideoFrame::YV16, test_engine_->GetSurfaceFormat());
codec_context_.pix_fmt = PIX_FMT_YUVJ422P;
EXPECT_EQ(VideoFrame::YV16, test_engine_->GetSurfaceFormat());
// Invalid value.
codec_context_.pix_fmt = PIX_FMT_NONE;
EXPECT_EQ(VideoFrame::INVALID, test_engine_->GetSurfaceFormat());
}
} // namespace media
<|endoftext|>
|
<commit_before>#include "scheduler.h"
#include <pthread.h> //for pthread_setschedparam
#include <time.h> //for clock_nanosleep
#include <signal.h> //for sigaction signal handlers
#include "logging.h"
#include "timeutil.h"
void onExit() {
LOG("Exiting\n");
}
void signalHandler(int s){
printf("Caught signal %d\n",s);
exit(1);
}
void segfaultHandler(int signal, siginfo_t *si, void *arg) {
printf("Caught segfault at address %p\n", si->si_addr);
exit(1);
}
static void Scheduler::configureExitHandlers() {
if (DO_LOG) {
std::atexit(onExit);
}
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = signalHandler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
struct sigaction sa;
//memset(&sa, 0, sizeof(sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = segfaultHandler;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
}
Scheduler::Scheduler() : _lockPushes(mutex, std::defer_lock), _arePushesLocked(false) {
clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //initialize to current time.
}
void Scheduler::queue(const Event& evt) {
//LOGV("Scheduler::queue\n");
std::unique_lock<std::mutex> lock(this->mutex);
if (this->eventQueue.empty()) { //if no event is before this, then the relative time held by this event must be associated with the current time:
clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime));
}
this->eventQueue.push(evt);
this->nonemptyCond.notify_one(); //notify the consumer thread that a new event is ready.
}
Event Scheduler::nextEvent() {
Event evt;
{
//std::unique_lock<std::mutex> lock(this->mutex);
if (!this->_arePushesLocked) { //check if the mutex is already locked *by us*
_lockPushes.lock();
}
while (this->eventQueue.empty()) { //wait for an event to be pushed.
this->nonemptyCond.wait(_lockPushes); //condition_variable.wait() can produce spurious wakeups; need the while loop.
}
evt = this->eventQueue.front();
this->eventQueue.pop();
if (this->eventQueue.size() < SCHED_CAPACITY) { //queue is underfilled; release the lock
_lockPushes.unlock();
this->_arePushesLocked = false;
} else { //queue is filled; do not release the lock.
this->_arePushesLocked = true;
}
} //unlock the mutex and then handle the event.
struct timespec sleepUntil = evt.time();
struct timespec curTime;
clock_gettime(CLOCK_MONOTONIC, &curTime);
//struct timespec sleepUntil = timespecAdd(this->lastEventHandledTime, evt.time());
//LOGV("Scheduler::nextEvent sleep from %lu.%lu until %lu.%lu\n", curTime.tv_sec, curTime.tv_nsec, sleepUntil.tv_sec, sleepUntil.tv_nsec);
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &sleepUntil, NULL); //sleep to event time.
//clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //in case we fall behind, preserve the relative time between events.
this->lastEventHandledTime = sleepUntil;
return evt;
}
void Scheduler::initSchedThread() {
struct sched_param sp;
sp.sched_priority=SCHED_PRIORITY;
if (int ret = pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp)) {
LOGW("Warning: pthread_setschedparam (increase thread priority) at scheduler.cpp returned non-zero: %i\n", ret);
}
}
struct timespec Scheduler::lastSchedTime() const {
Event evt;
{
std::unique_lock<std::mutex> lock(this->mutex);
if (this->eventQueue.size()) {
evt = this->eventQueue.back();
} else {
lock.unlock();
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts;
}
}
return evt.time();
}
<commit_msg>catch ctrl-z<commit_after>#include "scheduler.h"
#include <pthread.h> //for pthread_setschedparam
#include <time.h> //for clock_nanosleep
#include <signal.h> //for sigaction signal handlers
#include "logging.h"
#include "timeutil.h"
void onExit() {
LOG("Exiting\n");
}
void signalHandler(int s){
printf("Caught signal %d\n",s);
exit(1);
}
void segfaultHandler(int signal, siginfo_t *si, void *arg) {
printf("Caught segfault at address %p\n", si->si_addr);
exit(1);
}
static void Scheduler::configureExitHandlers() {
if (DO_LOG) {
std::atexit(onExit);
}
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = signalHandler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
sigaction(SIGTSTP, &sigIntHandler, NULL);
struct sigaction sa;
//memset(&sa, 0, sizeof(sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = segfaultHandler;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
}
Scheduler::Scheduler() : _lockPushes(mutex, std::defer_lock), _arePushesLocked(false) {
clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //initialize to current time.
}
void Scheduler::queue(const Event& evt) {
//LOGV("Scheduler::queue\n");
std::unique_lock<std::mutex> lock(this->mutex);
if (this->eventQueue.empty()) { //if no event is before this, then the relative time held by this event must be associated with the current time:
clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime));
}
this->eventQueue.push(evt);
this->nonemptyCond.notify_one(); //notify the consumer thread that a new event is ready.
}
Event Scheduler::nextEvent() {
Event evt;
{
//std::unique_lock<std::mutex> lock(this->mutex);
if (!this->_arePushesLocked) { //check if the mutex is already locked *by us*
_lockPushes.lock();
}
while (this->eventQueue.empty()) { //wait for an event to be pushed.
this->nonemptyCond.wait(_lockPushes); //condition_variable.wait() can produce spurious wakeups; need the while loop.
}
evt = this->eventQueue.front();
this->eventQueue.pop();
if (this->eventQueue.size() < SCHED_CAPACITY) { //queue is underfilled; release the lock
_lockPushes.unlock();
this->_arePushesLocked = false;
} else { //queue is filled; do not release the lock.
this->_arePushesLocked = true;
}
} //unlock the mutex and then handle the event.
struct timespec sleepUntil = evt.time();
struct timespec curTime;
clock_gettime(CLOCK_MONOTONIC, &curTime);
//struct timespec sleepUntil = timespecAdd(this->lastEventHandledTime, evt.time());
//LOGV("Scheduler::nextEvent sleep from %lu.%lu until %lu.%lu\n", curTime.tv_sec, curTime.tv_nsec, sleepUntil.tv_sec, sleepUntil.tv_nsec);
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &sleepUntil, NULL); //sleep to event time.
//clock_gettime(CLOCK_MONOTONIC, &(this->lastEventHandledTime)); //in case we fall behind, preserve the relative time between events.
this->lastEventHandledTime = sleepUntil;
return evt;
}
void Scheduler::initSchedThread() {
struct sched_param sp;
sp.sched_priority=SCHED_PRIORITY;
if (int ret = pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp)) {
LOGW("Warning: pthread_setschedparam (increase thread priority) at scheduler.cpp returned non-zero: %i\n", ret);
}
}
struct timespec Scheduler::lastSchedTime() const {
Event evt;
{
std::unique_lock<std::mutex> lock(this->mutex);
if (this->eventQueue.size()) {
evt = this->eventQueue.back();
} else {
lock.unlock();
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts;
}
}
return evt.time();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_libevent.h"
#include <errno.h>
#include <fcntl.h>
#include "eintr_wrapper.h"
#include "base/auto_reset.h"
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/scoped_ptr.h"
#include "base/time.h"
#include "third_party/libevent/event.h"
// Lifecycle of struct event
// Libevent uses two main data structures:
// struct event_base (of which there is one per message pump), and
// struct event (of which there is roughly one per socket).
// The socket's struct event is created in
// MessagePumpLibevent::WatchFileDescriptor(),
// is owned by the FileDescriptorWatcher, and is destroyed in
// StopWatchingFileDescriptor().
// It is moved into and out of lists in struct event_base by
// the libevent functions event_add() and event_del().
//
// TODO(dkegel):
// At the moment bad things happen if a FileDescriptorWatcher
// is active after its MessagePumpLibevent has been destroyed.
// See MessageLoopTest.FileDescriptorWatcherOutlivesMessageLoop
// Not clear yet whether that situation occurs in practice,
// but if it does, we need to fix it.
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: is_persistent_(false),
event_(NULL) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_) {
StopWatchingFileDescriptor();
}
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
DCHECK(event_ == NULL);
is_persistent_ = is_persistent;
event_ = e;
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
struct event *e = event_;
event_ = NULL;
return e;
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
event* e = ReleaseEvent();
if (e == NULL)
return true;
// event_del() is a no-op if the event isn't active.
int rv = event_del(e);
delete e;
return (rv == 0);
}
// Called if a byte is received on the wakeup pipe.
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = HANDLE_EINTR(read(socket, &buf, 1));
DCHECK_EQ(nread, 1);
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
if (wakeup_pipe_in_ >= 0)
close(wakeup_pipe_in_);
if (wakeup_pipe_out_ >= 0)
close(wakeup_pipe_out_);
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK(fd > 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
int event_mask = persistent ? EV_PERSIST : 0;
if ((mode & WATCH_READ) != 0) {
event_mask |= EV_READ;
}
if ((mode & WATCH_WRITE) != 0) {
event_mask |= EV_WRITE;
}
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
// Ownership is transferred to the controller.
evt.reset(new event);
} else {
// Make sure we don't pick up any funky internal libevent masks.
int old_interest_mask = evt.get()->ev_events &
(EV_READ | EV_WRITE | EV_PERSIST);
// Combine old/new event masks.
event_mask |= old_interest_mask;
// Must disarm the event before we can reuse it.
event_del(evt.get());
// It's illegal to use this function to listen on 2 separate fds with the
// same |controller|.
if (EVENT_FD(evt.get()) != fd) {
NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd;
return false;
}
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification, delegate);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get()) != 0) {
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL) != 0) {
return false;
}
// Transfer ownership of evt to controller.
controller->Init(evt.release(), persistent);
return true;
}
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
Watcher* watcher = static_cast<Watcher*>(context);
if (flags & EV_WRITE) {
watcher->OnFileCanWriteWithoutBlocking(fd);
}
if (flags & EV_READ) {
watcher->OnFileCanReadWithoutBlocking(fd);
}
}
// Tell libevent to break out of inner loop.
static void timer_callback(int fd, short events, void *context)
{
event_base_loopbreak((struct event_base *)context);
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
AutoReset auto_reset_in_run(&in_run_, true);
// event_base_loopexit() + EVLOOP_ONCE is leaky, see http://crbug.com/25641.
// Instead, make our own timer and reuse it on each call to event_base_loop().
scoped_ptr<event> timer_event(new event);
for (;;) {
ScopedNSAutoreleasePool autorelease_pool;
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - Time::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_set(timer_event.get(), -1, 0, timer_callback, event_base_);
event_base_set(event_base_, timer_event.get());
event_add(timer_event.get(), &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
event_del(timer_event.get());
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = Time();
}
}
}
keep_running_ = true;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = HANDLE_EINTR(write(wakeup_pipe_in_, &buf, 1));
DCHECK(nwrite == 1 || errno == EAGAIN)
<< "[nwrite:" << nwrite << "] [errno:" << errno << "]";
}
void MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
} // namespace base
<commit_msg>Fix DCHECK that thinks fd = 0 is invalid.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/message_pump_libevent.h"
#include <errno.h>
#include <fcntl.h>
#include "eintr_wrapper.h"
#include "base/auto_reset.h"
#include "base/logging.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/scoped_ptr.h"
#include "base/time.h"
#include "third_party/libevent/event.h"
// Lifecycle of struct event
// Libevent uses two main data structures:
// struct event_base (of which there is one per message pump), and
// struct event (of which there is roughly one per socket).
// The socket's struct event is created in
// MessagePumpLibevent::WatchFileDescriptor(),
// is owned by the FileDescriptorWatcher, and is destroyed in
// StopWatchingFileDescriptor().
// It is moved into and out of lists in struct event_base by
// the libevent functions event_add() and event_del().
//
// TODO(dkegel):
// At the moment bad things happen if a FileDescriptorWatcher
// is active after its MessagePumpLibevent has been destroyed.
// See MessageLoopTest.FileDescriptorWatcherOutlivesMessageLoop
// Not clear yet whether that situation occurs in practice,
// but if it does, we need to fix it.
namespace base {
// Return 0 on success
// Too small a function to bother putting in a library?
static int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
: is_persistent_(false),
event_(NULL) {
}
MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
if (event_) {
StopWatchingFileDescriptor();
}
}
void MessagePumpLibevent::FileDescriptorWatcher::Init(event *e,
bool is_persistent) {
DCHECK(e);
DCHECK(event_ == NULL);
is_persistent_ = is_persistent;
event_ = e;
}
event *MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
struct event *e = event_;
event_ = NULL;
return e;
}
bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
event* e = ReleaseEvent();
if (e == NULL)
return true;
// event_del() is a no-op if the event isn't active.
int rv = event_del(e);
delete e;
return (rv == 0);
}
// Called if a byte is received on the wakeup pipe.
void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
base::MessagePumpLibevent* that =
static_cast<base::MessagePumpLibevent*>(context);
DCHECK(that->wakeup_pipe_out_ == socket);
// Remove and discard the wakeup byte.
char buf;
int nread = HANDLE_EINTR(read(socket, &buf, 1));
DCHECK_EQ(nread, 1);
// Tell libevent to break out of inner loop.
event_base_loopbreak(that->event_base_);
}
MessagePumpLibevent::MessagePumpLibevent()
: keep_running_(true),
in_run_(false),
event_base_(event_base_new()),
wakeup_pipe_in_(-1),
wakeup_pipe_out_(-1) {
if (!Init())
NOTREACHED();
}
bool MessagePumpLibevent::Init() {
int fds[2];
if (pipe(fds)) {
DLOG(ERROR) << "pipe() failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[0])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
return false;
}
if (SetNonBlocking(fds[1])) {
DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
return false;
}
wakeup_pipe_out_ = fds[0];
wakeup_pipe_in_ = fds[1];
wakeup_event_ = new event;
event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST,
OnWakeup, this);
event_base_set(event_base_, wakeup_event_);
if (event_add(wakeup_event_, 0))
return false;
return true;
}
MessagePumpLibevent::~MessagePumpLibevent() {
DCHECK(wakeup_event_);
DCHECK(event_base_);
event_del(wakeup_event_);
delete wakeup_event_;
if (wakeup_pipe_in_ >= 0)
close(wakeup_pipe_in_);
if (wakeup_pipe_out_ >= 0)
close(wakeup_pipe_out_);
event_base_free(event_base_);
}
bool MessagePumpLibevent::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
DCHECK_GE(fd, 0);
DCHECK(controller);
DCHECK(delegate);
DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
int event_mask = persistent ? EV_PERSIST : 0;
if ((mode & WATCH_READ) != 0) {
event_mask |= EV_READ;
}
if ((mode & WATCH_WRITE) != 0) {
event_mask |= EV_WRITE;
}
scoped_ptr<event> evt(controller->ReleaseEvent());
if (evt.get() == NULL) {
// Ownership is transferred to the controller.
evt.reset(new event);
} else {
// Make sure we don't pick up any funky internal libevent masks.
int old_interest_mask = evt.get()->ev_events &
(EV_READ | EV_WRITE | EV_PERSIST);
// Combine old/new event masks.
event_mask |= old_interest_mask;
// Must disarm the event before we can reuse it.
event_del(evt.get());
// It's illegal to use this function to listen on 2 separate fds with the
// same |controller|.
if (EVENT_FD(evt.get()) != fd) {
NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd;
return false;
}
}
// Set current interest mask and message pump for this event.
event_set(evt.get(), fd, event_mask, OnLibeventNotification, delegate);
// Tell libevent which message pump this socket will belong to when we add it.
if (event_base_set(event_base_, evt.get()) != 0) {
return false;
}
// Add this socket to the list of monitored sockets.
if (event_add(evt.get(), NULL) != 0) {
return false;
}
// Transfer ownership of evt to controller.
controller->Init(evt.release(), persistent);
return true;
}
void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
void* context) {
Watcher* watcher = static_cast<Watcher*>(context);
if (flags & EV_WRITE) {
watcher->OnFileCanWriteWithoutBlocking(fd);
}
if (flags & EV_READ) {
watcher->OnFileCanReadWithoutBlocking(fd);
}
}
// Tell libevent to break out of inner loop.
static void timer_callback(int fd, short events, void *context)
{
event_base_loopbreak((struct event_base *)context);
}
// Reentrant!
void MessagePumpLibevent::Run(Delegate* delegate) {
DCHECK(keep_running_) << "Quit must have been called outside of Run!";
AutoReset auto_reset_in_run(&in_run_, true);
// event_base_loopexit() + EVLOOP_ONCE is leaky, see http://crbug.com/25641.
// Instead, make our own timer and reuse it on each call to event_base_loop().
scoped_ptr<event> timer_event(new event);
for (;;) {
ScopedNSAutoreleasePool autorelease_pool;
bool did_work = delegate->DoWork();
if (!keep_running_)
break;
did_work |= delegate->DoDelayedWork(&delayed_work_time_);
if (!keep_running_)
break;
if (did_work)
continue;
did_work = delegate->DoIdleWork();
if (!keep_running_)
break;
if (did_work)
continue;
// EVLOOP_ONCE tells libevent to only block once,
// but to service all pending events when it wakes up.
if (delayed_work_time_.is_null()) {
event_base_loop(event_base_, EVLOOP_ONCE);
} else {
TimeDelta delay = delayed_work_time_ - Time::Now();
if (delay > TimeDelta()) {
struct timeval poll_tv;
poll_tv.tv_sec = delay.InSeconds();
poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
event_set(timer_event.get(), -1, 0, timer_callback, event_base_);
event_base_set(event_base_, timer_event.get());
event_add(timer_event.get(), &poll_tv);
event_base_loop(event_base_, EVLOOP_ONCE);
event_del(timer_event.get());
} else {
// It looks like delayed_work_time_ indicates a time in the past, so we
// need to call DoDelayedWork now.
delayed_work_time_ = Time();
}
}
}
keep_running_ = true;
}
void MessagePumpLibevent::Quit() {
DCHECK(in_run_);
// Tell both libevent and Run that they should break out of their loops.
keep_running_ = false;
ScheduleWork();
}
void MessagePumpLibevent::ScheduleWork() {
// Tell libevent (in a threadsafe way) that it should break out of its loop.
char buf = 0;
int nwrite = HANDLE_EINTR(write(wakeup_pipe_in_, &buf, 1));
DCHECK(nwrite == 1 || errno == EAGAIN)
<< "[nwrite:" << nwrite << "] [errno:" << errno << "]";
}
void MessagePumpLibevent::ScheduleDelayedWork(const Time& delayed_work_time) {
// We know that we can't be blocked on Wait right now since this method can
// only be called on the same thread as Run, so we only need to update our
// record of how long to sleep when we do sleep.
delayed_work_time_ = delayed_work_time;
}
} // namespace base
<|endoftext|>
|
<commit_before>/****************************************************************************
** irsimsend.c *************************************************************
****************************************************************************
*
* irsimsend - send all codes defined in a given config file.
*
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include <getopt.h>
#include "lirc_private.h"
#include "lirc_client.h"
static const char* const USAGE =
"Send key symbols durations to fixed file 'simsend.out'.\n\n"
"Synopsis:\n"
" irsimsend [-U path] [-s time] [-c count] <file>\n"
" irsimsend [-k keysym | -l listfile] [-U path] [-s time] [-c count]"
" <file>\n"
" irsimsend [-h | -v]\n\n"
"<file> is a lircd.conf type config file. In the first form, all keys in\n"
"that file are sent.\n\n"
"Options:\n"
" -U, --plugindir <path>: Load drivers from <path>.\n"
" -c, --config <count>: Repeat each key <count> times.\n"
" -l, --listfile <file> Send symbols in file.\n"
" -k, --keysym <keysym> Send a single keysym.\n"
" -s, --start-space <time> Send a start space <time> us\n"
" -v, --version Print version.\n"
" -h, --help Print this message.\n";
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ "count", required_argument, NULL, 'c' },
{ "keysym", required_argument, NULL, 'k' },
{ "listfile", required_argument, NULL, 'l' },
{ "pluginpath", required_argument, NULL, 'U' },
{ "start-space", required_argument, NULL, 's' },
{ 0, 0, 0, 0 }
};
static const char* const OUTFILE = "simsend.out";
static int opt_count = 1;
static int opt_startspace = -1;
static const char* opt_keysym = NULL;
static const char* opt_listfile = NULL;
static struct ir_remote* setup(const char* path)
{
struct ir_remote* remote;
FILE* f;
if (hw_choose_driver("file") == -1) {
fputs("Cannot load file driver (bad plugin path?)\n",
stderr);
exit(EXIT_FAILURE);
}
unlink(OUTFILE);
curr_driver->open_func(OUTFILE);
curr_driver->init_func();
if (opt_listfile != NULL && access(opt_listfile, R_OK) != 0) {
fprintf(stderr, "Cannot open %s for read\n", opt_listfile);
exit(EXIT_FAILURE);
}
f = fopen(path, "r");
if (f == NULL) {
fprintf(stderr, "Cannot open %s for read\n", path);
exit(EXIT_FAILURE);
}
remote = read_config(f, path);
fclose(f);
if (remote == NULL) {
fprintf(stderr, "Cannot parse %s\n", path);
exit(EXIT_FAILURE);
}
remote->min_repeat = 0;
return remote;
}
static void send_space(int duration)
{
char buff[64];
snprintf(buff, sizeof(buff), "send-space:%d", duration);
drv_handle_options(buff);
}
static void send_code(struct ir_remote* remote, struct ir_ncode* code)
{
int i;
static char last_code[32] = { '\0' };
code->transmit_state = NULL;
if (has_toggle_mask(remote))
remote->toggle_mask_state = 0;
if (has_toggle_bit_mask(remote))
remote->toggle_bit_mask_state =
(remote->toggle_bit_mask_state ^ remote->toggle_bit_mask);
code->transmit_state = NULL;
remote->min_repeat = 0;
if (strcmp(code->name, last_code) == 0)
repeat_remote = remote;
send_ir_ncode(remote, code, 0);
repeat_remote = remote;
for (i = 1; i < opt_count; i += 1)
send_ir_ncode(remote, code, 0);
repeat_remote = NULL;
strncpy(last_code, code->name, sizeof(last_code));
}
static int simsend_remote(struct ir_remote* remote)
{
struct ir_ncode* code;
for (code = remote->codes; code->name != NULL; code++) {
printf("%s\n", code->name);
send_code(remote, code);
}
return 0;
}
static int simsend_keysym(struct ir_remote* remote, const char* keysym)
{
struct ir_ncode* code;
code = get_code_by_name(remote, keysym);
if (code != NULL) {
send_code(remote, code);
printf("%s\n", keysym);
} else {
fprintf(stderr, "No such key: %s\n", keysym);
exit(EXIT_FAILURE);
}
return 0;
}
static int simsend_list(struct ir_remote* remote)
{
char line[256];
char keysym[32];
struct ir_ncode* code;
FILE* f;
char* s;
int r;
f = fopen(opt_listfile, "r");
s = fgets(line, sizeof(line), f);
while (s != NULL) {
r = sscanf(line, "%*x %*x %32s %*s", keysym);
if (r != 1)
r = sscanf(line, "%32s", keysym);
if (r != 1) {
printf("Cannot parse line: %s\n", line);
continue;
}
code = get_code_by_name(remote, keysym);
if (code == NULL) {
printf("Illegal keycode: %s\n", keysym);
} else {
printf("%s\n", code->name);
send_code(remote, code);
}
s = fgets(line, sizeof(line), f);
}
fclose(f);
return 0;
}
int parse_uint_arg(const char* optind, const char* errmsg)
{
long c;
c = strtol(optarg, NULL, 10);
if (c > INT_MAX || c < 0 || errno == EINVAL || errno == ERANGE) {
fputs(errmsg, stderr);
exit(EXIT_FAILURE);
}
return (int)c;
}
int main(int argc, char* argv[])
{
long c;
struct ir_remote* remote;
char path[128];
while ((c = getopt_long(argc, argv, "c:hk:l:s:U:v", options, NULL))
!= EOF) {
switch (c) {
case 'h':
puts(USAGE);
return EXIT_SUCCESS;
case 'c':
opt_count = parse_uint_arg(optarg,
"Illegal count value\n");
break;
case 'v':
printf("%s\n", "irw " VERSION);
return EXIT_SUCCESS;
case 'U':
options_set_opt("lircd:pluginpath", optarg);
break;
case 'k':
opt_keysym = optarg;
break;
case 'l':
opt_listfile = optarg;
break;
case 's':
opt_startspace = parse_uint_arg(optarg,
"Illegal space value\n");
break;
case '?':
fprintf(stderr, "unrecognized option: -%c\n", optopt);
fputs("Try `irsimsend -h' for more information.\n",
stderr);
return EXIT_FAILURE;
}
}
if (argc != optind + 1) {
fputs(USAGE, stderr);
return EXIT_FAILURE;
}
lirc_log_get_clientlog("irsimsend", path, sizeof(path));
lirc_log_set_file(path);
lirc_log_open("irsimsend", 1, LIRC_NOTICE);
remote = setup(argv[optind]);
if (opt_startspace != -1)
send_space(opt_startspace);
if (opt_keysym != NULL)
simsend_keysym(remote, opt_keysym);
else if (opt_listfile != NULL)
simsend_list(remote);
else
simsend_remote(remote);
return 0;
}
<commit_msg>irsimsend: bugfix.<commit_after>/****************************************************************************
** irsimsend.c *************************************************************
****************************************************************************
*
* irsimsend - send all codes defined in a given config file.
*
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
#include <getopt.h>
#include "lirc_private.h"
#include "lirc_client.h"
static const char* const USAGE =
"Send key symbols durations to fixed file 'simsend.out'.\n\n"
"Synopsis:\n"
" irsimsend [-U path] [-s time] [-c count] <file>\n"
" irsimsend [-k keysym | -l listfile] [-U path] [-s time] [-c count]"
" <file>\n"
" irsimsend [-h | -v]\n\n"
"<file> is a lircd.conf type config file. In the first form, all keys in\n"
"that file are sent.\n\n"
"Options:\n"
" -U, --plugindir <path>: Load drivers from <path>.\n"
" -c, --config <count>: Repeat each key <count> times.\n"
" -l, --listfile <file> Send symbols in file.\n"
" -k, --keysym <keysym> Send a single keysym.\n"
" -s, --start-space <time> Send a start space <time> us\n"
" -v, --version Print version.\n"
" -h, --help Print this message.\n";
static struct option options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ "count", required_argument, NULL, 'c' },
{ "keysym", required_argument, NULL, 'k' },
{ "listfile", required_argument, NULL, 'l' },
{ "pluginpath", required_argument, NULL, 'U' },
{ "start-space", required_argument, NULL, 's' },
{ 0, 0, 0, 0 }
};
static const char* const OUTFILE = "simsend.out";
static int opt_count = 1;
static int opt_startspace = -1;
static const char* opt_keysym = NULL;
static const char* opt_listfile = NULL;
static struct ir_remote* setup(const char* path)
{
struct ir_remote* remote;
FILE* f;
if (hw_choose_driver("file") == -1) {
fputs("Cannot load file driver (bad plugin path?)\n",
stderr);
exit(EXIT_FAILURE);
}
unlink(OUTFILE);
curr_driver->open_func(OUTFILE);
curr_driver->init_func();
if (opt_listfile != NULL && access(opt_listfile, R_OK) != 0) {
fprintf(stderr, "Cannot open %s for read\n", opt_listfile);
exit(EXIT_FAILURE);
}
f = fopen(path, "r");
if (f == NULL) {
fprintf(stderr, "Cannot open %s for read\n", path);
exit(EXIT_FAILURE);
}
remote = read_config(f, path);
fclose(f);
if (remote == NULL) {
fprintf(stderr, "Cannot parse %s\n", path);
exit(EXIT_FAILURE);
}
remote->min_repeat = 0;
return remote;
}
static void send_space(int duration)
{
char buff[64];
snprintf(buff, sizeof(buff), "send-space:%d", duration);
drv_handle_options(buff);
}
static void send_code(struct ir_remote* remote, struct ir_ncode* code)
{
int i;
static char last_code[32] = { '\0' };
code->transmit_state = NULL;
if (has_toggle_mask(remote))
remote->toggle_mask_state = 0;
if (has_toggle_bit_mask(remote))
remote->toggle_bit_mask_state =
(remote->toggle_bit_mask_state ^ remote->toggle_bit_mask);
code->transmit_state = NULL;
remote->min_repeat = 0;
if (strcmp(code->name, last_code) == 0)
repeat_remote = remote;
send_ir_ncode(remote, code, 0);
repeat_remote = remote;
for (i = 1; i < opt_count; i += 1)
send_ir_ncode(remote, code, 0);
repeat_remote = NULL;
strncpy(last_code, code->name, sizeof(last_code));
}
static int simsend_remote(struct ir_remote* remote)
{
struct ir_ncode* code;
for (code = remote->codes; code->name != NULL; code++) {
printf("%s\n", code->name);
send_code(remote, code);
}
return 0;
}
static int simsend_keysym(struct ir_remote* remote, const char* keysym)
{
struct ir_ncode* code;
code = get_code_by_name(remote, keysym);
if (code != NULL) {
send_code(remote, code);
printf("%s\n", keysym);
} else {
fprintf(stderr, "No such key: %s\n", keysym);
exit(EXIT_FAILURE);
}
return 0;
}
static int simsend_list(struct ir_remote* remote)
{
char line[256];
char keysym[32];
struct ir_ncode* code;
FILE* f;
char* s;
int r;
f = fopen(opt_listfile, "r");
s = fgets(line, sizeof(line), f);
while (s != NULL) {
r = sscanf(line, "%*x %*x %32s %*s", keysym);
if (r != 1)
r = sscanf(line, "%32s", keysym);
if (r != 1) {
printf("Cannot parse line: %s\n", line);
continue;
}
code = get_code_by_name(remote, keysym);
if (code == NULL) {
printf("Illegal keycode: %s\n", keysym);
} else {
printf("%s\n", code->name);
send_code(remote, code);
}
s = fgets(line, sizeof(line), f);
}
fclose(f);
return 0;
}
int parse_uint_arg(const char* optind, const char* errmsg)
{
long c;
c = strtol(optarg, NULL, 10);
if (c > INT_MAX || c < 0 || errno == EINVAL || errno == ERANGE) {
fputs(errmsg, stderr);
exit(EXIT_FAILURE);
}
return (int)c;
}
int main(int argc, char* argv[])
{
long c;
struct ir_remote* remote;
char path[128];
while ((c = getopt_long(argc, argv, "c:hk:l:s:U:v", options, NULL))
!= EOF) {
switch (c) {
case 'h':
puts(USAGE);
return EXIT_SUCCESS;
case 'c':
opt_count = parse_uint_arg(optarg,
"Illegal count value\n");
break;
case 'v':
printf("%s\n", "irw " VERSION);
return EXIT_SUCCESS;
case 'U':
options_set_opt("lircd:plugindir", optarg);
break;
case 'k':
opt_keysym = optarg;
break;
case 'l':
opt_listfile = optarg;
break;
case 's':
opt_startspace = parse_uint_arg(optarg,
"Illegal space value\n");
break;
case '?':
fprintf(stderr, "unrecognized option: -%c\n", optopt);
fputs("Try `irsimsend -h' for more information.\n",
stderr);
return EXIT_FAILURE;
}
}
if (argc != optind + 1) {
fputs(USAGE, stderr);
return EXIT_FAILURE;
}
lirc_log_get_clientlog("irsimsend", path, sizeof(path));
lirc_log_set_file(path);
lirc_log_open("irsimsend", 1, LIRC_NOTICE);
remote = setup(argv[optind]);
if (opt_startspace != -1)
send_space(opt_startspace);
if (opt_keysym != NULL)
simsend_keysym(remote, opt_keysym);
else if (opt_listfile != NULL)
simsend_list(remote);
else
simsend_remote(remote);
return 0;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////
//
// Pixie
//
// Copyright 1999 - 2003, Okan Arikan
//
// Contact: okan@cs.utexas.edu
//
// 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
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
// File : pointHierarchy.cpp
// Classes : CPointHierarchy
// Description :
//
////////////////////////////////////////////////////////////////////////
#include "pointHierarchy.h"
#include "error.h"
///////////////////////////////////////////////////////////////////////
// Class : CPointHierarchy
// Method : CPointHierarchy
// Description : Ctor
// Return Value :
// Comments :
CPointHierarchy::CPointHierarchy(const char *n,const float *from,const float *to,FILE *in) : CMapHierarchy<CPointCloudPoint>(), CTexture3d(n,from,to) {
// Try to read the point cloud
// Read the header
readChannels(in);
// Read the points
CMap<CPointCloudPoint>::read(in);
// Reserve the actual space
data.reserve(numItems*dataSize);
// Read the data
fread(data.array,sizeof(float),numItems*dataSize,in);
data.numItems = numItems*dataSize;
// Close the file
fclose(in);
// Compute the point hierarchy so that we can perform lookups
computeHierarchy();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointHierarchy
// Method : ~CPointHierarchy
// Description : Dtor
// Return Value :
// Comments :
CPointHierarchy::~CPointHierarchy() {
}
///////////////////////////////////////////////////////////////////////
// Class : CPointHierarchy
// Method : store
// Description : Store smtg
// Return Value :
// Comments :
void CPointHierarchy::store(const float *Cl,const float *Pl,const float *Nl,float dP) {
vector P,N;
mulmp(P,to,Pl);
mulmn(N,from,Nl);
dP *= dPscale;
// Should never be called
assert(FALSE);
}
///////////////////////////////////////////////////////////////////////
// Class : CPointHierarchy
// Method : lookup
// Description : Lookup smtg
// Return Value :
// Comments :
void CPointHierarchy::lookup(float *Cl,const float *Pl,const float *Nl,float dP) {
int *stack = (int *) alloca(100*sizeof(int));
int *stackBase = stack;
int i;
vector P,N;
// Transform the lookup point to the correct coordinate system
mulmp(P,to,Pl);
mulmn(N,from,Nl);
dP *= dP;
// Clear the data
for (i=0;i<dataSize;i++) Cl[i] = 0;
*stack++ = root;
while(stack > stackBase) {
const int currentNode = *(--stack);
// Is this a leaf ?
if (currentNode < 0) {
CPointCloudPoint *item = CMap<CPointCloudPoint>::items - currentNode;
vector D;
subvv(D,item->P,P);
// Sum this item
if ( (dotvv(D,N) < 0) && (dotvv(D,item->N) < 0) ) { // map normals are the other way round
Cl[0] += (float) (C_PI*item->dP*item->dP/dotvv(D,D));
}
} else {
CMapNode *node = nodes.array + currentNode;
CPointCloudPoint *average = CMap<CPointCloudPoint>::items + node->average;
// Decide whether we want to split this node
vector D;
subvv(D,average->P,P);
// Compare the code angle to maximum solid angle
const float distSq = dotvv(D,D);
const float dParea = (float) (C_PI*average->dP*average->dP);
if ( (lengthv(D) > average->dP) && ((dParea / distSq) < 0.05) ) {
//if ( ((dParea / distSq) < 0.05) ) {
if ( (dotvv(D,N) < 0) && (dotvv(D,average->N) < 0) ) { // map normals are the other way round
// Use the average
Cl[0] += (float) (C_PI*average->dP*average->dP/dotvv(D,D));
}
} else {
// Sanity check
assert((stack-stackBase) < 98);
// Split
*stack++ = node->child0;
*stack++ = node->child1;
}
}
}
// FIXME: we should be weighting averages using the occlusion factor
// to avoid double-shadowing
Cl[0] /= (float) (4*C_PI);
}
<commit_msg>normals were reversed due to stupid test-case shader<commit_after>//////////////////////////////////////////////////////////////////////
//
// Pixie
//
// Copyright 1999 - 2003, Okan Arikan
//
// Contact: okan@cs.utexas.edu
//
// 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
//
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
//
// File : pointHierarchy.cpp
// Classes : CPointHierarchy
// Description :
//
////////////////////////////////////////////////////////////////////////
#include "pointHierarchy.h"
#include "error.h"
///////////////////////////////////////////////////////////////////////
// Class : CPointHierarchy
// Method : CPointHierarchy
// Description : Ctor
// Return Value :
// Comments :
CPointHierarchy::CPointHierarchy(const char *n,const float *from,const float *to,FILE *in) : CMapHierarchy<CPointCloudPoint>(), CTexture3d(n,from,to) {
// Try to read the point cloud
// Read the header
readChannels(in);
// Read the points
CMap<CPointCloudPoint>::read(in);
// Reserve the actual space
data.reserve(numItems*dataSize);
// Read the data
fread(data.array,sizeof(float),numItems*dataSize,in);
data.numItems = numItems*dataSize;
// Close the file
fclose(in);
// Compute the point hierarchy so that we can perform lookups
computeHierarchy();
}
///////////////////////////////////////////////////////////////////////
// Class : CPointHierarchy
// Method : ~CPointHierarchy
// Description : Dtor
// Return Value :
// Comments :
CPointHierarchy::~CPointHierarchy() {
}
///////////////////////////////////////////////////////////////////////
// Class : CPointHierarchy
// Method : store
// Description : Store smtg
// Return Value :
// Comments :
void CPointHierarchy::store(const float *Cl,const float *Pl,const float *Nl,float dP) {
vector P,N;
mulmp(P,to,Pl);
mulmn(N,from,Nl);
dP *= dPscale;
// Should never be called
assert(FALSE);
}
///////////////////////////////////////////////////////////////////////
// Class : CPointHierarchy
// Method : lookup
// Description : Lookup smtg
// Return Value :
// Comments :
void CPointHierarchy::lookup(float *Cl,const float *Pl,const float *Nl,float dP) {
int *stack = (int *) alloca(100*sizeof(int));
int *stackBase = stack;
int i;
vector P,N;
// Transform the lookup point to the correct coordinate system
mulmp(P,to,Pl);
mulmn(N,from,Nl);
dP *= dP;
// Clear the data
for (i=0;i<dataSize;i++) Cl[i] = 0;
*stack++ = root;
while(stack > stackBase) {
const int currentNode = *(--stack);
// Is this a leaf ?
if (currentNode < 0) {
CPointCloudPoint *item = CMap<CPointCloudPoint>::items - currentNode;
vector D;
subvv(D,item->P,P);
// Sum this item
if ( (dotvv(D,N) > 0) && (dotvv(D,item->N) < 0) ) {
Cl[0] += (float) (C_PI*item->dP*item->dP/dotvv(D,D));
}
} else {
CMapNode *node = nodes.array + currentNode;
CPointCloudPoint *average = CMap<CPointCloudPoint>::items + node->average;
// Decide whether we want to split this node
vector D;
subvv(D,average->P,P);
// Compare the code angle to maximum solid angle
const float distSq = dotvv(D,D) + C_EPSILON;
const float dParea = C_PI*average->dP*average->dP;
if ( (lengthv(D) > average->dP) && ((dParea / distSq) < 0.05) ) {
//if ( ((dParea / distSq) < 0.05) ) {
if ( (dotvv(D,N) > 0) && (dotvv(D,average->N) < 0) ) {
// Use the average
Cl[0] += (float) (C_PI*average->dP*average->dP/dotvv(D,D));
}
} else {
// Sanity check
assert((stack-stackBase) < 98);
// Split
*stack++ = node->child0;
*stack++ = node->child1;
}
}
}
// FIXME: we should be weighting averages using the occlusion factor
// to avoid double-shadowing
Cl[0] /= (float) (4*C_PI);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.